如何加入向量< int>到C 中的单个INT

How to join a vector<int> to a single int in C++?

本文关键字:INT 单个 int 何加入 向量 lt gt      更新时间:2023-10-16

如何将int的向量转换为c 中的单个int?

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

预期答案:355278

这是一种快速而肮脏的方式:

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());

这是一种无需字符串的方法:

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;

i /= 10是此处的关键位,因为它根据当前数字中的数字数来缩放数字,i

使用<string>库和+=操作员您可以在ints的向量上迭代,将每个数字施放为字符串并打印出结果:

#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
}

这应该完成工作。请注意,int可能不足以处理数字的数量。

#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;
}

诀窍是您需要弄清每个数字包含多少位。您可以使用<cmath>中的log10进行此操作。您可以通过pow(10, x)移动总数,其中x是您要添加的数字数:

#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;
}

输出为355278,如预期的。

这是一个IDEONE链接。