3种方法来切换表示为char的位 [英] 3 ways to toggle a bit represented as a char

查看:95
本文介绍了3种方法来切换表示为char的位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样写:

#include <iostream>
#include <vector>

int main()
{
    std::vector<char> v = {0, 0, 0};
    v[0] = v[0] == 0 ? 1 : 0;
    v[1] = !v[1];
    v[2] ^= 1;
    std::cout << (int)v[0] << (int)v[1] << (int)v[2] << "\n";
    return 0;
}

这会切换所有位,但实际上我只关心第i个一点。

which toggles all bits, but I actually care on changing only the i-th bit.

我感兴趣的是项目,当您唯一关心的是速度(而不是内存和可读性)时?

What am I interested in is which one of these ways should one use in a c++ project, when the only thing that you care is speed (not memory and readability)?

使用 std :: vector< char> 作为位集的原因是在我的时间安排中,我发现它更快比 int s或 char s和 std :: bitset

The reason for using std::vector<char> as a bitset is that in my timings I found that it's faster than a vector of ints or chars, and std::bitset.

推荐答案

您可以改用 std :: bitset ,只要您对位感兴趣或直接使用bool的向量而不是char:

You can instead use either std::bitset as long as you are interested in bits or use directly vector of bool not char:

#include <iostream>
#include <vector>

int main()
{
    std::vector<bool> v = { 0, 0, 0 };

    for (int i(0); i < v.size(); i++)
        v[i] = !v[i];

    for (int i(0); i < v.size(); i++)
        std::cout << (int)v[i];

    std::cout << std::endl;

    std::cin.get();
    return 0;
} 




  • 按位不推荐使用!,因为它的速度和清洁度。

    • the bitwise not ! is recommended due to its speed and cleanness.
    • 这篇关于3种方法来切换表示为char的位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆