【问题标题】:Random Integer List随机整数列表
【发布时间】:2011-08-11 23:54:57
【问题描述】:

如果我在一行上有一个由空格分隔的整数列表(例如:50 34 1 3423 5 345),那么将它们中的每一个设为单独的整数变量的最佳方法是什么 - 收集整数列表cin?

【问题讨论】:

    标签: c++ string list integer


    【解决方案1】:
    #include <iostream>
    #include <vector>
    #include <iterator>
    
    std::vector<int> ints;
    std::copy(std::istream_iterator<int>(cin), 
          std::istream_iterator<int>(), 
          std::back_inserter(ints));
    

    完成。如果你真的需要明确地逐行阅读:

    #include <sstream>
    #include <iostream>
    #include <vector>
    #include <iterator>
    
    std::string singleline;
    std::istringstream iss; // out of loop for performance
    while (std::getline(cin, singleline))
    {
          iss.str(singleline);
          std::copy(std::istream_iterator<int>(iss), 
                std::istream_iterator<int>(), 
                std::back_inserter(ints));
    }
    

    istream_iterator&lt;int&gt; 将重复地将operator&gt;&gt;(int&amp;) 应用于引用的流(直到流结束)。默认情况下会默默忽略空格,如果输入操作失败(例如遇到非整数输入)会抛出异常

    back_inserter 是一个输出迭代器,您可以将它与支持.push_back 操作的所有容器类型(如vector)一起使用。所以实际上用 STL 算法写在那里的内容类似于

    std::vector<int> ints;
    while (iss>>myint)
    {
         ints.push_back(myint);
    }
    

    【讨论】:

    • 谢谢 - 仔细解释一下...有什么作用吗?
    • @sehe - 你不觉得这个答案对于 OP 来说有点太基本了吗?
    • @Pete 我不同意。这正是初学者应该使用的代码类型。初学者自己写的代码越少越好。
    • @Pete:我倾向于发布答案的核心,然后花一些时间来修饰,通常取决于 OP 反馈
    • @sehe:我想..你的意思是std::istream_iterator&lt;int&gt;(iss)..而不是std::istream_iterator&lt;iss&gt;(cin)
    【解决方案2】:

    在 sehe 的回答之后,这里是你如何做的更详细一点 (ahem)。

    他使用的算法基本上在内部执行此操作。这个答案主要是为了清楚起见。

    #include <iostream>
    #include <vector>
    
    int main()
    {
       std::vector<int> myInts;
    
       int tmp;
       while (std::cin >> tmp) {
          myInts.push_back(tmp);
       }
    
       // Now `myInts` is a vector containing all the integers
    }
    

    Live example.

    【讨论】:

    • +1 呵呵。感谢您接手我的工作来解释尴尬的 STL-ese :) 我想在实践中,我实际上会建议这样做。虽然,是的,出于稍微纯粹的原因,我确实更喜欢算法变体。
    • 我不明白 - 如果我在一行中输入所有整数,这将如何工作?
    • @PigHead:线条无关紧要。 &gt;&gt; 在对int 有效的同时读取尽可能多的字符,然后停止。它还倾向于忽略空格,因此它会立即准备好提取下一个看起来像数字的子字符串。
    • 这是我真正需要知道的唯一事情!谢谢
    • @PigHead:没问题。 iostreams 有点垃圾。祝你好运!
    【解决方案3】:

    查看strtok( )atoi( ) 的手册页

    【讨论】:

    • Ew。现在是 21 世纪,伙计。
    • @Tomalak Geret'kal - 上帝保佑我对马车鞭子的投资!
    猜你喜欢
    • 2018-11-06
    • 2023-03-03
    • 2013-07-06
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 2011-05-09
    • 2014-05-15
    相关资源
    最近更新 更多