0

The input for the program consists of two parts. The first line of the input is the number of elements, and the second line is all the elements. This is an example input:

5
1 3 23 4 2

Is there a way to deal with this kind of input without using std::string and parsing it to the vector of ints later?

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
Marcin Poloczek
  • 923
  • 6
  • 21

1 Answers1

3

It sounds like this is for a programming competition or some other similar setup where you can trust that the input is properly formatted. If that's the case, yes, you can do this without buffering things through a std::string. Here's one option:

std::size_t size;
std::cin >> size;

std::vector<int> values;
// Could do values.reserve(size); here if you'd like.

for (std::size_t i = 0; i < size; i++) {
    std::size_t value;
    std::cin >> value;

    values.push_back(value);
}

Note that the stream extraction operator operator >> will use any whitespace character as a delimiter, so the newline after the number of elements and the space characters between the numbers themselves will work great as separators. There's no need to pull the entire second line by itself and then parse it apart.

This does no error-checking, which is a real problem if you can't trust the inputs. But if you can, this should do the trick.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • Thanks, that's what I needed. – Marcin Poloczek Aug 28 '19 at 22:11
  • 1
    Addendum: After you read the size, you can `values.reserve(size);` to possibly save a bit of time spent resizing the `vector` during `push_back`s. – user4581301 Aug 28 '19 at 22:12
  • @user4581301 He can also use vector's constructor and set the initialized elements' count to this size, and then instead `push_back`, just use `vec[i] = value` – Coral Kashri Aug 28 '19 at 22:21
  • @KorelK True. For a small number of elements, I imagine all of these are a wash. But if there's, say, a billion elements, then using the constructor, which has to zero those elements out, might be appreciably slower. – templatetypedef Aug 28 '19 at 22:22