-5

For some reason, I need to frequently generate strings use characters in {'0', '1', '2', '3'}. My current code use push_back() function and looks like:

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

I want to store the string in a char type or int type, and use binary form of each character to recursively generate the string. "023" would be stored in a char = '0010 1100'.

Do you think the binary operation is more time-efficient than push_back? If so, how to write the code.

Thanks!

  • 1
    How could you differentiate `10` from `101`, or any other binary strings that share a prefix? – Purag Aug 07 '17 at 17:53
  • 1
    Why would there be a performance difference between adding the binary representation of a number as a string vs the number as a string? In either case you are doing string concatenation, the string has no idea that one is "in binary" because they're just `char`s – Cory Kramer Aug 07 '17 at 17:54
  • @Purag Each character would exactly be represented by 2 bits. – user2566640 Aug 07 '17 at 17:58
  • @CoryKramer Thanks for your reply. In binary format, we might can use & | operators to represent this string in a number. Think about how to represent n*n adjacency matrix by a char array. In my case, I also want to store this string "023" in a char, which would be 00101100. – user2566640 Aug 07 '17 at 18:04
  • I would think reducing the number of allocations would trump bit squeezing digits inside a single `char`. Can you estimate the number of digits per string and reserve upfront to reduce them? – Borgleader Aug 07 '17 at 18:14
  • @Borgleader Thanks for your suggestion. Yes, indeed I do reserve the space by test.reserve(N). I have already edit my question a little bit. Hope it can help. – user2566640 Aug 07 '17 at 18:26

2 Answers2

1

You might use bitfield, something like

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;
};

and then use

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

So your data would indeed be more compact.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
-2

make a string like string s="0123". And , use next_permutation(s.begin(),s.end()) to generate all permutation of number consisting of 0,1,2,3.

  • OP implies his desired strings are variable length. This will only generate fixed length strings. – hnefatl Aug 07 '17 at 18:21