将迭代器转换为int

the*_*ux4 10 c++ iterator vector

int i;
vector<string> names;
string s = "penny";
names.push_back(s);
i = find(names.begin(), names.end(), s);
cout << i;
Run Code Online (Sandbox Code Playgroud)

我正在尝试在向量中找到元素的索引.没关系iterators,但我想要它int.我该怎么做?

CB *_*ley 25

你可以用std::distance它.

i = std::distance( names.begin(), std::find( names.begin(), names.end(), s ) );
Run Code Online (Sandbox Code Playgroud)

但是,您可能希望检查您的索引是否超出范围.

if( i == names.size() )
    // index out of bounds!
Run Code Online (Sandbox Code Playgroud)

但是,在使用std :: distance之前,使用迭代器执行此操作可能更清楚.

std::vector<std::string>::iterator it = std::find( names.begin(), names.end(), s );

if( it == names.end() )
     // not found - abort!

// otherwise...
i = std::distance( names.begin(), it );
Run Code Online (Sandbox Code Playgroud)


Geo*_*che 5

std::vector<string>::iterator it = std::find(names.begin(), names.end(), s);
if (it != names.end()) {
    std::cout << std::distance(names.begin(), it);
} else {
    // ... not found
}
Run Code Online (Sandbox Code Playgroud)