std::_Bit_rerefence& 类型的非常量引用的初始化无效
Invalid initialization of non-const reference of type std::_Bit_rerefence&
嗯,我正在编写一个代码将两个字符串转换为一个位集(不幸的是 std::bitset
不能使用,因为它有编译时模板常量大小要求)。
出于某种原因,我无法为基于范围的循环引用迭代:
#include <iostream>
#include <sstream>
#include <vector>
int main()
{
std::string line;
std::getline(std::cin, line);
std::string chips;
std::string pattern;
std::istringstream issline(line);
issline >> chips;
issline >> pattern;
auto toBool = [](const char c) -> bool { return(c == 'B'); };
std::vector<bool> bitchips;
for(auto& i : chips){
bitchips.push_back(toBool(i));
}
std::vector<bool> bitpattern;
for(auto& i: pattern){
bitpattern.push_back(toBool(i));
}
auto flip = [&bitchips]() -> void
{
for(auto& i : bitchips) { //error
i = !i;
}
};
return 0;
}
error: invalid initialization of non-const reference of type 'std::_Bit_reference&' from an rvalue of type 'std::_Bit_iterator::reference {aka std::_Bit_reference}'
目前正在做什么程序:
正在读取用户输入:BBBBNNNB NNNBBBNB
。转换为:11110001 00011101
std::vector<bool>
是 std::vector
的特化,它的行为与普通的 std::vector
不同。特别是,std::vector<bool>::reference
是代理 class。
proxy class representing a reference to a single bool
您可以改用右值引用。例如
auto flip = [&bitchips]() -> void
{
for(auto&& i : bitchips) {
i = !i;
}
};
或
auto flip = [&bitchips]() -> void
{
for(auto i : bitchips) {
i = !i;
}
};
或
auto flip = [&bitchips]() -> void
{
for(auto i : bitchips) {
i.flip();
}
};
即使它们看起来违反直觉。
嗯,我正在编写一个代码将两个字符串转换为一个位集(不幸的是 std::bitset
不能使用,因为它有编译时模板常量大小要求)。
出于某种原因,我无法为基于范围的循环引用迭代:
#include <iostream>
#include <sstream>
#include <vector>
int main()
{
std::string line;
std::getline(std::cin, line);
std::string chips;
std::string pattern;
std::istringstream issline(line);
issline >> chips;
issline >> pattern;
auto toBool = [](const char c) -> bool { return(c == 'B'); };
std::vector<bool> bitchips;
for(auto& i : chips){
bitchips.push_back(toBool(i));
}
std::vector<bool> bitpattern;
for(auto& i: pattern){
bitpattern.push_back(toBool(i));
}
auto flip = [&bitchips]() -> void
{
for(auto& i : bitchips) { //error
i = !i;
}
};
return 0;
}
error: invalid initialization of non-const reference of type 'std::_Bit_reference&' from an rvalue of type 'std::_Bit_iterator::reference {aka std::_Bit_reference}'
目前正在做什么程序:
正在读取用户输入:BBBBNNNB NNNBBBNB
。转换为:11110001 00011101
std::vector<bool>
是 std::vector
的特化,它的行为与普通的 std::vector
不同。特别是,std::vector<bool>::reference
是代理 class。
proxy class representing a reference to a single bool
您可以改用右值引用。例如
auto flip = [&bitchips]() -> void
{
for(auto&& i : bitchips) {
i = !i;
}
};
或
auto flip = [&bitchips]() -> void
{
for(auto i : bitchips) {
i = !i;
}
};
或
auto flip = [&bitchips]() -> void
{
for(auto i : bitchips) {
i.flip();
}
};
即使它们看起来违反直觉。