count 1 in string

T

thomas

I have a list of strings composed of only 0 and 1, like
0000100001 1000010000, ....
They all have the same length.
Now they are stored in a vector of strings.
I want to calculate count(string1 xor string2).

for example:
1010, 0101 -xor-> 1111 --> 4 (four 1s in the result string)
1111, 0000 -xor-> 0000 --> 0

I can do it by string comparing, but I think it's really ugly.
And I do think there must be some easy and simple method, but I don't
know how.
Can you help me?
 
L

Lionel B

I have a list of strings composed of only 0 and 1, like 0000100001
1000010000, ....
They all have the same length.
Now they are stored in a vector of strings. I want to calculate
count(string1 xor string2).

for example:
1010, 0101 -xor-> 1111 --> 4 (four 1s in the result string) 1111,
0000 -xor-> 0000 --> 0

I can do it by string comparing, but I think it's really ugly. And I do
think there must be some easy and simple method, but I don't know how.
Can you help me?

Consider using the std::bitset container, which represents a (fixed
length) sequence of bits. It supports basic logical operations (including
xor), bit counting and lots more. It can also be converted easily to and
from a character string representation.
 
E

Eric Pruneau

Lionel B said:
Consider using the std::bitset container, which represents a (fixed
length) sequence of bits. It supports basic logical operations (including
xor), bit counting and lots more. It can also be converted easily to and
from a character string representation.

Suppose you have
string s1("1010");
string s2("0101");

you can do:
bitset<4> b1(s1);
bitset<4> b2(s2);
bitset<4> bxor = b1 ^ b2;
size_t count = bxor.count();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top