【问题标题】:Printing out contents of a list from the c++ list library [duplicate]从c ++列表库中打印出列表的内容[重复]
【发布时间】:2013-04-26 06:02:23
【问题描述】:

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

#include <list>

但是,我不知道如何打印此列表的内容以测试/检查其中的数据。我该怎么做?

【问题讨论】:

  • #include &lt;list&gt; 单独不会创建任何列表。它只包含相关的头文件,但您仍然需要放置代码来创建、修改、打印等列表。 cppreference.com 有各种标准容器的示例代码,例如这里为std::listen.cppreference.com/w/cpp/container/list/push_back

标签: c++ list


【解决方案1】:

如果您有最新的编译器(至少包含一些 C++11 功能的编译器),您可以根据需要避免(直接)处理迭代器。对于像ints 这样的“小”事物列表,您可以执行以下操作:

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

【讨论】:

  • 感谢非常简洁的代码。我能问一下这种用法是否有一个名字——写auto v : mylist而不是auto itr = mylist.begin()?谢谢!
  • @yuqli:这是一个“基于范围的 for 循环”。
  • 谢谢 - 没想到在五年前的回答下会这么快回复:-)
【解决方案2】:

试试:

#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, " "));
}

【讨论】:

  • +1,但如果您解释其中的一些内容,这将是一个很好的答案。我怀疑 OP 是否能够掌握这里发生的事情。
  • 如果我读得很好,根据stackoverflow.com/questions/3804183/…,您提出的解决方案将在末尾添加一对多分隔符。这可能是也可能不是问题,仅供参考。
  • @quetzalcoatl:这是一个众所周知的问题。一种相当干净的解决方案是将ostream_iterator 替换为infix_ostream_iterator
【解决方案3】:

例如,对于一个 int 列表

list<int> lst = ...;
for (list<int>::iterator i = lst.begin(); i != lst.end(); ++i)
    cout << *i << endl;

如果您正在使用列表,您最好很快适应迭代器。

【讨论】:

    【解决方案4】:

    您使用迭代器。

    for(list<type>::iterator iter = list.begin(); iter != list.end(); iter++){
       cout<<*iter<<endl;
    }
    

    【讨论】:

      【解决方案5】:

      您可以为此使用迭代器和一个小的for 循环。由于您只是输出列表中的值,因此您应该使用 const_iterator 而不是 iterator 以防止意外修改迭代器引用的对象。

      这是一个如何遍历变量var 的示例,该变量是int 的列表

      for (list<int>::const_iterator it = var.begin(); it != var.end(); ++it)
          cout << *it << endl;
      

      【讨论】:

        猜你喜欢
        • 2022-08-08
        • 1970-01-01
        • 2023-03-28
        • 2016-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多