Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate ints in an array?

As part of a homework assignment I need to concatenate certain values in an array in C++. So, for example if I have:

int v[] = {0,1,2,3,4}

I may need at some point to concatenate v[1] -> v[4] so that I get an int with the value 1234.

I got it working using stringstream, by appending the values onto the stringstream and then converting back to an integer. However, throughout the program there will eventually be about 3 million different permutations of v[] passed to my toInt() function, and the stringstream seems rather expensive (at least when dealing with that many values). it's working, but very slow and I'm trying to do whatever I can to optimize it.

Is there a more optimal way to concatenate ints in an array in C++? I've done some searching and nearly everywhere seems to just suggest using stringstream (which works, but seems to be slowing my program down a lot).

EDIT: Just clarifying, I do need the result to be an int.

like image 222
Nate Avatar asked Mar 25 '12 11:03

Nate


3 Answers

Pseudo code for a simple solution:

int result = 0;
for (int i=0; i < len(v); i++)
{
  result = result*10 + v[i];
}

Large arrays will bomb out due to int size overflow.

like image 91
TommyN Avatar answered Oct 01 '22 15:10

TommyN


How about:

int result = (((v[1])*10+v[2])*10+v[3])*10+v[4];

If the number of elements is variable rather than a fixed number, I'm sure you can spot a pattern here that can be applied in a loop.

like image 26
Joni Avatar answered Oct 01 '22 15:10

Joni


Remember ASCII codes?

char concat[vSize+1];
concat[vSize] = 0;
for(int i = 0; i < vSize; i++) {
    concat[i] = (v[i] % 10) & 0x30;
}
like image 30
Ed J Avatar answered Oct 01 '22 14:10

Ed J