web-dev-qa-db-ja.com

C ++文字列配列の初期化

私はこれを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
21
poy

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});
}
18
Xeo

C++ 11より前は、type []を使用して配列を初期化することはできません。ただし、最新のc ++ 11は初期化を提供(統合)するため、次の方法で実行できます。

string* pStr = new string[3] { "hi", "there"};

http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init を参照してください

9
Guangchun

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
1
DavidJ