Получить строку целых чисел, разделенных пробелами, из stdio, не зная, сколько они есть (C ++) - PullRequest
1 голос
/ 29 мая 2020

Я имею дело с проблемой конкурентного программирования, в которой мне нужно взять строку разделенных пробелами целых чисел из стандартного ввода, поместить их в массив и обработать их определенным образом. Проблема в том, что я не знаю, сколько целых чисел я могу получить в каждом тестовом примере. Если я знаю, мой код будет примерно таким:

int n; // number of integers;
int arr[n];
for(int i = 0; i < n; i++)
    cin >> arr[i];

Если у меня нет «n», как мне добиться того же?

Ответы [ 3 ]

4 голосов
/ 29 мая 2020

std::vector<int> - это массив целых чисел динамического размера. Вы можете продолжать добавлять в него что-нибудь, и он будет расти по мере необходимости. Если вам задано количество элементов в качестве первого ввода, вы можете сделать что-то вроде:

std::vector<int> items;

int count;
std::cin >> count;

// Preallocates room for the items. This is not necessary, it's just an optimization.
items.reserve(count);

while (count > 0) {
    int item;
    std::cin >> item;
    items.push_back(item);
    --count;
}

Если вам не указано количество элементов, просто читайте, пока чтение не завершится ошибкой:

std::vector<int> items;
int item;

while (std::cin >> item) {
    items.push_back(item);
}
2 голосов
/ 30 мая 2020

Когда вам будет присвоено значение n. Вы можете выполнить любой из следующих двух шагов:

Шаг: 1

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    int n;
    cin >> n; // Input n
    vector<int>vv(n); // It will declare a vector(similar to an array) of size n
    for(int i = 0; i < n; i++)
    {
        cin >> vv[i];
    }
    return 0;
}

Шаг: 2

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    int n, number;
    cin >> n; // Input n
    vector<int>vv; // It will declare an empty vector
    for(int i = 0; i < n; i++)
    {
        cin >> number; // Take a number as input
        vv.push_back(number); // Put the input to the last of the vector
    }
    return 0;
}

Когда вам не дадут значение n:

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    int number;
    vector<int>vv; // It will declare an empty vector.
    while(cin >> number)
    {
        vv.push_back(number); // Push(put) the input to the back(end/last) of the vector
    }

    /* In case of reading input from a file,
    the loop will continue until the end of the file.

    When you'll try it from console, you need to enter
    end-of-file command from keyboard.*/

    return 0;
}
2 голосов
/ 29 мая 2020

Используйте векторы, так как векторы имеют динамический размер c. Продолжайте вставлять элементы в вектор, пока не появятся входные данные.

std::vector<int> v; 
int temp; 
while (std::cin >> temp) { 
     v.push_back(temp); 
}
...