C++ vector<string>::iterator - 如何找到元素的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19441875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:49:21  来源:igfitidea点击:

vector<string>::iterator - how to find position of an element

c++stliteratorstdvector

提问by user2754070

I am using the following code to find a string in an std::vectorof stringtype. But how to return the position of particular element?

我使用下面的代码找到一个字符串std::vectorstring类型。但是如何返回特定元素的位置?

Code:

代码:

#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;
}

Output:

输出:

FOUND AT : r

FOUND AT : r

Expected Output:

预期输出:

FOUND AT : 9

FOUND AT : 9

回答by juanchopanza

You can use std::distancefor that:

你可以使用std::distance

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

For an std::vector::iterator, you can also use arithmetic:

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

auto pos = it - vec.begin();

回答by P0W

Use following :

使用以下:

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

回答by Pingakshya Goswami

#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;

回答by keep_smiling

Use this statement:

使用这个语句:

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