Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert vector<int> to integer

Tags:

c++

stl

stdvector

I was looking for pre-defined function for converting a vector of integers into a normal integer but i din't find one.

vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);

Need this:

int i=123 //directly converted from vector to int

Is there a possible way to achieve this?

like image 958
Chirag Shah Avatar asked Mar 28 '17 17:03

Chirag Shah


4 Answers

Using C++ 11:

reverse(v.begin(), v.end());
int decimal = 1;
int total = 0;
for (auto& it : v)
{
    total += it * decimal;
    decimal *= 10;
}

EDIT: Now it should be the right way.

EDIT 2: See DAle's answer for a shorter/simpler one.

For the sake of wrapping it into a function to make it re-usable. Thanks @Samer

int VectorToInt(vector<int> v)
{
    reverse(v.begin(), v.end());
    int decimal = 1;
    int total = 0;
    for (auto& it : v)
    {
        total += it * decimal;
        decimal *= 10;
    }
    return total;
}
like image 117
Rafael Avatar answered Nov 17 '22 11:11

Rafael


If elements of vector are digits:

int result = 0;
for (auto d : v)  
{
    result = result * 10 + d;
}

If not digits:

stringstream str;
copy(v.begin(), v.end(), ostream_iterator<int>(str, ""));
int res = stoi(str.str());
like image 37
DAle Avatar answered Nov 17 '22 10:11

DAle


One liner with C++11 using std::accumulate():

auto rz = std::accumulate( v.begin(), v.end(), 0, []( int l, int r ) {
    return l * 10 + r; 
} );

live example

like image 27
Slava Avatar answered Nov 17 '22 12:11

Slava


In conjunction with the answer provided by deepmax in this post Converting integer into array of digits and the answers provided by multiple users in this post, here is a complete test program with a function to convert an integer to a vector and a function to convert a vector to an integer:

// VecToIntToVec.cpp

#include <iostream>
#include <vector>

// function prototypes
int vecToInt(const std::vector<int> &vec);
std::vector<int> intToVec(int num);

int main(void)
{
  std::vector<int> vec = { 3, 4, 2, 5, 8, 6 };

  int num = vecToInt(vec);

  std::cout << "num = " << num << "\n\n";

  vec = intToVec(num);

  for (auto &element : vec)
  {
    std::cout << element << ", ";
  }

  return(0);
}

int vecToInt(std::vector<int> vec)
{
  std::reverse(vec.begin(), vec.end());

  int result = 0;

  for (int i = 0; i < vec.size(); i++)
  {
    result += (pow(10, i) * vec[i]);
  }

  return(result);
}

std::vector<int> intToVec(int num)
{
  std::vector<int> vec;

  if (num <= 0) return vec;

  while (num > 0)
  {
    vec.push_back(num % 10);
    num = num / 10;
  }

  std::reverse(vec.begin(), vec.end());

  return(vec);
}
like image 1
cdahms Avatar answered Nov 17 '22 11:11

cdahms