配列を作って初期化するとこんな感じになります。
int a[] = {10, 20, 30};
どうすれば std::vector
を作成し、同じようにエレガントに初期化できますか?
私が知っている最良の方法は
std::vector<int> ints;
ints.push_back(10);
ints.push_back(20);
ints.push_back(30);
他に良い方法はありますか?
コンパイラがC++11をサポートしている場合は、単純に
std::vector<int> v = {1, 2, 3, 4};
これは GCC バージョン 4.4で利用可能です。残念ながら、VC++ 2010はこの点では遅れをとっているようです。
また、Boost.Assignというライブラリでは、マクロではないマジックを使って以下のようなことが可能になっています。
#include <boost/assign/list_of.hpp>
...
std::vector<int> v = boost::assign::list_of(1)(2)(3)(4);
あるいは
#include <boost/assign/std/vector.hpp>
using namespace boost::assign;
...
std::vector<int> v;
v += 1, 2, 3, 4;
しかし、これにはいくつかのオーバーヘッドがあることを覚えておいてください(基本的に、list_of
はフードの下でstd::deque
を構築します)。したがって、パフォーマンスが重要なコードでは、Yacoby氏の言うようにしたほうがよいでしょう。
C++0xでは、配列と同じようにできるようになりますが、現在の標準ではできません。
言語サポートのみで、使用することができます。
int tmp[] = { 10, 20, 30 };
std::vector<int> v( tmp, tmp+3 ); // use some utility to avoid hardcoding the size here
他のライブラリを追加できるのであれば、boost::assignmentを試してみてはいかがでしょうか。
vector<int> v = list_of(10)(20)(30);
配列のサイズをハードコーディングしないようにする。
// option 1, typesafe, not a compile time constant
template <typename T, std::size_t N>
inline std::size_t size_of_array( T (&)[N] ) {
return N;
}
// option 2, not typesafe, compile time constant
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
// option 3, typesafe, compile time constant
template <typename T, std::size_t N>
char (&sizeof_array( T(&)[N] ))[N]; // declared, undefined
#define ARRAY_SIZE(x) sizeof(sizeof_array(x))