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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With