且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-12 13:53:56

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

The syntax you have there for your function doesn't make sense (why would the return value have a member called arr?).

要查找索引,请使用 标头中的 std::distancestd::find.

To find the index, use std::distance and std::find from the <algorithm> header.

int x = std::distance(arr, std::find(arr, arr + 5, 3));

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

Or you can make it into a more generic function:

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 算法返回最后一个迭代器的方式一致).根据您的喜好,您可能希望使用某种其他形式的故障报告.

Here, I'm returning the length of the sequence if the value is not found (which is consistent with the way the STL algorithms return the last iterator). Depending on your taste, you may wish to use some other form of failure reporting.

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

In your case, you would use it like so:

size_t x = index_of(arr, arr + 5, 3);