从 c++ 列表库中打印出列表的内容
Printing out contents of a list from the c++ list library
我想打印出我正在编写的简单程序的列表内容。我正在使用内置列表库
#include <list>
但是,我不知道如何打印出此列表的内容以测试/检查其中的数据。我该怎么做?
如果你有一个最新的编译器(一个至少包含几个C++11功能(,你可以避免处理迭代器(直接(。对于像 int
s 这样的"小"事情的列表,您可以执行以下操作:
#include <list>
#include <iostream>
int main() {
list<int> mylist = {0, 1, 2, 3, 4};
for (auto v : mylist)
std::cout << v << "n";
}
如果列表中的项较大(具体而言,大到足以避免复制它们(,则需要在循环中使用引用而不是值:
for (auto const &v : mylist)
std::cout << v << "n";
尝试:
#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, " "));
}
例如,对于 int 的列表
list<int> lst = ...;
for (list<int>::iterator i = lst.begin(); i != lst.end(); ++i)
cout << *i << endl;
如果您正在使用列表,您最好尽快习惯迭代器。
您使用迭代器。
for(list<type>::iterator iter = list.begin(); iter != list.end(); iter++){
cout<<*iter<<endl;
}
您可以使用迭代器和一个小的for
循环。由于您只是输出列表中的值,因此您应该使用const_iterator
而不是iterator
来防止意外修改迭代器引用的对象。
下面是如何遍历变量var
的示例,
int
的列表 for (list<int>::const_iterator it = var.begin(); it != var.end(); ++it)
cout << *it << endl;
相关文章:
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- LNK2038、MSVS2017 MAGMA的原因列表
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 没有为自己的结构调用列表推回方法
- 使用简单类型列表实现的指数编译时间.为什么
- 一对向量构造函数:初始值设定项列表与显式构造
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 通过for循环使用用户输入填充列表
- C++:如何使函数只返回作为列表一部分的字符串
- 概念中的cv限定符需要表达式参数列表
- 下面是我为检测链接列表中的循环而制作的代码
- 建议在运行时将带有类实例的列表从c++导入qml
- 如何维护资源管理器项目视图中当前可见的项目列表
- 在卡萨布兰卡形成编码参数的列表
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题