C++:vector<string> 到 char**

Ing*_*nix 1 c++ vector

我正在将我的应用程序转换为能够用作库。为此,我想提供将字符串向量传递给库的默认运行例程的可能性。

我遇到的问题实际上是创建char**. 这是我当前的实现,在源代码中注释掉了,因为它不起作用:

IceTea* IceTea::setupCli(vector<string> strings) {
    int argc=strings.size(), i=0;
    char* argv[argc];
    vector<string>::iterator it;
    for(it=strings.begin(); it != strings.end(); ++it) {
        argv[i++] = (char*)it->c_str();
    }

    // Pass the char** to the original method.
    return this->setupCli(argc, argv);
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误:

src/IceTea.cpp:132:18: error: no matching member function for call to 'setupCli'
    return this->setupCli(argc, argv);
           ~~~~~~^~~~~~~~
src/IceTea.h:44:13: note: candidate function not viable: no known conversion from 'char *[argc]' to 'const char **' for 2nd argument
    IceTea* setupCli(int, const char**);
            ^
src/IceTea.cpp:124:17: note: candidate function not viable: requires single argument 'strings', but 2 arguments were provided
IceTea* IceTea::setupCli(vector<string> strings) {
Run Code Online (Sandbox Code Playgroud)

Arm*_*yan 5

恐怕您无法在恒定时间内将 a 转换为vector<string>to char**。Avector<string>可以string*很容易地转换为,也string可以char*很容易地转换为,但是 vector 不能转换为char**. 实际上,这是一个与为什么 anint[10][20]不能简单地转换为 an的问题非常相似int**

现在,如果你绝对必须这样做,那么

vector<char*> pointerVec(strings.size());
for(unsigned i = 0; i < strings.size(); ++i)
{
    pointerVec[i] = strings[i].data();
} //you can use transform instead of this loop
char** result = pointerVec.data();
Run Code Online (Sandbox Code Playgroud)

您的代码的主要问题是您使用的c_str是返回const char *. 请注意,我使用的是data()成员函数,它返回非常量指针。您的尝试和我的建议之间的另一个区别是您使用的数组长度不是常量表达式。这在标准 C++ 中是非法的。我改用了向量,后来将其转换为具有相同data()功能的指针。