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

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

问题描述

伪code:

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

x = find(3).arr ; 

十大将然后返回2。

x would then return 2.

推荐答案

你有没有为你的功能没有任何意义(为什么会返回值都称为成员的语法改编?)。

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

要查找索引,使用的std ::距离的std ::找到<算法方式>

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天全站免登陆