vector <string> :: iterator - 如何查找元素的位置</string>

时间:2013-10-18 04:57:39

标签: c++ stl iterator stdvector

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

代码:

#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

3 个答案:

答案 0 :(得分:23)

您可以使用std::distance

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

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

auto pos = it - vec.begin();

答案 1 :(得分:3)

使用以下内容:

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

答案 2 :(得分: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;