哪里错了?

时间:2019-05-26 07:44:50

标签: c++11

编译器错误     错误C2440'=':无法从'const std :: basic_string,std :: allocator>'转换为'const char *'

int main(void)
{

    /*
    complier error
    Error   C2440    '=': cannot convert from 'const std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'const char *' 
    primer  C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\VC\Tools\MSVC\14.22.27706\include\xutility  1745
    */
    list<string> names = {"A","B"};
    vector<const char*> vnames;
    vnames.assign(names.cbegin(), names.cend());//OK
    /*for (auto it = names.cbegin(); it != names.cend(); ++it)
    {
        cout << *it << endl;
    }*/
    for (auto it = vnames.cbegin(); it != vnames.cend(); ++it)
    {
        cout << *it << endl;
    }
    cout << "hello world" << endl;
    return 0;
}

1 个答案:

答案 0 :(得分:0)

此:

vnames.assign(names.cbegin(), names.cend());//OK

您的评论说“确定”,但不正确。您无法将std::string个对象分配给const char*个对象。如果要获取每个std::string的C字符串指针并将其放入vnames,则必须:

for (const auto& i : names) {
    vnames.push_back(i.c_str());
}

此后,您需要非常小心,不要以任何会导致重新分配的方式修改names向量。这样做会使存储在vnames中的指针无效。