c++ - How do you use the extraction operator (>>) with vector<bool>? -
in example vector<int> somevector
, istringstream somestringstream
can this:
for (int i=0; < somevector.size(); i++) { somestringstream >> somevector[i]; }
i know vector<bool>
efficient implementation, , operator[]
returns reference object. code should using index rather iterator, readability. currently, i'm using this:
for (int i=0; < somevector.size(); i++) { bool temp; somestringstream >> temp; somevector[i] = temp; }
is there more direct way of implementing this?
you use std::copy
or std::vector
range constructor if want consume whole stream:
std::stringstream ss("1 0 1 0"); std::vector<bool> vec; std::copy(std::istream_iterator<bool>(ss), {}, std::back_inserter(vec));
std::stringstream ss("1 0 1 0"); std::vector<bool> vec(std::istream_iterator<bool>(ss), {});
now looking @ examples posted , if you're sure std::vector
s size proper use std::generate
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;});
Comments
Post a Comment