【问题标题】:reading variable length input in C++ using stream使用流在 C++ 中读取可变长度输入
【发布时间】:2019-11-03 08:58:33
【问题描述】:

我有以下要读入程序的要求。

第一行包含两个以空格分隔的整数,分别表示 p(可变长度数组的数量)和 q(查询的数量)的值。 后续行中的每一行都包含数组中每个元素的空格分隔序列。

随后的每一行都包含两个以空格分隔的整数,分别描述查询的 i(数组中的索引)和 j(由 引用的数组中的索引)的值。

2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3

在上面的示例中,我有 2 个数组和 2 个查询。第一个数组是 3,3,5,4,第二个数组是 5 1 2 8 9 3。

我的问题是如何在我的容器中读取这些数据。注意:我无法从控制台输入输入,这里有一些测试程序提供输入。

我写的如下

int iNoOfVectors = 0;
    int iNoOfQueries = 0;
    cin >> iNoOfVectors >> iNoOfQueries;
    cout << iNoOfVectors ; 
    vector<vector<int>> container;
    container.reserve(iNoOfVectors);
    for(int i = 0; i < iNoOfVectors; i++ ) {
        int temp;
        std::string line;
        while (std::getline(std::cin, line))
        {
            std::cout << line << std::endl;
        }
    }

上面的输出

2
3 1 5 4
5 1 2 8 9 3
0 1
1 3

如何将可变长度数组元素放入容器中。

谢谢

【问题讨论】:

标签: c++ c++11


【解决方案1】:

如果你想从一个字符串中读取相似的数据到一个向量中,你需要做以下2个步骤:

  • 将字符串内容放入std::istringstream
  • 使用 std::istream_iterator 遍历 istringstream 中的元素

例子:

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>

int main() {

    // The source string
    std::string stringWithIntegers{ "5 1 2 8 9 3" };

    // Build an istringstream with the above string as data source
    std::istringstream iss{ stringWithIntegers };

    // Define variable 'data'. Use range constructor and stream iterator    
    std::vector<int> data{std::istream_iterator<int>(iss), std::istream_iterator<int>()};

    // Display result
    std::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, "\n"));

    return 0;
}

也可以复制数据:

    std::vector<int> data{};

    std::copy(
        std::istream_iterator<int>(iss),
        std::istream_iterator<int>(),
        std::back_inserter(data)
    );

【讨论】:

    猜你喜欢
    • 2011-12-02
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多