将迭代器转换为int

时间:2011-05-26 09:25:33

标签: c++ vector iterator

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

我正在尝试在向量中找到元素的索引。 iterators可以,但我希望它为int。我该怎么办?

5 个答案:

答案 0 :(得分:25)

您可以使用std::distance

i = std::distance( names.begin(), std::find( names.begin(), names.end(), s ) );

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

if( i == names.size() )
    // index out of bounds!

在使用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 );

答案 1 :(得分: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
}

答案 2 :(得分:1)

尝试

i = (find( names.begin(), names.end(), s ) - names.begin());  

编辑: 虽然您应该考虑使用vector :: size_type而不是int。

答案 3 :(得分:1)

我对您的代码做出的假设:

using std::vector;
using std::cout;
using std::string;

如果我的假设是正确的,那么您可以在find的开头和distance之间vector iterator(基本上是vector的索引你可以找到这样的元素):

using std::distance;

像这样...

vector<string>::iterator i = find(names.begin(), names.end(), s);
if (i != names.end())
{
    cout << "Index " << std::distance(names.begin(), i);
}
else
{
    cout << s << "not found";
}

答案 4 :(得分:0)

您可以解除引用迭代器

int i = *name;
相关问题