【问题标题】:C++ Assign char** to an array of stringsC++ 将 char** 分配给字符串数组
【发布时间】:2019-10-14 17:53:35
【问题描述】:

我知道你可以给字符串赋值一个字符数组:

#include <string>
using std::string;

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

但是如何将字符数组(char**)分配给字符串数组呢?

【问题讨论】:

  • 你有没有尝试过?如果是这样,请发布您尝试过的内容并指出您遇到问题的地方。
  • 我无法发布任何示例,因为我不知道该怎么做。代码只针对第一句
  • @ryyker,是的,标准 C++ 库有一个 std::string 类。 string str = foo; 是一个完全有效的声明,因为它上面有 using std::string; 声明。

标签: c++ arrays string char


【解决方案1】:

你来了

#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;
}

程序输出是

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;
}

【讨论】:

    猜你喜欢
    • 2011-02-07
    • 2012-05-03
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 2014-06-08
    • 2012-10-16
    • 1970-01-01
    相关资源
    最近更新 更多