我遇到了以下问题:假设我有
pair<int, int> p(1,2)
vector<pair<int, int>> vec;
我想使用find来获得指向向量中元素p的迭代器
find(vec.begin(), vec.end(), p)
但它给了我错误
type 'std::__1::pair<int, int>' does not provide a call operator
我应该如何继续?
这是我使用过的,效果很好。
#include <iostream>
#include <vector>
#include <algorithm>
struct FindPair {
FindPair (int first, int second)
: m_first_value(first)
, m_second_value(second) { }
int m_first_value;
int m_second_value;
bool operator()
( const std::pair<int, int> &p ) {
return (p.first == m_first_value && p.second == m_second_value);
}
};
int main()
{
std::vector< std::pair<int, int> > myVec;
std::vector< std::pair<int, int> >::iterator it;
myVec.push_back(std::make_pair(1,1));
myVec.push_back(std::make_pair(1,2));
it = std::find_if(myVec.begin(), myVec.end(), FindPair(1, 2));
if (it != myVec.end())
{
// We Found it
std::cout << "Matched Found on Current Iterator!" << std::endl;
std::cout << "it.first: " << (*it).first << std::endl;
std::cout << "it.second: " << (*it).second << std::endl;
}
else
{
std::cout << "Nothing Matched!" << std::endl;
}
return 0;
}
输出:
Matched Found on Current Iterator!
it.first: 1
it.second: 2