如何获取CMake列表中的最大元素?

huangapple go评论73阅读模式
英文:

How can I get the highest element in a CMake list?

问题

我有一个CMake列表(字面上或在一个变量中),我想要获取具有最大值的列表项。我应该如何做到这一点?

注意:列表不一定是排序的,也不一定是不重复的。

英文:

I have a CMake list (literally or in a variable), and I want to obtain the list item with the maximum value. How should I do this?

Note: The list is not necessarily sorted, nor necessarily duplicate-free.

答案1

得分: 1

自 CMake 版本 3.18 开始,您应该能够使用 list(SORT) 来获取一个排序后的元素列表,从而轻松提取最大的元素。也许不如通过列表进行搜索高效,但对于预期的输入大小可能没有太大区别:

function(max_element OUT_VAR)
	list(SORT ARGN COMPARE NATURAL ORDER DESCENDING)
	list(GET ARGN 0 MAX_ELEMENT)
	set(${OUT_VAR} ${MAX_ELEMENT} PARENT_SCOPE)
endfunction()

max_element(MAX 10 4 19 1)
message("MAX = ${MAX}") # 打印 "MAX = 19"
英文:

Starting CMake version 3.18 you should be able to use list(SORT) for getting a sorted list of elements making it simple to extract the maximum one. Perhaps not as efficient as a search through a list, but for the expected input sizes probably makes little difference:

function(max_element OUT_VAR)
	list(SORT ARGN COMPARE NATURAL ORDER DESCENDING)
	list(GET ARGN 0 MAX_ELEMENT)
	set(${OUT_VAR} ${MAX_ELEMENT} PARENT_SCOPE)
endfunction()

max_element(MAX 10 4 19 1)
message("MAX = ${MAX}") # prints "MAX = 19"

答案2

得分: 0

我不知道有一个CMake命令可以获取最大的元素,但你可以自己编写一个函数来实现这个功能:

function(max out_var)
    list(GET ARGN 0 ${out_var})
    list(SUBLIST ARGN 1 -1 tail)
    foreach(val ${tail})
        if (${val} GREATER ${out_var})
            set(${out_var} ${val})
        endif()
    endforeach()
    return(PROPAGATE ${out_var})
endfunction()

你可以这样调用它:

max(out1 1 2 3 5 4 5 3)
# out1 现在是 "5"
set(my_list 7 3 5)
max(out2 ${my_list})
# out2 现在是 "7"

更多阅读资料:

英文:

I don't know of a CMake command that gets you the maximum element, but you can write your own function for getting this:

function(max out_var)
    list(GET ARGN 0 ${out_var})
    list(SUBLIST ARGN 1 -1 tail)
    foreach(val ${tail})
        if (${val} GREATER ${out_var})
            set(${out_var} ${val})
        endif()
    endforeach()
    return(PROPAGATE ${out_var})
endfunction()

You invoke it like so:

max(out1 1 2 3 5 4 5 3)
# out1 is now "5"
set(my_list 7 3 5)
max(out2 ${my_list})
# out2 is now "7"

Further reading:

huangapple
  • 本文由 发表于 2023年7月23日 23:43:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76749101.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定