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?
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;
}
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());
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With