c++ - 使用流读取C++中的可变长度输入

标签 c++ c++11

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

第一行包含两个以空格分隔的整数,分别表示 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

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

谢谢

最佳答案

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

  • 将字符串的内容放入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)
    );

关于c++ - 使用流读取C++中的可变长度输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58678685/

相关文章:

c++ - 目标文件中带有 "U" undefined symbol 类型的程序如何在没有任何链接器错误的情况下进行编译?

c++ - 为什么必须内联定义在类外部(但在头文件中)的类成员函数?

C++ - vector 迭代错误

c++ - 为什么有些包含文件只驻留在 tr1 中?

std::lower_bound 和 std::set::lower_bound 之间的 C++ 区别?

c++ - 更改链表

C++ 返回整个空分隔字符串

c++ - 层次结构中的反向可变参数模板参数

c++ - 宏与模板结合生成Object

c++ - constexpr std::optional 可能的实现