c++ - 如何将所有元素合二为一?
问题描述
我的代码将一个整数解析为多个部分并将它们写入一个数组,但现在我想将该数组收集回一个整数。
我将修改数组内的数据,因此我需要在更改后收集所有内容。
int a = 123456789;
std::string stringInt = std::to_string(a);
std::vector<int> numbers;
numbers.reserve(stringInt.length());
for (const auto& chr : stringInt)
{
// ...
numbers.push_back(chr - '0');
cout << chr << "\n" << endl;
}
解决方案
您可以将整数相加,将结果乘以10
每次:
int b = 0;
for (const auto& chr : stringInt)
{
numbers.push_back(chr - '0');
b *= 10;
b += chr - '0';
}
std::cout << b << std::endl;
或者,您可以将字符放入字符串中,而不是int
将它们转换为向量并将它们放入向量中,然后用于std::stoi
从int
字符串中取出:
std::string numbers;
for (const auto& chr : stringInt)
{
numbers.push_back(chr);
cout << chr << "\n" << endl;
}
int b = std::stoi(numbers);
std::cout << b << std::endl;