为什么这段代码有效
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)
我正在使用受此答案启发的格式功能。只要我通过const char*
它,一切就可以正常工作:
const char* hello = "Hello";
std::string world = "world";
string_format("%s, %s!", hello , world.c_str());
// Returns "Hello, world!"
Run Code Online (Sandbox Code Playgroud)
现在,我在所有地方都使用std :: strings,我想避免.c_str()
在任何地方调用。如何修改此函数以为我调用它,并允许我仅将std :: strings传递给它?
比方说,我有一个基础抽象类B
百余类,从它派生D1
... D100
.我也有两个(智能)指针unique_ptr<B> p1, p2;
,其指向的类型的两个不同的实例Di
和Dj
.我想知道他们指向的对象是否具有相同的类型(即是否i
等于j
).有一个简单的方法吗?
#include <iostream>
#include <bitset>
#include <cstring>
using namespace std;
int main()
{
uint8_t a = 1;
uint16_t b = 0;
memcpy(&b, &a, 1);
cout << bitset<16>(b) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个的输出是0000000000000001
.但是,我会想到memcpy
把刚才复制a
到的第一个字节b
,并b
要0000000100000000
代替.这里发生了什么?