[英]std::vector and std::list find_if and max_element performance
[英]find int inside struct with find_if for std::list with structs
如果列表包含結構,如何將find_if與std :: list一起使用? 我的第一個偽代碼嘗試如下:
typename std::list<Event>::iterator found =
find_if(cal.begin(), cal.last(), predicate);
這里的問題是該謂詞不是直接在列表中可見,而是在event.object.return_number()
內部。 我想如何引用嵌套在struct中並且需要訪問get方法的int。
在編譯器可能已經部分實現的C ++ 0x中,可以執行以下操作:
find_if(cal.begin(), cal.last(), [&](const Event& e)
{
return e.object.return_number() == value_to_find;
});
您可以使用函子類(類似於函數,但是允許您擁有狀態,例如配置):
class Predicate
{
public:
Predicate(int x) : x(x) {}
bool operator() (const Cal &cal) const { return cal.getter() == x; }
private:
const int x;
};
std::find_if(cal.begin(), cal.end(), Predicate(x));
您可以建立這樣的謂詞:
struct IsEventObjectReturnNumber
{
int num;
explicit IsEventObjectReturnNumber( int n ) : num( n ) {}
bool operator()(const Event & event ) const
{
return event.object.return_number() == num;
}
};
std::list<Event>::iterator = std::find_if(cal.begin(), cal.end(), IsEventObjectReturnNumber(x));
(不是那么簡單,但是)最簡單的方法(在沒有C ++ 11的情況下)是一個自定義比較器:
struct CompareMyStruct {
int n_;
CompareMyStruct(int n) : n_(n) { }
bool operator()(const Event& a) const {
return a.object.return_number() == n_;
}
};
typename std::list<Event>::iterator found =
find_if(cal.begin(), cal.last(), CompareMyStruct(123));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.