为什么遍历bool的向量( w/修改元素)需要&&,而不是int的向量?
// junk10.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <algorithm>
#include <array>
#include <vector>
using namespace std;
int main()
{
vector<int> miv{ 1, 2, 3 };
for (auto &e : miv) { e = 15; } // Legal
vector<bool> mbv{ false };
for (auto &e : mbv) { e = true; } // Illegal
for (auto &&e : mbv) { e = true; } // Legal
return 0;
}发布于 2018-05-08 11:22:27
实现std::vector<bool>的方式是为了提高空间效率,每个布尔值占用1位,而不是布尔值1字节。
这意味着你不能引用它。引用是一个包装的指针,你不能有一个指向一个位的指针。
您可以使用C++ 11中的auto &&修改该位,但请注意,auto不会变成布尔值:
std::vector<bool> vec { 1, 0, 1 };
bool &&i = vec[1];
i = 1; // DOES NOT MODIFY VECTOR
auto &&k = vec[2];
k = 0; // MODIFIES VECTOR
for (bool i : vec)
std::cout << i;100
https://stackoverflow.com/questions/50225114
复制相似问题