【问题标题】:How to collect all the elements into one?如何将所有元素合二为一?
【发布时间】:2019-10-17 09:53:57
【问题描述】:

我的代码将一个整数解析为多个部分并将它们写入一个数组,但现在我想将该数组收集回一个整数。

我将修改数组中的数据,所以我需要在更改后收集所有内容。

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

【问题讨论】:

  • 你的问题是......?

标签: c++ string vector integer


【解决方案1】:

您可以将整数相加,每次将结果乘以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::stoiint 从字符串中取出:

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;

【讨论】:

  • 我喜欢第二个例子,但我不知道我是否可以不使用数组来计数。
  • 我可以这样做吗? chr++;
  • @chip 你可以做到。请注意,因为它是 char,当它的值为 '9' 时增加它会使其不再是有效数字。
  • 知道了,谢谢,for 循环是否将所有内容都变成了字符?例如可以更改为 int 吗?
  • @chip 在这个循环中,chr 是一个char,因为std::stringchar 的容器,可以这么说,所以当你迭代它的元素时,你会得到字符。当然,您可以将chr 分配给int 变量或以其他方式将其转换为其他内容。只要您放入另一个容器中的元素是正确的,这一切都很好。例如,如果numbers 应该是一个只包含数字的std::string,那么您只能在其中添加代表数字的字符。
猜你喜欢
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 2013-07-05
  • 2012-08-14
  • 2021-11-18
  • 2014-05-26
  • 2022-01-25
  • 2023-02-15
相关资源
最近更新 更多