小编Val*_*tin的帖子

Range-for-loops和std :: vector <bool>

为什么这段代码有效

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引用

for(auto& i : boolVector)
Run Code Online (Sandbox Code Playgroud)

c++ for-loop range auto c++11

34
推荐指数
3
解决办法
3457
查看次数

函数采用可变参数模板包将std :: strings转换为const char *?

我正在使用受此答案启发的格式功能。只要我通过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传递给它?

c++ formatting

4
推荐指数
1
解决办法
408
查看次数

检查两个(智能)指针是否指向同一派生类

比方说,我有一个基础抽象类B百余类,从它派生D1... D100.我也有两个(智能)指针unique_ptr<B> p1, p2;,其指向的类型的两个不同的实例DiDj.我想知道他们指向的对象是否具有相同的类型(即是否i等于j).有一个简单的方法吗?

c++ c++11

3
推荐指数
2
解决办法
620
查看次数

memcpy是否识别目标的基础大小?

#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,并b0000000100000000代替.这里发生了什么?

c++ bit-manipulation

1
推荐指数
1
解决办法
187
查看次数

标签 统计

c++ ×4

c++11 ×2

auto ×1

bit-manipulation ×1

for-loop ×1

formatting ×1

range ×1