如何在数组中找到特定值并返回其索引?

rec*_*gle 20 c++ arrays

伪代码:

int arr[ 5 ] = { 4, 1, 3, 2, 6 }, x;

x = find(3).arr ; 
Run Code Online (Sandbox Code Playgroud)

然后x将返回2.

Pet*_*der 44

你在函数中使用的语法没有意义(为什么返回值会有一个名为arr?的成员).

要查找索引,使用std::distancestd::find<algorithm>报头.

int x = std::distance(arr, std::find(arr, arr + 5, 3));
Run Code Online (Sandbox Code Playgroud)

或者你可以把它变成一个更通用的功能:

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;
}
Run Code Online (Sandbox Code Playgroud)

在这里,如果找不到值,我将返回序列的长度(这与STL算法返回最后一个迭代器的方式一致).根据您的喜好,您可能希望使用其他形式的故障报告.

在你的情况下,你会像这样使用它:

size_t x = index_of(arr, arr + 5, 3);
Run Code Online (Sandbox Code Playgroud)


Bri*_*ian 12

这是一种非常简单的手工操作方法.<algorithm>正如彼得所说,你也可以使用它.

#include <iostream>
int find(int arr[], int len, int seek)
{
    for (int i = 0; i < len; ++i)
    {
        if (arr[i] == seek) return i;
    }
    return -1;
}
int main()
{
    int arr[ 5 ] = { 4, 1, 3, 2, 6 };
    int x = find(arr,5,3);
    std::cout << x << std::endl;    
}
Run Code Online (Sandbox Code Playgroud)