convert vector into char** C++

前端 未结 3 1857
慢半拍i
慢半拍i 2020-11-27 20:24

I have a vector variable. I need to pass it onto a method which accepts char**as an input parameter.

how to do this ? If

3条回答
  •  悲&欢浪女
    2020-11-27 20:46

    Galik's answer has a number of safety issues. Here is how I would do it in Modern C++:

    #include 
    #include 
    #include 
    
    void old_func(char** carray, std::size_t size)
    {
        for(std::size_t i(0); i < size; ++i)
            std::cout << carray[i] << '\n';
    }
    
    void other_old_func(const char** carray, std::size_t size)
    {
        for(std::size_t i(0); i < size; ++i)
            std::cout << carray[i] << '\n';
    }
    
    int main()
    {
        {
            std::cout << "modifiable version\n";
            std::vector strings{"one", "two", "three"};
            std::vector cstrings{};
    
            for(auto& string : strings)
                cstrings.push_back(&string.front());
    
            old_func(cstrings.data(), cstrings.size());
    
            std::cout << "\n\n";
        }
        {
            std::cout << "non-modifiable version\n";
            std::vector strings{"four", "five", "six"};
            std::vector cstrings{};
    
            for(const auto& string : strings)
                cstrings.push_back(string.c_str());
    
            other_old_func(cstrings.data(), cstrings.size());
            std::cout << std::endl;
        }
    }
    

    No messy memory management or nasty const_casts.

    Live on Coliru.

    Outputs:

    modifiable version
    one
    two
    three
    
    
    non-modifiable version
    four
    five
    six
    

提交回复
热议问题