C ++字符串数组的初始化 [英] c++ string array initialization
问题描述
我知道我可以在C ++中做到这一点:
字符串s [] = {喜,那里};
不过,反正是有delcare阵列时不delcaring这样字符串s []
?
例如
无效美孚(字符串[] strArray){
//一些code
}字符串s [] = {喜,那里}; //作品
富(S); //作品美孚(新的String [] {喜,有}); //不工作
在C ++ 11即可。的注意事项事先:不要新
数组,就没有必要为
首先,的String [] strArray
是一个语法错误,要么是字符串* strArray
或字符串strArray []
。而且我认为它只是一个例子的缘故,你不传递任何大小参数。
的#include<串GT;无效美孚(标准::字符串* strArray,无符号大小){
// 做东西...
}模板<类T>
使用别名= T;诠释主(){
富(化名<的std ::字符串[]> {喜,有},2);
}
请注意,这将是更好,如果你没有需要通过数组的大小作为一个额外的参数,幸运的是还有一个办法:模板
模板<无符号N'GT;
无效美孚(INT常量(安培; ARR)[N]){
// ...
}
请注意,这将只匹配堆叠阵列,如 INT X [5] = ...
。或临时的人,通过上面的使用别名
创建的。
INT的main(){
富(别名&下; INT []≥{1,2,3});
}
I know I can do this in C++:
string s[] = {"hi", "there"};
But is there anyway to delcare an array this way without delcaring string s[]
?
e.g.
void foo(string[] strArray){
// some code
}
string s[] = {"hi", "there"}; // Works
foo(s); // Works
foo(new string[]{"hi", "there"}); // Doesn't work
In C++11 you can. A note beforehand: Don't new
the array, there's no need for that.
First, string[] strArray
is a syntax error, that should either be string* strArray
or string strArray[]
. And I assume that it's just for the sake of the example that you don't pass any size parameter.
#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);
}
Note that it would be better if you didn't need to pass the array size as an extra parameter, and thankfully there is a way: Templates!
template<unsigned N>
void foo(int const (&arr)[N]){
// ...
}
Note that this will only match stack arrays, like int x[5] = ...
. Or temporary ones, created by the use of alias
above.
int main(){
foo(alias<int[]>{1, 2, 3});
}
这篇关于C ++字符串数组的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!