【发布时间】:2020-09-09 17:51:52
【问题描述】:
我有一个遗留函数,其输入参数类型为 const char* 数组
myfunc(const char* names[]);
我有一组std::set<std::string> mynames;。该集合已被填充。
我必须将mynames 传递给myfunc
使用基于范围的循环,我有
const char* names[];
int i = 0;
for (const auto &name : mynames)
{
//allocate memory to names here
names[i] = name.c_str();
++i;
}
//call myfunc
myfunc(names);
有没有更好的方法来做到这一点?
【问题讨论】:
-
为什么不使用
std::vector<std::string> names;而不是const char* names[];?有什么好的理由吗?如果你真的需要这些指针,你可以随时使用std::string::c_str()来获取这些。 -
“更好”是非常主观的。恕我直言,最好修复
myfunc