C ++如何用二进制格式表示字符串?

时间:2017-08-07 17:50:42

标签: c++ string push-back

出于某种原因,我需要频繁生成字符串,使用{' 0',' 1',' 2',' 3&# 39;}。我当前的代码使用push_back()函数,如下所示:

string test = ""
test.push_back('0')
test.push_back('2')
test.push_back('3') // test would be "023"

我想将字符串存储在char类型或int类型中,并使用每个字符的二进制形式递归生成字符串。 " 023"将被存储在char =' 0010 1100'中。

你认为二进制操作比push_back更节省时间吗?如果是这样,如何编写代码。

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用位域,类似

struct data
{
    unsigned char v1 : 2; // Can only store 0, 1, 2, 3
    unsigned char v2 : 2;
    unsigned char v3 : 2;
    unsigned char v4 : 2;
};

然后使用

std::vector<data> v;
int nd_elem_in_last_item = 0; // to differenciate 00 from 0 and not there for final item.

所以你的数据确实会更加紧凑。

答案 1 :(得分:-2)

制作一个类似string s="0123"的字符串。 并且,使用next_permutation(s.begin(),s.end())生成由0,1,2,3组成的所有数字排列。