我编写了以下代码片段,将两种状态的字符串 ("+++--+-"或"yynnny") 转换为std::bitset:
#include <bitset>
#include <cstddef>
#include <string>
#include <iostream>
std::bitset<70> convertTwoStateString(std::string twoState)
{
std::bitset<70> a{0b0};
std::bitset<70> eins{0b1};
for(const auto c : twoState) {
if(c == '+') {
a <<= 1;
a |= eins;
}
if(c == '-') {
a <<= 1;
}
}
return a;
}
int main()
{
std::string s{"-+--+++--+--+"};
std::bitset<70> set = convertTwoStateString(s);
std::cout << set << std::endl;
//0000000000000000000000000000000000000000000000000000000000100111001001
}
Run Code Online (Sandbox Code Playgroud)
是否有更算法和/或更优雅的方法来进行此类转换?
康桓瑋*_*康桓瑋 49
构造函数std::bitset可以指定表示 的替代字符0/1,因此您可以
std::string s{"-+--+++--+--+"};
std::bitset<70> set(s, 0, s.size(), '-', '+');
Run Code Online (Sandbox Code Playgroud)