c++ string array initialization
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});
}
Prior to C++11, you cannot initialise an array using type[]. However the latest c++11 provides(unifies) the initialisation, so you can do it in this way:
string* pStr = new string[3] { "hi", "there"};
See http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init
With support for C++11 initializer lists it is very easy:
#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" } );
}
Lacking that (e.g. for Visual C++ 10.0) you can do things like this:
#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" );
}