2012-08-17 50 views
6

假设我有以下代码:find_if和std ::对,但只是一个元素

std::vector< std::pair <int, char> > myVec; 
or 
std::list< std::pair <int, char> > myList; 
/* then ***************/ 
std::list< std::pair <int, char> >::iterator listIt; 
or 
std::vector< std::pair <int, char> >::iterator vectorIt; 

/* No difference between vector and list */ 

现在我需要搜索只是在其中一个int元素,所以:

vectorIt = std::find_if(myVec.begin(),myVect.end(),make_pair(.....)); 
                ^^^^^^^^^^^^^^^^^ 

我该怎么做?

+0

你有C++ 11或boost吗? – Flexo 2012-08-17 14:53:06

+0

您是用值还是谓词搜索? – ecatmur 2012-08-17 14:54:39

回答

13

编写一个采用std::pair的一元谓词,如果first元素等于给定值,则返回true。

例如:

struct CompareFirst 
{ 
    CompareFirst(int val) : val_(val) {} 
    bool operator()(const std::pair<int,char>& elem) const { 
    return val_ == elem.first; 
    } 
    private: 
    int val_; 
}; 

然后

// find first element with first == 42 
vectorIt = std::find_if(myVec.begin(),myVect.end(), CompareFirst(42)); 
11

它使用C++ 11个lambda表达式,并给予value要找到:

std::find_if(container.begin(), container.end(), 
    [&value](std::pair<int, char> const& elem) { 
    return elem.first == value; 
}); 

其中containermyVecmyList

Lambda表达式[&value](...){...}是临时表达式(的功能等同性很像可以传递“3 + 2”作为参数传递给一个int参数,它会被转换为函数对象(很像一个在juanchopanza的接听)编译器这样可以节省你打字,并保持你的代码本地化

+0

@Flexo错字。固定。 – TemplateRex 2012-08-17 14:57:16

+1

另一个错字? 'int'没有'first'。 – juanchopanza 2012-08-17 15:00:20

+1

@juanchopanza渴望在lambdas中拥有'auto' http://cpp-next.com/archive/2011/12/a-breakthrough-for-concepts/ – TemplateRex 2012-08-17 15:01:33

2
template <class T,class S> struct pair_equal_to : binary_function <T,pair<T,S>,bool> { 
    bool operator() (const T& y, const pair<T,S>& x) const 
    { 
     return x.first==y; 
    } 
}; 

为了找到你应该使用需要int值如下:。

int find_me = 1;//chenge the value as you want 
vector< pair <int, char> >::iterator it = 
     find_if(myVec.begin(),myVec.end(),bind1st(pair_equal_to<int,char>(),find_me)); 

例如:

int main() { 
    vector< pair <int, char> > myVec; 
    pair<int,char> p1 = make_pair(1,'a'); 
    pair<int,char> p2 = make_pair(2,'b'); 
    pair<int,char> p3 = make_pair(1,'c'); 
    myVec.push_back(p1); 
    myVec.push_back(p2); 
    myVec.push_back(p3); 
    vector< pair <int, char> >::iterator it = find_if(myVec.begin(),myVec.end(),bind1st(pair_equal_to<int,char>(),1)); 
    if (it == myVec.end()) { 
     cout << "not found\n"; 
    } 
    else { 
     cout<< "found - first instance is < " << it->first <<"," << it->second << " >"; 
    } 
     return 0; 
    } 
相关问题