【问题标题】:C++ printing a list of setsC++ 打印集合列表
【发布时间】:2017-06-28 04:48:27
【问题描述】:

我正在尝试打印一组集合列表,但我对语法感到困惑。我希望每组都在一个新的线上。这是我的代码:

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
}

尝试打印指向迭代器的指针时出现错误。很确定,因为我在列表中使用了一个集合,但我不知道输出这个列表的正确语法。

【问题讨论】:

  • 错误是什么,您希望如何打印该集合?
  • @Ryan 没有运算符匹配这些操作数 std::set,std::allocator>,正如我所说,我希望每个集合都被打印出来在新行上,每个集合元素用空格分隔

标签: c++ list iterator set


【解决方案1】:

您要打印如下吗?

  for (it = list1.begin(); it != list1.end(); ++it)
  {
      for (set<int>::iterator s = it->begin(); s != it->end(); s++) {                                                        
          cout << *s << ' ';
      }
      cout << endl;
  }

输出:

List contents:
2 4 5
4 5

【讨论】:

    【解决方案2】:

    operator &lt;&lt; 没有重载 std::set,您必须自己编写循环(并可能为此创建一个函数)

    使用 for range,您可以简单地这样做:

    for (const auto& s : list1) {
        for (int i : s) {
            std::cout << i << ' ';
        }
        std::cout << std::endl;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 2019-04-26
      相关资源
      最近更新 更多