2012-11-28 26 views
2

我有一個字符串的向量。我希望能夠搜索該矢量的字符串,如果我在矢量中找到匹配,我希望能夠返回該位置,例如矢量中項目的矢量索引。我可以讀取矢量<string> ::迭代器的數字位置嗎?

這裏是我試圖解決該問題的代碼:

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循環,並返回了,我覺得這場比賽在循環索引,但我想知道對於更一般的情況 - 我可以得到vector :: iterator的索引值嗎?

+1

'參數nIndex = ITR - _sActorTypes.cbegin();' – ildjarn

回答

8

使用std::distance

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

您應該檢查的find返回值來end()第一,雖然,以確保它實際上找到。您也可以使用減法,因爲std::vector使用隨機訪問迭代器,但減法不適用於所有容器,例如使用雙向迭代器的std::list

+0

出於某種原因,vs2012不喜歡的std ::開始(_sActorTypes),但確實喜歡_sActorType。開始()。無論如何,您的答案都能解決我的問題,謝謝! – fishfood

+0

@lapin,'std :: begin'是C++ 11。對我來說這是一種習慣的力量,對不起。兩者之間沒有太大的區別。 – chris

+0

可能只是VS2012編譯器:)謝謝 – fishfood

4

您可以使用std::distance

auto itr = std::find(_sActorTypes.cbegin(), _sActorTypes.cend(), s); 
uint32_t nIndex = std::distance(_sActorTypes.cbegin(), itr);