c++ - 使用 'std::algorithm' 无显式循环迭代自定义对的 vector

标签 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<
    }
};

我声明了这些自定义对的 vector ,我正在尝试使用 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(), [&](){});
}

最佳答案

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

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

关于c++ - 使用 'std::algorithm' 无显式循环迭代自定义对的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25477814/

相关文章:

c++ - 编译时用整数替换字符串常量

c++ - 将数组作为值传递的函数中基于范围的 for 循环

c++ - 在将参数传递给基类时使用 std::move()

c++ - 智能指针 : Does a 'base' part of an object get created?

c++ - PCRE多行匹配问题

c++ - std::vector 与 std::list 与 std::slist 的相对性能?

c++ - 为什么以下代码不调用 std::string 的移动构造函数?

c++ - visual studio 和 gcc 的 const 引用语法区别

c++ - 关于 std::thread 中的 C++ 自动类型转换行为

c++ - 从纯抽象基类继承 typedef