我知道可以用C++完成这个操作:
string s[] = {"hi", "there"};
有没有办法在不声明 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++完成这个操作:
string s[] = {"hi", "there"};
有没有办法在不声明 string s[]
的情况下声明数组?
例如:
void foo(string[] strArray){
// some code
}
string s[] = {"hi", "there"}; // Works
foo(s); // Works
foo(new string[]{"hi", "there"}); // Doesn't work
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之前,你不能使用type[]初始化一个数组。然而,最新的C++11提供了(统一的)初始化方式,所以你可以这样做:
string* pStr = new string[3] { "hi", "there"};
支持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" } );
}
#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" );
}
for(auto s : strings) cout << s <<endl;
- rwststd::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
std::vector
。在使用C++11时,你可以使用初始化列表来构造它们。例如,void foo(vector<string>); foo({"hi", "there"});
应该在C++11中起作用。 - Grizzly