簡體   English   中英

轉換矢量 <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對更短/更簡單的答案。

為了將其包裝成函數以使其可重復使用。 謝謝@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());

一個使用std :: accumulate()的 C ++ 11的襯墊:

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

實例

結合deepmax中由deepmax提供的答案將整數轉換為數字數組以及本文中多個用戶提供的答案,這里有一個完整的測試程序,其中包含將整數轉換為向量的函數和轉換為向量到整數:

// 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

現場演示

其他答案(截至19年5月)似乎只假設整數(也可能是0)。 我有負輸入,因此,我擴展了他們的代碼以考慮數字符號

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM