我有一个字符串向量.我希望能够搜索该向量的字符串,如果我在向量中得到匹配,我希望能够返回位置,例如向量中项目的向量索引.
这是我试图解决问题的代码:
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的索引值吗?
用途std::distance:
uint32_t index = std::distance(std::begin(_sActorTypes), itr);
Run Code Online (Sandbox Code Playgroud)
您应该检查返回值find到end()第一,不过,以确保它实际上找到.您也可以使用减法,因为std::vector使用随机访问迭代器,但减法不适用于所有容器,例如std::list,使用双向迭代器.
| 归档时间: |
|
| 查看次数: |
205 次 |
| 最近记录: |