gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:29:12 24 4
gpt4 key购买 nike

我写了自己的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com