You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将C++ vector<int>元素按顺序拼接为字符串存储且不打印

C++ 将vector中整数按序拼接的实现方案

首先纠正你代码中的两处错误:

  1. 声明存储n个整数的vector的代码有误,vector<int> tostore[n]; 是声明了长度为n、元素类型为vector<int>的数组,正确写法是vector<int> tostore(n);
  2. 你示例中定义的int store_str; 类型存在溢出风险:如果拼接后的数字长度超过int的取值范围会直接溢出,优先推荐用std::string类型存储拼接结果,若确实需要存为整数,建议改用取值范围更大的long long同时做好溢出校验。

方案1:存储为字符串(推荐,无长度限制)

直接遍历vector,将每个元素转为字符串后拼接即可,代码如下:

#include <vector>
#include <string>
#include <iostream>

int main() {
    std::vector<int> store_vec{1,2,3,4,5};
    std::string store_str;
    for (int num : store_vec) {
        store_str += std::to_string(num);
    }
    // 验证输出
    std::cout << store_str << std::endl; // 输出结果:12345
    return 0;
}

方案2:存储为整数(仅适用于拼接结果较短的场景)

通过逐位进位的方式拼接为数字,需要提前判断溢出:

#include <vector>
#include <iostream>
#include <stdexcept>
#include <climits>

int main() {
    std::vector<int> store_vec{1,2,3,4,5};
    long long store_num = 0;
    for (int num : store_vec) {
        // 溢出校验,避免结果超出long long取值范围
        if (store_num > LLONG_MAX / 10 || (store_num == LLONG_MAX / 10 && num > LLONG_MAX % 10)) {
            throw std::overflow_error("拼接结果过长,超出整数类型取值范围,建议改用字符串存储");
        }
        store_num = store_num * 10 + num;
    }
    // 验证输出
    std::cout << store_num << std::endl; // 输出结果:12345
    return 0;
}

补充说明:如果vector中存储的是多位数,比如{12, 34, 5},两种方案都会得到12345的结果,符合拼接需求。

内容的提问来源于stack exchange,提问作者Aurorachilles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 13:24:03