簡體   English   中英

C++ 將 char** 分配給字符串數組

[英]C++ Assign char** to an array of strings

我知道您可以將字符數組分配給字符串:

#include <string>
using std::string;

char foo[] = "foo";
string str = foo;

但是如何將字符數組 arrays (char**) 分配給字符串數組?

給你

#include <iostream>
#include <vector>
#include <iterator>

int main() 
{
    const char * a[] = { "Hello", "World" };

    std::vector<std::string> v( std::begin( a ), std::end( a ) );

    for ( const auto &s : v ) std::cout << s << ' ';
    std::cout << '\n';

    return 0;
}

程序 output 是

Hello World 

或者

#include <iostream>
#include <vector>

int main() 
{
    const size_t N = 2;
    const char ** a = new const char * [N] { "Hello", "World" };

    std::vector<std::string> v( a, a + N );

    for ( const auto &s : v ) std::cout << s << ' ';
    std::cout << '\n';

    delete [] a;

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM