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

如何将指定格式的字符串转换为C++的vector<vector<int>>二维向量?

解决字符串转二维vector的问题

我懂你这种明明思路对却卡在字符串解析上的无奈!咱们先揪出你代码里的问题:

你用ss >> temp时,默认是按空白分割字符串,所以拿到的temp会是[[1,4],、[5,7],、[4,1],、[8,9]]这些带括号和逗号的片段。之后你试图用ss2 >> x >> y直接读整数,但[、]、,这些符号会干扰流的整数解析逻辑,导致x和y根本读不到,最终每个子向量t都是空的,vec自然不符合预期。

下面给你两种实用的解决思路,都能精准解析出你要的二维vector:

方法一:逐字符过滤+读取数字

这种方法逻辑直观,手动处理每个字符,只提取有效数字并组织成子向量:

#include<iostream>
#include<sstream>
#include<vector>
#include<cctype>
using namespace std;

int main() {
    string str = "[[1,4], [5,7], [4,1], [8,9]]";
    vector<vector<int>> vec;
    stringstream ss(str);
    char c;
    vector<int> current_subvec;

    while (ss >> c) {
        // 遇到左括号,准备新的子向量
        if (c == '[') {
            current_subvec.clear();
        }
        // 遇到数字(含负数符号),读取完整整数
        else if (isdigit(c) || c == '-') {
            ss.unget(); // 把刚读的字符放回流,方便读取完整数字
            int num;
            ss >> num;
            current_subvec.push_back(num);
        }
        // 遇到右括号,把当前子向量加入二维vector
        else if (c == ']' && !current_subvec.empty()) {
            vec.push_back(current_subvec);
        }
        // 逗号、空格这类分隔符直接跳过,不用处理
    }

    // 验证输出
    for (int i = 0; i < vec.size(); ++i) {
        cout << "vec[" << i << "] = {" << vec[i][0] << ", " << vec[i][1] << "}" << endl;
    }
    return 0;
}

方法二:字符串分割处理

先剥离外层括号,再拆分出每个子数组的字符串,最后提取数字:

#include<iostream>
#include<sstream>
#include<vector>
#include<string>
using namespace std;

// 辅助函数:按指定分隔符分割字符串
vector<string> split(const string& s, char delim) {
    vector<string> tokens;
    string token;
    istringstream token_stream(s);
    while (getline(token_stream, token, delim)) {
        if (!token.empty()) {
            tokens.push_back(token);
        }
    }
    return tokens;
}

int main() {
    string str = "[[1,4], [5,7], [4,1], [8,9]]";
    // 去掉首尾的外层括号
    string content = str.substr(1, str.size() - 2);
    // 按"], "分割出每个子数组的字符串
    vector<string> sub_strs = split(content, ']');
    
    vector<vector<int>> vec;
    for (string& sub : sub_strs) {
        // 去掉子字符串开头的" ["
        size_t bracket_pos = sub.find('[');
        if (bracket_pos != string::npos) {
            sub = sub.substr(bracket_pos + 1);
        }
        // 按","分割数字字符串
        vector<string> num_strs = split(sub, ',');
        vector<int> temp_subvec;
        for (string& num_str : num_strs) {
            // 去掉数字前后的空格
            size_t first_valid = num_str.find_first_not_of(' ');
            size_t last_valid = num_str.find_last_not_of(' ');
            if (first_valid != string::npos && last_valid != string::npos) {
                num_str = num_str.substr(first_valid, last_valid - first_valid + 1);
            }
            temp_subvec.push_back(stoi(num_str));
        }
        if (!temp_subvec.empty()) {
            vec.push_back(temp_subvec);
        }
    }

    // 验证输出
    for (int i = 0; i < vec.size(); ++i) {
        cout << "vec[" << i << "] = {" << vec[i][0] << ", " << vec[i][1] << "}" << endl;
    }
    return 0;
}

两种方法都能输出你想要的结果:vec[0]={1,4}、vec[1]={5,7}、vec[2]={4,1}、vec[3]={8,9},你可以根据自己的习惯选择使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:58:13