2017-06-28 232 views
0

我試圖打印出一組列表,但我混淆了語法。我希望每一集都在一個新的線上。這裏是我的代碼:C++打印一組列表

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 
} 

我試圖打印指針到迭代器時出現錯誤。很確定,因爲我在列表中使用了一個集合,但是我不知道輸出這個列表的正確語法。

+0

什麼是錯誤,你想如何設置打印? – Ryan

+0

@Ryan沒有運算符匹配這些操作數std :: set ,std :: allocator >,正如我所說我希望每個集合都打印在一個新行上並且每個set元素由一個太空 – Daoud

回答

3

是否要打印如下?

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 
+0

完美,謝謝! – Daoud

1

沒有爲std::set沒有operator <<超載,你必須自己寫循環(也可能是創建一個功能)

隨着範圍,你可能只是:

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