3

I found an example about how to use std::getline(), and this is the code snippet:

std::istringstream input("abc|def|gh");
std::vector<std::array<char, 4>> v;

for (std::array<char, 4> a; input.getline(&a[0], 4, '|'); )
    v.push_back(a);

We can find that a is constructed at the for-loop, and it is passed into push_back as an argument. Is there a better way to make sure there is no temporary object like a to avoid overhead?

I have found a member function called emplace_back() to reduce the use of temporary object, but I am not sure how can I use it in this case, or I should just leave it for compiler optimizations?

Kevin Dong
  • 5,001
  • 9
  • 29
  • 62

2 Answers2

1

getline needs to have a location to get the line in to, but you can make that location be the new element in the v vector, thus avoiding the use of an extra variable. Replace the for loop with a do/while loop:

do {
    v.emplace_back();
} while (input.getline(&v.back()[0], 4, '|'));
v.pop_back();

The emplace_back takes the place of a in your original code.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
0

Is there a better way to make sure there is no temporary object like a to avoid overhead?

If you know the size of the vector ahead of time, you create one with the known size and use the preallocated members of the vector in the call to getline.

size_t size = 10;
std::istringstream input("abc|def|gh");
std::vector<std::array<char, 4>> v(size); // Assuming size of the vector.

for ( size_t i = 0; i < size && input.getline(&v[i], 4, '|'); ++i ) {}
R Sahu
  • 204,454
  • 14
  • 159
  • 270