1

When I try to use for_each to change vector in place:

vector<bool> sub_accs_ind(vec_ids_.size());
std::for_each(sub_accs_ind.begin(), sub_accs_ind.end(), [](bool& b){ b = false; });

It results in error /usr/include/c++/4.8/bits/stl_algo.h:4417:14: error: no match for call to ‘(main(int, char* const*)::__lambda3) (std::_Bit_iterator::reference)’ __f(*__first);

Could you please guide me about what is wrong here?

Cron Merdek
  • 1,084
  • 1
  • 14
  • 25
  • 1
    why not using fill constructor in your case ? `vector sub_accs_ind(vec_ids_.size(), false);` is enough to have all elements to `false` – Garf365 Jul 26 '16 at 09:26
  • And also, what you need is [`transform`](http://www.cplusplus.com/reference/algorithm/transform/), not `for_each` – Garf365 Jul 26 '16 at 09:27
  • Reference type of vector is not a bool, but a proxy class. – Arunmu Jul 26 '16 at 09:28

1 Answers1

8

std::vector<bool> is not a container !

Its iterators don't return a bool&, but a proxy instance. In C++11, you have to name its type explicitly:

std::for_each(
    sub_accs_ind.begin(),
    sub_accs_ind.end(),
    [](decltype(sub_accs_ind)::reference b){ b = false; }
);

C++14 would allow you to declare the parameter as auto&& to accomodate both real references and proxies.

Community
  • 1
  • 1
Quentin
  • 62,093
  • 7
  • 131
  • 191
  • I want to ask you, `transform(sub_accs_ind.begin(), sub_accs_ind.end(), sub_accs_ind.begin(), [](bool b){ return false; });`, does it also really change that value? – kaitian521 Jul 26 '16 at 09:48
  • @kaitian521 yes, it will work as expected. Two proxies will be used, one for getting the `bool` for your parameter, and one to store the return value back into the vector. – Quentin Jul 26 '16 at 09:52
  • this make sense, bitset use 1/8 storage than `vector`, but sometimes readability is more important than efficiency – kaitian521 Jul 26 '16 at 10:00