从 c++ 列表库中打印出列表的内容

Printing out contents of a list from the c++ list library

本文关键字:列表 c++ 打印      更新时间:2023-10-16

我想打印出我正在编写的简单程序的列表内容。我正在使用内置列表库

#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;