#include <vector>
#include <iostream>
using namespace std;
int main()
{
auto f = [](auto& vec) {
auto d = vec[0];
d = true;
for(auto i : vec)
cout << i << " ";
cout << "\n";
};
vector<bool> bools{ false, true, false, true, false };
vector<int> ints{0,1,0,1,0};
f(ints);
f(bools);
return 0;
}
程序输出:
0 1 0 1 0
1 1 0 1 0
使用实参ints调用lambda表达式f,第一个元素没有被修改,使用实参ints调用lambda表达式f,第一个元素被修改。原因是std::vector<bool>::reference并不是bool类型引用,而是指向一个代理类。当操作符[]配合auto使用时,出现和其他容器不同的非标准行为。
也正因为代理类,使得std::vector<bool>还存在其他缺点,但我感觉相比代码片段中的问题,这些缺点并不严重。
补充一个std::vector<bool>非标准行为示例
#include <stdio.h>
#include <vector>
int main()
{
std::vector<bool> v{false};
v[0] |= false;
return 0;
}
编译报错,有两种解决方法
方法一
#include <stdio.h>
#include <vector>
int main()
{
std::vector<bool> v{false};
v[0] = v[0] | false;
return 0;
}
方法二
#include <stdio.h>
#include <vector>
using namespace std;
std::vector<bool>::reference operator|= (std::vector<bool>::reference a, const bool& b){
a = a | b;
return a;
}
int main()
{
vector<bool> a{false};
bool b = false;
bool c = true;
a[0] |= b |= c;
printf("b:%d\n", bool(a[0]));
return 0;
}