2

文字列のベクトルがあります。そのベクトルで文字列を検索できるようにしたいのですが、ベクトルで一致するものが見つかった場合は、ベクトル内のアイテムのベクトルインデックスなどの位置を返すことができるようにしたいと思います。

これが私が問題を解決しようとしているコードです:

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;
    }       
};

forループを記述して、一致するforループインデックスを返すことができることはわかっていますが、もっと一般的なケースを考えていました-vector :: iteratorのインデックス値を取得できますか?

4

2 に答える 2

8

使用std::distance

uint32_t index = std::distance(std::begin(_sActorTypes), itr);

findただし、最初にtoの戻り値をチェックして、end()実際に見つかったことを確認する必要があります。std::vectorランダムアクセスイテレータを使用するため、減算を使用することもできますがstd::list、双方向イテレータを使用するなど、すべてのコンテナで減算が機能するわけではありません。

于 2012-11-28T21:26:23.187 に答える
4

std :: distance:を使用できます

auto itr = std::find( _sActorTypes.cbegin(), _sActorTypes.cend(), s );
uint32_t nIndex = std::distance(_sActorTypes.cbegin(), itr);
于 2012-11-28T21:26:34.707 に答える