0

如何快速将一串由空格分隔的 1 和 0 转换为bitset?

存在一个构造函数来bitset从不被空格分隔的字符串初始化 a,一个将 a 初始化bitset为全零或一,以及一个从整数初始化。在我的脑海中,我可以想到三种方法:

  • 从字符串中删除空格并将其传递给构造函数
  • 将二进制转换为整数并将其传递给构造函数
  • 将所有值初始化为零并根据for循环中的字符串更改每个位的值

位数为 24,每个字符串正好有 24 位,不多也不少。

编辑: 是我用来测试性能的代码,是方法一和二的代码。在我的机器上,方法 1 需要 3 毫秒,方法 3 需要 14 毫秒。

编辑 2:我使用-O3 -o -g --std=c++11的是我的编译器设置。我使用了 gccclang。

4

1 回答 1

1

通过相应地设置每个位来转换(不改变输入字符串)到无符号整数:

#include <bitset>
constexpr unsigned long long
extract_bits(const char* ptr, unsigned long long accumulator) {
    return (*ptr == 0)
        ? accumulator
        : extract_bits(ptr + 1, (*ptr == '1')
            ? accumulator << 1u | 1u
            : (*ptr == '0')
                ? accumulator << 1
                : accumulator);
}

template <unsigned N>
constexpr std::bitset<N>
to_bitset(const char* ptr) {
    return std::bitset<N>(extract_bits(ptr, 0));
}

#include <iostream>
int main()
{
    constexpr auto b = to_bitset<24>("0 0 1 1 0 0 1 1 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0");
    std::cout << b << '\n';
    return 0;
}

注意:转换会悄悄地忽略除“0”和“1”之外的任何字符(“01-01”之类的字符串也是有效的)。

获取上述转换的时间并从字符串中删除空格:

#include <algorithm>
#include <cctype>
#include <cstring>
#include <chrono>
#include <iostream>
#include <random>

using namespace std::chrono;

void print_duration(const char* what, const system_clock::time_point& start, const system_clock::time_point& stop) {
    auto duration = duration_cast<microseconds>(stop - start);
    std::cout << what << ": " << duration.count() << std::endl;
}

volatile unsigned long long result;
int main()
{
    std::string str = "0 0 1 1 0 0 1 1 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0";
    std::vector<std::string> strings(1000, str);
    std::random_device random_device;
    std::mt19937 random_generator(random_device());
    for(auto& str : strings) {
        std::shuffle(str.begin(), str.end(), random_generator);
    }

    // Non mutating to_bitset
    {
        auto start = system_clock::now();
        for(const auto& str : strings) {
            auto b = to_bitset<24>(str.c_str());
            result = b.to_ullong();
        }
        auto stop = system_clock::now();
        print_duration("to_bitset", start, stop);
    }
    // Erasing spaces
    {
        auto start = system_clock::now();
        for(auto& str : strings) {
            str.erase(std::remove_if(str.begin(), str.end(), ::isspace), str.end());
            auto b = std::bitset<24>(str);
            result = b.to_ullong();
        }
        auto stop = system_clock::now();
        print_duration("str.erase", start, stop);
    }
    return 0;
}

g++ 4.8.4 和 g++ -std=c++11 -O3 显示:

to_bitset比 .快大约 3 倍erasing spaces from a string/constructing a bitset

于 2016-06-30T20:13:40.023 回答