【问题标题】:Returning iterator index on an array search返回数组搜索的迭代器索引
【发布时间】:2016-02-07 20:32:24
【问题描述】:

我想搜索一个特定的数字并让一个迭代器跟踪正在测试的数组元素。如果找到数字,我想返回找到数字的数组的索引。到目前为止,这是我所拥有的:

    vector<int>::iterator iterator;
    find(vector.begin(),vector.end(), num);

    if(//the number is found in the search)
    {
       return //where the number is found
    }

我不太确定如何将迭代器与正在测试的数组元素同步。如果可能的话,我将不胜感激任何帮助解决这个问题。

【问题讨论】:

  • “数组的地址”是什么意思?你想返回元素的内存地址还是仅仅返回它的索引?
  • 查看std::find() 的任何示例。然后,取消引用迭代器会为您提供一个引用,并获取它的地址给您它的地址。我宁愿使用迭代器,而不是不必要地使用指针。另外,请考虑使用引用,尽管在找不到元素的情况下需要例外。

标签: c++ arrays iterator


【解决方案1】:

这应该做你想做的:

std::vector<int> v = {500, 600, 700};
auto it = std::find(v.begin(),v.end(), 600);
std::size_t pos = it - v.begin(); //found(iterator) - begin(iterator)

// of course first you should check if (it != v.end())

【讨论】:

    猜你喜欢
    • 2015-01-13
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 2014-06-13
    • 1970-01-01
    • 2021-03-18
    相关资源
    最近更新 更多