如何在std::array
不运行任何循环的情况下获取项目中的索引?
#include <iostream>
#include <array>
std::array<int, 10> some_array = { 89, 56, 78, 96, 4, 34, 77, 2, 48, 3};
unsigned int GetIndexOfValue(unsigned int some_value) {
// How get the index of some_value here without running a loop?
}
int main() {
unsigned int some_value = 34;
std::cout << "The index of value passed is " << GetIndexOfValue(some_value) << std::endl;
}
是否可以使用std::find
?
您可以使用<algorithm>
标头中的功能,因此可以避免编写原始循环,如下所示:
unsigned int GetIndexOfValue(unsigned int some_value) {
return std::distance(std::begin(some_array),
std::find(std::begin(some_array), std::end(some_array), some_value));
}
这是一个演示。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句