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

C++中如何将字符串初始化列表以指针形式传递给函数?

问题描述

尝试将初始化列表以指针形式传递给check()函数,代码如下:

#include <bits/stdc++.h>
using namespace std;

void check(vector<std::string>* vecptr) {
    cout << "size of vecptr: " << vecptr->size() << endl;
}

int main() {
    check({"hello", "there", "how", "are", "you"});
    return 0;
}

编译时报错:

error: cannot convert ‘<brace-enclosed initializer list>’ to ‘std::vector<std::__cxx11::basic_string<char> >*’

请问如何将这类硬编码的初始化列表以指针形式传递?

解决方法

初始化列表本身不是具体的对象,无法直接转换成指针,必须先将其转为vector<string>对象后再传递指针,有两种可行方式:

方式1:显式构造临时对象并取地址

调用函数时直接显式构造vector,再用&取其地址传递:

check(&vector<string>{"hello", "there", "how", "are", "you"});

临时对象的生命周期会覆盖整个函数调用过程,check()内部访问指针是安全的。

方式2:创建局部变量后传递指针

如果需要后续复用该容器,可以先定义局部变量,再传递它的地址:

int main() {
    vector<string> vec{"hello", "there", "how", "are", "you"};
    check(&vec);
    return 0;
}

额外优化建议

如果不是必须使用指针,更推荐用常量引用替代指针:它既能直接接收初始化列表,又避免了空指针风险,代码更简洁安全:

void check(const vector<std::string>& vec) {
    cout << "size of vec: " << vec.size() << endl;
}

int main() {
    check({"hello", "there", "how", "are", "you"});
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 18:10:36