使用'std :: algorithm'迭代自定义对的向量,没有显式循环

时间:2014-08-25 01:07:21

标签: c++ c++11

我写了自己的Pairs课程:

#include <string>
#include <utility>
template<class K, class V>
class MyPair : public std::pair<K, V>
{
public:
    MyPair(){};
    MyPair(const K & x, const V & y) : std::pair<K, V>(x, y) {} 
    friend bool operator==(const MyPair& p1, const MyPair &p2)
    {
        return p1.first == p2.first; // requires that type K implements operator=
    }
    bool operator() (const MyPair& p1, const MyPair &p2)
    {
        return ( p1.first < p2.first ); // requires that type K implements operator<
    }
};

并且我声明了这些自定义对的向量,我正在尝试使用std :: for_each函数来实现print()函数,但由于某种原因我不能这样做,我得到了所有有点错误,我觉得这可能是对自定义迭代器需求的二重奏? 如何在没有显式循环的情况下实现解决方案?

typedef typename std::vector<MyPair<std::string, int> > myVecType;
myVecType wordvec;
void WordVector::print() const
{
    std::for_each(wordvec.begin(), wordvec.end(), [&](){});
}

1 个答案:

答案 0 :(得分:1)

std::for_each()的谓词需要接受一个参数,因为每次迭代时该函数都会传递每个元素:

std::for_each(wordvec.begin(), wordvec.end(),
    [&] (MyPair<std::string, int>& p) { /* ... */ });
//       ^^^^^^^^^^^^^^^^^^^^^^^^^^^