Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use the extraction operator (>>) with vector<bool>?

In an example with vector<int> someVector and istringstream someStringStream you can do this:

for (int i=0; i < someVector.size(); i++) {
  someStringStream >> someVector[i];
}

I know that vector<bool> is an efficient implementation, and operator[] returns a reference object. For this code I should be using an index rather than an iterator, mostly for readability. Currently, I'm using this:

for (int i=0; i < someVector.size(); i++) {
  bool temp;
  someStringStream >> temp;
  someVector[i] = temp;
}

Is there a more direct way of implementing this?

like image 639
Caleb Zulawski Avatar asked Jun 03 '15 21:06

Caleb Zulawski


1 Answers

You could use std::copy or the std::vector range constructor if you want to consume the whole stream:

std::stringstream ss("1 0 1 0");
std::vector<bool> vec;
std::copy(std::istream_iterator<bool>(ss), {}, std::back_inserter(vec));

LIVE DEMO

std::stringstream ss("1 0 1 0");
std::vector<bool> vec(std::istream_iterator<bool>(ss), {});

LIVE DEMO

Now looking at the examples that you posted and if you're sure that your std::vectors size is proper you could use std::generate like the example below:

std::stringstream ss("1 0 1 0");
std::vector<bool> vec(4);
std::generate(std::begin(vec), std::end(vec), [&ss](){ bool val; ss >> val; return val;});

LIVE DEMO

like image 155
101010 Avatar answered Sep 18 '22 10:09

101010