为什么这段代码有效
std::vector<int> intVector(10);
for(auto& i : intVector)
std::cout << i;
Run Code Online (Sandbox Code Playgroud)
这不是吗?
std::vector<bool> boolVector(10);
for(auto& i : boolVector)
std::cout << i;
Run Code Online (Sandbox Code Playgroud)
在后一种情况下,我收到一个错误
错误:从'std :: _ Bit_iterator :: reference {aka std :: _ Bit_reference}'类型的右值开始,无效初始化'std :: _ Bit_reference&'类型的非const引用
Run Code Online (Sandbox Code Playgroud)for(auto& i : boolVector)
请考虑以下示例:
#include <iostream>
#include <vector>
int main() {
std::vector<bool> vectorBool{false, true};
for(const auto &element : vectorBool) std::cout << std::boolalpha << element << ' ';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它会发出警告:
test.cpp:6:21: warning: loop variable 'element' is always a copy because the range of type 'std::vector<bool>' does not return a reference [-Wrange-loop-analysis]
for(const auto &element : vectorBool) std::cout << std::boolalpha << element << ' ';
^
test.cpp:6:9: note: use non-reference type 'std::_Bit_reference'
for(const auto &element : vectorBool) std::cout << std::boolalpha …Run Code Online (Sandbox Code Playgroud)