我想打印一份列表的内容,我正在编写一个简单的程序.我正在使用内置列表库
#include <list>
Run Code Online (Sandbox Code Playgroud)
但是,我不知道如何打印出这个列表的内容,以便测试/检查其中的数据.我该怎么做呢?
Jer*_*fin 12
如果你有一个最近的编译器(一个至少包含一些C++ 11特性的编译器),你可以避免处理迭代器(直接),如果你想:
#include <list>
#include <iostream>
int main() {
list<int> mylist = {0, 1, 2, 3, 4};
for (auto v : mylist)
std::cout << v << "\n";
}
Run Code Online (Sandbox Code Playgroud)
尝试:
#include <list>
#include <algorithm>
#include <iterator>
#include <iostream>
int main()
{
list<int> l = {1,2,3,4};
// std::copy copies items using iterators.
// The first two define the source iterators [begin,end). In this case from the list.
// The last iterator defines the destination where the data will be copied too
std::copy(std::begin(l), std::end(l),
// In this case the destination iterator is a fancy output iterator
// It treats a stream (in this case std::cout) as a place it can put values
// So you effectively copy stuff to the output stream.
std::ostream_iterator<int>(std::cout, " "));
}
Run Code Online (Sandbox Code Playgroud)
您使用迭代器。
for(list<type>::iterator iter = list.begin(); iter != list.end(); iter++){
cout<<*iter<<endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43964 次 |
| 最近记录: |