伪代码:
int arr[ 5 ] = { 4, 1, 3, 2, 6 }, x;
x = find(3).arr ;
x 会返回 2。
最佳答案
你的函数的语法没有意义(为什么返回值会有一个名为 arr
的成员?)。
要查找索引,请使用 std::distance
和 std::find
来自 <algorithm>
标题。
int x = std::distance(arr, std::find(arr, arr + 5, 3));
或者你可以把它变成一个更通用的函数:
template <typename Iter>
size_t index_of(Iter first, Iter last, typename const std::iterator_traits<Iter>::value_type& x)
{
size_t i = 0;
while (first != last && *first != x)
++first, ++i;
return i;
}
在这里,如果找不到值,我将返回序列的长度(这与 STL 算法返回最后一个迭代器的方式一致)。根据您的喜好,您可能希望使用其他形式的故障报告。
在你的情况下,你会像这样使用它:
size_t x = index_of(arr, arr + 5, 3);
关于c++ - 如何在数组中找到特定值并返回其索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3909784/