【问题标题】:vector<string>::iterator - how to find position of an elementvector<string>::iterator - 如何找到元素的位置
【发布时间】:2013-10-26 20:06:10
【问题描述】:

我正在使用以下代码在 std::vectorstring 类型中查找字符串。但是如何返回特定元素的位置呢?

代码:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
    vector<string> vec;
    vector<string>::iterator it;

    vec.push_back("H");
    vec.push_back("i");
    vec.push_back("g");
    vec.push_back("h");
    vec.push_back("l");
    vec.push_back("a");
    vec.push_back("n");
    vec.push_back("d");
    vec.push_back("e");
    vec.push_back("r");

    it=find(vec.begin(),vec.end(),"r");
    //it++;

    if(it!=vec.end()){
        cout<<"FOUND AT : "<<*it<<endl;
    }
    else{
        cout<<"NOT FOUND"<<endl;
    }
    return 0;
}

输出:

FOUND AT : r

预期输出:

FOUND AT : 9

【问题讨论】:

标签: c++ stl iterator stdvector


【解决方案1】:

您可以为此使用std::distance

auto pos = std::distance(vec.begin(), it);

对于std::vector::iterator,您还可以使用算术:

auto pos = it - vec.begin();

【讨论】:

  • 谢谢!只是出于好奇,如果我的向量包含1000 elements 并使用find 会更快还是我需要使用某种pointer to array
  • @user2754070 你必须测量它,但我怀疑在优化的构建中你会比find 更快。
【解决方案2】:

使用以下:

if(it != vec.end())
   std::cout<< "Found At :" <<  (it-vec.begin())  ;

【讨论】:

    【解决方案3】:
    #include <iostream>
    #include <algorithm>
    #include <vector>
    
    using namespace std;
    
    int main() {
        vector<string> vec;
        vector<string>::iterator it;
    
        vec.push_back("H");
        vec.push_back("i");
        vec.push_back("g");
        vec.push_back("h");
        vec.push_back("l");
        vec.push_back("a");
        vec.push_back("n");
        vec.push_back("d");
        vec.push_back("e");
        vec.push_back("r");
    
        it=find(vec.begin(),vec.end(),"a");
        //it++;
        int pos = distance(vec.begin(), it);
    
        if(it!=vec.end()){
            cout<<"FOUND  "<< *it<<"  at position: "<<pos<<endl;
        }
        else{
            cout<<"NOT FOUND"<<endl;
        }
        return 0;
    

    【讨论】:

    • 一些解释会有所帮助
    【解决方案4】:

    使用这个语句:

    it = find(vec.begin(), vec.end(), "r") - vec.begin();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-28
      • 1970-01-01
      • 2013-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-14
      • 2011-02-26
      相关资源
      最近更新 更多