I have a vector of string. I want to be able to search that vector for a string and if I get a match in the vector, I’d like to be able to return the position e.g. the vector index of the item in the vector.
Here’s the code I’m trying to solve the problem for:
enum ActorType { at_none, at_plane, at_sphere, at_cylinder, at_cube, at_skybox, at_obj, at_numtypes };
class ActorTypes
{
private:
std::vector<std::string> _sActorTypes;
public:
ActorTypes()
{
// initializer lists don't work in vs2012 :/
using std::string;
_sActorTypes.push_back( string("plane") );
_sActorTypes.push_back( string("sphere") );
_sActorTypes.push_back( string("cylinder") );
_sActorTypes.push_back( string("cube") );
_sActorTypes.push_back( string("skybox") );
_sActorTypes.push_back( string("obj") );
}
const ActorType FindType( const std::string & s )
{
auto itr = std::find( _sActorTypes.cbegin(), _sActorTypes.cend(), s );
uint32_t nIndex = ???;
// I want to be able to do the following
return (ActorType) nIndex;
}
};
I know I can just write a for loop and return the for loop index that I find the match at, but I was wondering for the more general case – can I get the index value of a vector::iterator ??
Use
std::distance:You should check the return value of
findtoend()first, though, to make sure it’s actually found. You could also use subtraction sincestd::vectoruses a random-access iterator, but subtraction will not work for all containers, such asstd::list, which uses a bidirectional iterator.