我知道我可以用C ++做到这一点:
string s[] = {"hi", "there"};
但是,无论如何都要以这种方式对数组进行delcare而不用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
答案 0 :(得分:18)
在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});
}
答案 1 :(得分:9)
在C ++ 11之前,您无法使用类型[]初始化数组。然而,最新的c ++ 11提供(统一)初始化,因此您可以这样做:
string* pStr = new string[3] { "hi", "there"};
请参阅http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init
答案 2 :(得分:4)
支持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" );
}
答案 3 :(得分:0)
在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