따라서 각 비트를 설정하여 부호없는 정수로 전환 (입력 문자열 돌연변이 생략) :
#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'조용히 (A 문자열 이외의 문자는 무시 " 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 g과 4.8.4 ++ ++ ++ -std = C 11 -03 보여준다
to_bitset
약 3 배 erasing spaces from a string/constructing a bitset
보다 빠릅니다.
첫 번째 옵션을 사용합니다. –
나는 모든 공백을 제거하고, 옵션 1을 사용한다. –
나는 여전히 언급 된 3 가지 이외의 방법을 찾고있다. 내 테스트에서 방법 1은 방법 3보다 4.67 배 빠릅니다. –