Nate
Nate

Reputation: 925

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.

Upvotes: 7

Views: 6884

Answers (5)

nakiya
nakiya

Reputation: 14413

Things you can do:

  1. Make sure that you compile with -O3 (Or equivalent compiler optimization).
  2. Do you generate the values in the vector yourself? If so, try changing toInt() function to accept a simple pointer type.
  3. Write the conversion yourself (Browser code : may not even compile - u get the idea though):

    char* toInt(int* values, size_t length)
    {
      int *end = values + sizeof(int)*length;
      int *cur = values;
    
      char* buf = new char[length + 1]
    
      for(char* out = buf;cur < end;++cur, ++buf)
      {
          *out = (char)*cur + '0';
      }
      *buf = '\0';
      return buf;
    }
    

Upvotes: 0

Tabrez Ahmed
Tabrez Ahmed

Reputation: 2950

All are integers. Shouldn't you do the following.

//if you want to concatenate v[1] and v[4]
int concatenated;
concatenated = v[1]*10+v[4];
//If you want to concatenate all
concatenated = 0;
for(int i=1;i<=4;i++)
    concatenated = concatenated*10+v[i];

the output would be an integer ( not a string)

Upvotes: 1

TommyN
TommyN

Reputation: 2381

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.

Upvotes: 7

Ed J
Ed J

Reputation: 101

Remember ASCII codes?

char concat[vSize+1];
concat[vSize] = 0;
for(int i = 0; i < vSize; i++) {
    concat[i] = (v[i] % 10) & 0x30;
}

Upvotes: 1

Joni
Joni

Reputation: 111259

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.

Upvotes: 4

Related Questions