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

C++如何将包含单个数字序列的字符串转换为每一位为元素的vector

C++数字字符串逐位转vector实现方案

实现原理

C++兼容ASCII的字符编码规范中,数字字符'0'~'9'的编码值是连续递增的,因此单个数字字符减去'0'即可得到对应的整型数值。

基础循环实现(兼容性好,易理解)

#include <string>
#include <vector>

using namespace std; // 若项目中不建议用全局using,可替换为std::前缀

int main() {
    string str = "00101";
    vector<int> num;
    // 预先分配空间,避免多次扩容带来的性能损耗
    num.reserve(str.size());
    
    for (char c : str) {
        // 可选校验逻辑:仅当字符是数字时才加入vector
        // if (isdigit(c)) {
        num.push_back(c - '0');
        // }
    }
    // 此时num即为{0,0,1,0,1},符合需求
    return 0;
}

STL算法简洁实现(C++11及以上版本支持)

#include <string>
#include <vector>
#include <algorithm> // transform算法所需头文件

int main() {
    std::string str = "00101";
    std::vector<int> num(str.size());
    std::transform(str.begin(), str.end(), num.begin(), [](char c) {
        return c - '0';
    });
    return 0;
}

注意事项

  • 上述实现默认输入字符串仅包含数字字符,若存在非数字字符,可通过isdigit()函数增加校验逻辑避免非法值
  • 两种实现的时间复杂度均为O(n),n为字符串长度,性能无显著差异

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:12:03