You need to enable JavaScript to run this app. 从二维std::vector向变量赋值时出现E0349运算符匹配错误
优惠活动
大模型
产品
解决方案
定价
更多

从二维std::vector向变量赋值时出现E0349运算符匹配错误

解决二维std::vector元素赋值的编译错误

你代码里的核心问题是错误使用了二维vector的元素访问语法:

你写的vec_data[0, 0]不是C里访问二维容器元素的正确方式。这里的逗号是C的逗号运算符,它会先执行左侧表达式(无实际作用),然后返回右侧的值,所以vec_data[0, 0]实际等价于vec_data[0]——这是一个std::vector<std::string>类型的对象,而你要赋值给std::string变量,类型不匹配,因此触发了E0349赋值运算符不匹配的错误。

正确写法

访问二维std::vector的元素需要使用两层方括号:第一层访问外层vector的元素(得到内层vector),第二层访问内层vector的元素(得到具体字符串)。修改后的完整代码如下:

#include <vector>
#include <string>

int main() // 注意:C++标准规定main函数必须返回int,不能用void
{
    std::string str_hi;
    std::string str_how;
    std::string str_goodbye;

    std::vector<std::vector<std::string>> vec_data
    {
        { "Hi", "" },
        { "How are you ?", "" },
        { "Good bye :)", "" }
    };

    str_hi = vec_data[0][0];
    str_how = vec_data[1][0];
    str_goodbye = vec_data[2][0];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:34:50