我可以读取vector <string> :: iterator的数字位置吗?

fis*_*ood 2 c++ iterator

我有一个字符串向量.我希望能够搜索该向量的字符串,如果我在向量中得到匹配,我希望能够返回位置,例如向量中项目的向量索引.

这是我试图解决问题的代码:

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;
    }       
};
Run Code Online (Sandbox Code Playgroud)

我知道我可以写一个for循环并返回我找到匹配的for循环索引,但我想知道更一般的情况 - 我能得到vector :: iterator的索引值吗?

chr*_*ris 8

用途std::distance:

uint32_t index = std::distance(std::begin(_sActorTypes), itr);
Run Code Online (Sandbox Code Playgroud)

您应该检查返回值findend()第一,不过,以确保它实际上找到.您也可以使用减法,因为std::vector使用随机访问迭代器,但减法不适用于所有容器,例如std::list,使用双向迭代器.

  • @chris:在一般情况下(即对于标准容器)`std :: begin`只返回`container.begin()`,因此给定一个非const容器,将返回`iterator`,并给出一个const容器a将返回`const_iterator`.如果`ActorTypes :: FindType`是`const`(因为它_should_是),你的代码将按原样运行,因为`_sActorTypes`在上下文中将是const. (2认同)