int i;
vector<string> names;
string s = "penny";
names.push_back(s);
i = find(names.begin(), names.end(), s);
cout << i;
I'm trying to find index of an element in vector. It's ok wi开发者_开发技巧th iterators
, but I want it as int
. How can I do it?
You can use std::distance
for this.
i = std::distance( names.begin(), std::find( names.begin(), names.end(), s ) );
You will probably want to check that your index isn't out of bounds, though.
if( i == names.size() )
// index out of bounds!
It's probably clearer to do this with the iterator before using std::distance, though.
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 );
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
}
try
i = (find( names.begin(), names.end(), s ) - names.begin());
Edit: Although you should consider using vector::size_type instead of an int.
Assumptions that I am making about your code:
using std::vector;
using std::cout;
using std::string;
If my assumptions are correct, then you can find
the distance
between the beginning of the vector
and the iterator
(essentially the index into the vector
at which you can find such element):
using std::distance;
Like so...
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";
}
You can just dereference your iterator
int i = *name;
精彩评论