1

How would I convert a vector of ints into a single int in c++?

vector<int>myints = {3, 55, 2, 7, 8}

Expected answer: 355278

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Sarah H.
  • 581
  • 1
  • 5
  • 13

4 Answers4

7

Here's a quick and dirty way:

using namespace std;

vector<int> myints = {3, 55, 2, 7, 8};
stringstream stream;

for(const auto &i : myints)
{
    stream << i;
}

int value = stoi(stream.str());

And here's a way to do it without strings:

using namespace std;

vector<int> myints = {3, 55, 2, 7, 8};

int value = 0;
for(auto i : myints)
{
    int number = i;
    do
    {
        value *= 10;
        i /= 10;
    }while(i != 0);

    value += number;
}

cout << value << endl;

The i /= 10 is the key bit here as it scales the number up based on the number of digits in the current number, i

Sean
  • 60,939
  • 11
  • 97
  • 136
2

Using the <string> library and the += operator you can iterate over the vector of ints, cast each number to a string and print out the result:

#include <vector>
#include <iostream>
#include <string>
using namespace std;

int main() {
  vector <int> myints = {3, 55, 2, -1, 7, 8};

  string s = "";
  for(int i : myints){
      s += to_string(i);
  }

  cout << s;      //prints 3552-178
}
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
soer
  • 147
  • 1
  • 9
1

This should do the job. Please care that an int may not be enough to handle the number of digits.

#include <vector>
#include <sstream>

int vectorToSingleInt(const std::vector<int> &myints)
{
    std::stringstream stringStream;

    for (int &i : myints)
        stringStream << i;

    int output = 0;
    stringStream >> output;

    return output;
}
Maxime Oudot
  • 145
  • 1
  • 9
0

The trick is that you need to figure out how many digits each number contains. You can use log10 from <cmath> to do this. You can move the total by pow(10, x), where x is the number of digits you are adding:

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

int main() {
    vector<int>myints = {3, 55, 2, 7, 8};
    int total = 0;
    for (auto it = myints.begin(); it != myints.end(); ++it) {
        int x = int(log10(*it)) + 1;
        total = total * pow(10, x) + *it;
    }
    cout << total << endl;
    return 0;
}

The output is 355278, as expected.

Here is an IDEOne link.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264