c++字符串数组初始化

c++ string array initialization

本文关键字:初始化 数组 字符串 c++      更新时间:2023-10-16

我知道我可以在C++中做到这一点:

string s[] = {"hi", "there"};

但是,在不delcare string s[]的情况下,有没有以这种方式delcare数组?

例如

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* strArraystring 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);
}

请注意,如果您不需要将数组大小作为额外的参数传递,那会更好,谢天谢地,有一种方法:Templates!

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