2013-02-25 80 views
3

我有一個類Attribute與財產std::string attributeName。我想開發一個簡單的函數,它返回Attribute的索引,該索引的attributeName與提供的字符串匹配。不幸的限制包括:我沒有使用C++ 0x,並且我已經爲更復雜的東西重載了Attribute ==運算符。任何幫助將不勝感激,謝謝!如何根據類屬性查找矢量中的對象?

編輯 - 我很抱歉,我意識到它不清楚,有一個我正在尋找的屬性的向量。vector<Attribute> aVec

+0

通過getter訪問名稱是不可能的? – Gjordis 2013-02-25 09:04:35

+0

是否可以有多個具有相同屬性值的對象?你想要一組結果還是第一場比賽?矢量可以重新排序嗎?性能是否重要? – 2013-02-25 09:16:01

回答

8

使用std::find_if使用自定義function object

class FindAttribute 
{ 
    std::string name_; 

public: 
    FindAttribute(const std::string& name) 
     : name_(name) 
     {} 

    bool operator()(const Attribute& attr) 
     { return attr.attributeName == name_; } 
}; 

// ... 

std::vector<Attribute> attributes; 
std::vector<Attribute>::iterator attr_iter = 
    std::find_if(attributes.begin(), attributes.end(), 
     FindAttribute("someAttrName")); 
if (attr_iter != attributes.end()) 
{ 
    // Found the attribute named "someAttrName" 
} 

要做到這一點在C++ 11,它實際上沒有什麼不同,但你顯然不需要一個函數對象,或有聲明迭代器類型:

std::vector<Attribute> attributes; 

// ... 

auto attr_iter = std::find_if(std::begin(attributes), std::end(attributes), 
    [](const Attribute& attr) -> bool 
    { return attr.attributeName == "someAttrName"; }); 

或者,如果你需要用不同的名字這個多次做,創建lambda函數作爲一個變量,並使用在電話到std::find_if

auto attributeFinder = 
    [](const Attribute& attr, const std::string& name) -> bool 
    { return attr.attributeName == name; }; 

// ... 

using namespace std::placeholders; // For `_1` below 

auto attr_iter = std::find_if(std::begin(attributes), std::end(attributes), 
    std::bind(attributeFinder, _1, "someAttrName")); 
+0

太棒了,謝謝! – user2012732 2013-02-25 09:12:02

+0

你能否把答案放在現代C++中呢? – 2013-02-25 09:16:19

+1

@PeterWood新增。 – 2013-02-25 09:38:36

0

您也可以使用綁定功能從boost庫:

std::vector<Attribute>::iterator it = std::find_if(
    aVec.begin(), 
    aVec.end(), 
    boost::bind(&Attribute::attributeName, _1) == "someValue" 
); 

或C++ 11的綁定功能:

std::vector<Attribute>::iterator it = std::find_if(
    aVec.begin(), 
    aVec.end(), 
    std::bind(
     std::equal_to<std::string>(), 
     std::bind(&Attribute::attributeName, _1), 
     "someValue" 
    ) 
); 

不宣謂語類或函數

1

你可以簡單地使用for循環來達到這個目的:

for (int i = 0; i<aVec.size();i++) 
{ 
    if(aVec[i].attributeName == "yourDesiredString") 
    { 
     //"i" is the index of your Vector.  
    } 
} 
相關問題