如何在数组中查找特定值并返回其索引? [英] How do I find a particular value in an array and return its index?

查看:43
本文介绍了如何在数组中查找特定值并返回其索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伪代码:

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

x = find(3).arr ; 

x 将返回 2.

推荐答案

你的函数的语法没有意义(为什么返回值会有一个名为 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);

这篇关于如何在数组中查找特定值并返回其索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆