[英]c++ string array initialization
我知道我可以用C ++做到这一点:
string s[] = {"hi", "there"};
但是,无论如何都要以这种方式对数组进行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
在C ++ 11中你可以。 事先说明:不要new
的阵列,没有必要。
首先, string[] strArray
是一个语法错误,应该是string* strArray
或string 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);
}
请注意,如果您不需要将数组大小作为额外参数传递会更好,谢天谢地有一种方法:模板!
template<unsigned N>
void foo(int const (&arr)[N]){
// ...
}
请注意,这只会匹配堆栈数组,例如int x[5] = ...
或者是临时的,通过使用上面的alias
创建的。
int main(){
foo(alias<int[]>{1, 2, 3});
}
在C ++ 11之前,您无法使用类型[]初始化数组。 然而,最新的c ++ 11提供(统一)初始化,因此您可以这样做:
string* pStr = new string[3] { "hi", "there"};
见http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init
通过支持C ++ 11初始化列表,它非常简单:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
using Strings = vector<string>;
void foo( Strings const& strings )
{
for( string const& s : strings ) { cout << s << endl; }
}
auto main() -> int
{
foo( Strings{ "hi", "there" } );
}
缺乏(例如对于Visual C ++ 10.0),您可以执行以下操作:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef vector<string> Strings;
void foo( Strings const& strings )
{
for( auto it = begin( strings ); it != end( strings ); ++it )
{
cout << *it << endl;
}
}
template< class Elem >
vector<Elem>& r( vector<Elem>&& o ) { return o; }
template< class Elem, class Arg >
vector<Elem>& operator<<( vector<Elem>& v, Arg const& a )
{
v.push_back( a );
return v;
}
int main()
{
foo( r( Strings() ) << "hi" << "there" );
}
在C ++ 11及更高版本中,您还可以使用初始化列表初始化std::vector
。 例如:
using namespace std; // for example only
for (auto s : vector<string>{"one","two","three"} )
cout << s << endl;
所以,你的例子将成为:
void foo(vector<string> strArray){
// some code
}
vector<string> s {"hi", "there"}; // Works
foo(s); // Works
foo(vector<string> {"hi", "there"}); // also works
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.