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

遍历std::vector<std::string>字符时触发vector越界的问题排查

问题分析与修复方案

越界错误原因

核心问题出在内部循环的字符插入逻辑中:你错误使用了userData.at(r)来获取字符,但r是当前遍历的字符串索引,而非外层userData这个vector的索引。当r的值大于等于userData.size()时,调用userData.at(r)就会触发vector越界异常。

同时,allVows和allCons是std::vector<std::string>类型,直接插入单个char会隐式转换,但更规范的做法是显式构造std::string对象。

修复后的代码

#include <cctype> // 用于std::tolower

void splitVowFromCons(std::vector<std::string>& userData, std::vector<std::string>& allCons, std::vector<std::string>& allVows){
    // 用size_t代替int,匹配vector.size()的无符号返回类型
    for (size_t q = 0; q < userData.size(); q++){
        // 用const引用避免字符串拷贝,提升效率
        const std::string& userDataCheck = userData.at(q);
        for (size_t r = 0; r < userDataCheck.size(); r++){
            char currChar = userDataCheck.at(r);
            char lowerChar = std::tolower(currChar);
            
            // 简化元音判断逻辑
            if (lowerChar == 'a' || lowerChar == 'e' || lowerChar == 'i' || lowerChar == 'o' || lowerChar == 'u'){
                // emplace_back直接在容器内构造string,比push_back更高效
                allVows.emplace_back(1, currChar);
            }
            else if ((currChar >= 'A' && currChar <= 'Z') || (currChar >= 'a' && currChar <= 'z')){
                allCons.emplace_back(1, currChar);
            }
            // 非字母直接跳过,无需多余的continue
        }
    }
}

关键修复点

  1. 替换userData.at(r)为currChar(来自当前字符串userDataCheck的字符),并显式构造std::string对象插入容器。
  2. 使用std::tolower统一转换字符为小写,简化元音判断的重复代码。
  3. 用size_t作为循环变量类型,避免无符号/有符号类型比较的警告。
  4. 对userDataCheck使用const引用,避免不必要的字符串拷贝。
  5. 用emplace_back替代push_back,提升容器插入效率。
  6. 移除了else分支中多余的分号(continue;;)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:15:31