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.