我正在尝试打印出我的 powerSet
的内容,这是一组给定的集合,但是当我尝试遍历我的 powerSet
时,我得到<< 二进制“<<”的 C2679 错误,具有以下功能。
template <typename T>
void writePowerSet(const set<set<T>>& pSet)
{
for(typename set< set<T> >::const_iterator itr = pSet.begin(); itr != pSet.end(); itr++)
{
cout << *itr;
}
}
我知道为了打印一个集合,您必须遍历它并引用迭代器,但这就是产生我的错误的原因。 有没有不同的方法来处理它?</p>
最佳答案
pSet
是 std::set<std::set<T>>
类型的引用, 所以 *itr
将是 std::set<T>
类型的引用.您正在尝试使用 std::ostream
过载 <<
在这种类型上。然而,标准库容器没有定义这样的重载。
如果要打印内部集合的所有元素,还需要对其进行迭代:
template <typename T>
void writePowerSet(const std::set<std::set<T>>& pSet)
{
for(const auto& s : pSet)
{
for(const auto& x : s)
{
std::cout << x;
}
}
}
这里我使用基于范围的 for 循环,因为它更容易编写和阅读。输出看起来不太好,在你喜欢的地方添加额外的输出。
这也假设 <<
为内部类型定义了重载 T
.
关于c++ - 如何使用迭代器打印一组集合中的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53365403/