[英]C++ printing a list of sets
I'm trying to print out a list of sets but I'm confused with the syntax. 我试图打印出一组列表,但是我对语法感到困惑。 I want each set to be on a new line.
我希望每组都换一个新行。 Here is my code:
这是我的代码:
set<int> set1 = { 2, 4, 5 };
set<int> set2 = { 4, 5 };
list<set<int>> list1;
list<set<int>>::iterator it = list1.begin();
list1.insert(it, set1);
list1.insert(it, set2);
cout << "List contents:" << endl;
for (it = list1.begin(); it != list1.end(); ++it)
{
cout << *it; //error is here
}
I'm getting an error when trying to print the pointer to the iterator. 尝试将指针打印到迭代器时出现错误。 Pretty sure its because I'm using a set inside of the list, but I don't know the proper syntax for outputting this list.
可以肯定,因为我在列表中使用了set,但是我不知道输出此列表的正确语法。
Do you want to print as following? 您要打印以下内容吗?
for (it = list1.begin(); it != list1.end(); ++it)
{
for (set<int>::iterator s = it->begin(); s != it->end(); s++) {
cout << *s << ' ';
}
cout << endl;
}
output: 输出:
List contents:
2 4 5
4 5
There is no overload of operator <<
for std::set
, you have to write the loop yourself (and possibly creating a function for that) std::set
没有operator <<
重载,您必须自己编写循环(并可能为此创建一个函数)
With for range, you may simply do: 使用for range,您可以简单地执行以下操作:
for (const auto& s : list1) {
for (int i : s) {
std::cout << i << ' ';
}
std::cout << std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.