c ++字符串数组初始化

poy*_*poy 22 c++ arrays string initialization

我知道我可以用C++做到这一点:

string s[] = {"hi", "there"};
Run Code Online (Sandbox Code Playgroud)

但是,无论如何都要以这种方式对阵列进行delcare而不进行删除string s[]吗?

例如

void foo(string[] strArray){
  // some code
}

string s[] = {"hi", "there"}; // Works
foo(s); // Works

foo(new string[]{"hi", "there"}); // Doesn't work
Run Code Online (Sandbox Code Playgroud)

Xeo*_*Xeo 18

在C++ 11中你可以.事先说明:不要new数组,没有必要.

首先,string[] strArray是一个语法错误,应该是string* strArraystring strArray[].我假设只是为了示例,您没有传递任何大小参数.

#include <string>

void foo(std::string* strArray, unsigned size){
  // do stuff...
}

template<class T>
using alias = T;

int main(){
  foo(alias<std::string[]>{"hi", "there"}, 2);
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果您不需要将数组大小作为额外参数传递会更好,谢天谢地有一种方法:模板!

template<unsigned N>
void foo(int const (&arr)[N]){
  // ...
}
Run Code Online (Sandbox Code Playgroud)

请注意,这只会匹配堆栈数组,例如int x[5] = ....或者是临时的,使用alias上面创建的.

int main(){
  foo(alias<int[]>{1, 2, 3});
}
Run Code Online (Sandbox Code Playgroud)


小智 9

在C++ 11之前,您无法使用类型[]初始化数组.然而,最新的c ++ 11提供(统一)初始化,因此您可以这样做:

string* pStr = new string[3] { "hi", "there"};
Run Code Online (Sandbox Code Playgroud)

http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init