将向量<int> 转换为整数

Convert vector<int> to integer

我一直在寻找用于将整数向量转换为普通整数的预定义函数,但我没有找到。

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

需要这个:

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

有没有办法实现这个?

使用 C++ 11:

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

编辑:现在应该是正确的方法了。

编辑 2:请参阅 DAle 的 shorter/simpler 答案。

为了将其包装成一个函数以使其可重复使用。谢谢@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;
}

如果向量的元素是数字:

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

如果不是数字:

stringstream str;
copy(v.begin(), v.end(), ostream_iterator<int>(str, ""));
int res = stoi(str.str());

使用 C++11 的一个衬里 std::accumulate():

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

live example

结合deepmax在本postConverting integer into array of digits和多个用户在本post提供的答案,这里是一个完整的测试程序具有将整数转换为向量的函数和将向量转换为整数的函数:

// 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);
}

负数的工作解决方案!

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

template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

int vectorToInt(vector<int> v) {
  int result = 0;
  if(!v.size()) return result;
  result = result * 10 + v[0];
  for (size_t i = 1; i < v.size(); ++i) {
    result = result * 10 + (v[i] * sgn(v[0]));
  }
  return result;
}

int main(void) {
  vector<int> negative_value = {-1, 9, 9};
  cout << vectorToInt(negative_value) << endl;

  vector<int> zero = {0};
  cout << vectorToInt(zero) << endl;

  vector<int> positive_value = {1, 4, 5, 3};
  cout << vectorToInt(positive_value) << endl;
  return 0;
}

输出:

-199
0
1453

Live Demo

其他答案(截至 19 年 5 月)似乎仅假定 整数(也可能为 0)。我有负面输入,因此,我扩展了他们的代码以考虑 sign of the number