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

In the 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 use an index, not an iterator, mainly for readability. I am currently using this:

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

Is there a more direct way to implement this?

+7
c ++ vector c ++ 11 extraction-operator
source share
2 answers

You can use the range constructor std::copy or std::vector if you want to use 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 you provided, and if you are sure that your std::vector size is correct, you can use std::generate , as shown 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

+5
source share

If all you need is the same interface for bool and other types, it's easy to wrap things up.

 template <typename T> T read(std::istream& stream) { T value; stream >> value; // TODO: guard against failure of extraction, eg throw an exception. return value; } 

However, this requires a type directly.

 for (int i=0; i < someIntVector.size(); i++) { someIntVector[i] = read<int>(someStringStream); } for (int i=0; i < someBoolVector.size(); i++) { someBoolVector[i] = read<bool>(someStringStream); } 

If you reuse this for several different vectors, just return it again:

 template <typename T, typename A> void fillVectorFromStream(std::istream& stream, std::vector<T, A>& vector) { for ( int i = 0; i < vector.size(); ++i ) { vector[i] = read<T>(stream); } } 

Consequently, usage just becomes

 fillVectorFromStream(streamOfBool, vectorOfBooleanValues); fillVectorFromStream(streamOfIntegers, vectorOfIntegers); 
0
source share

All Articles