I have the following code snippet, which takes the std::vector<int> list
and writes a zero in all vector elements. This example is working perfectly fine.
#include <vector>
#include <iostream>
#include <algorithm>
int main () {
std::vector<int> list {1, 1, 2};
auto reset = [](int & element){element = 0;};
auto print = [](int element) {std::cout << element << " ";};
std::for_each(list.begin(), list.end(), reset);
std::for_each(list.begin(), list.end(), print);
}
If I take change the type of the vector from int
to bool
, the code will not compile.
#include <vector>
#include <iostream>
#include <algorithm>
int main () {
std::vector<bool> list {true, true, false};
auto reset = [](bool & element){element = false;};
auto print = [](int element) {std::cout << element << " ";};
std::for_each(list.begin(), list.end(), reset);
std::for_each(list.begin(), list.end(), print);
}
I don't understand the compiler error message:
/opt/compiler-explorer/gcc-7.2.0/lib/gcc/x86_64-linux-gnu/7.2.0/../../../../include/c++/7.2.0/bits/stl_algo.h:3884:2: error: no matching function for call to object of type '(lambda at :7:18)'
__f(*__first); ^~~
:10:10: note: in instantiation of function template specialization 'std::for_each:7:18)>' requested here
std::for_each(list.begin(), list.end(),reset); ^
:7:18: note: candidate function not viable: no known conversion from 'std::_Bit_iterator::reference' (aka 'std::_Bit_reference') to 'bool &' for 1st argument
auto reset = [](bool & element){element = false;}; ^
:7:18: note: conversion candidate of type 'void (*)(bool &)'
Why does std::foreach
work with a std::vector<int>
, but does not work with a std::vector<bool>
?
Is the memory optimisation of an std::vector<bool>
(see here ) part of the answer?