【问题标题】:How to join a vector<int> to a single int in C++?如何在 C++ 中将 vector<int> 连接到单个 int?
【发布时间】:2018-03-07 22:18:36
【问题描述】:

如何在 c++ 中将整数向量转换为单个整数?

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

预期答案:355278

【问题讨论】:

  • 你会如何处理-1?
  • 循环和乘法似乎可以解决问题。
  • 提示:8 + 7*10 + 2*100 + 55*1000 + 3*100000.
  • 或带有&lt;&lt; 的循环到strstream。如果你想要一个字符串。请注意,如果您想要一个 int 输出,您将很快用完数字
  • 您需要检查 log10(x) 以查看现有数字乘以多少。

标签: c++ vector int


【解决方案1】:

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

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 中的位数向上扩展号码

【讨论】:

  • 不是我会做的那样,但可能比我的解决方案更好地处理底片。
  • 第二个例子中不需要声明 stringstream 流,因为它从未使用过
【解决方案2】:

诀窍是您需要弄清楚每个数字包含多少位数字。您可以使用来自&lt;cmath&gt;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 link

【讨论】:

  • 要摆脱编译器警告,最好明确地使用 static_cast
  • 按照警告所说的去做。
【解决方案3】:

这应该可以完成工作。请注意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;
}

【讨论】:

    【解决方案4】:

    使用&lt;string&gt; 库和+= 运算符,您可以遍历整数向量,将每个数字转换为字符串并打印结果:

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

    【讨论】:

      猜你喜欢
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 2013-02-18
      • 2016-11-07
      相关资源
      最近更新 更多