2010-12-05 27 views
1

は、だから私はstd::vector<int> WidthNumbers = 320, 640, 1280;ような何かをしようが、あなたのコンパイラがC++ 0xのをサポートしている場合、コンパイラは私にエラーC2440: 'int' to 'std::vector<_Ty>'std :: vectorのエラーを修正する方法<int> WidthNumbers = 320,640,1280 ;,

+0

私の作品、私は個人的にベクトルを宣言し、初期化する方法はありますか? –

+0

はい私はboost =を使用することができます=) – Rella

答えて

5

を使用することができますがすることはできませんその構文を使用してvectorを初期化します。 C++ 0xでは、次のものを使用できるようにするイニシャライザリストを使用できます。

std::vector<int> WidthNumbers = {320, 640, 1280}; 

これはVS2010では実装されていません。選択肢は次のとおりです。

int myArr[] = {320, 640, 1280}; 
std::vector<int> WidthNumbers(myArr, myArr + sizeof(myArr)/sizeof(myArr[0])); 

OR

std::vector<int> WidthNumbers; 

WidthNumbers.push_back(320); 
WidthNumbers.push_back(640); 
WidthNumbers.push_back(1280); 
+3

最初のオプションを使用する場合、次のテンプレートが便利です: 'template T * endof(T(&ra)[N]){return ra + N; } '。これは、C++ 0xの 'std :: end'が配列に対して行うのと同じポインタを返します。つまり、2行目が' std :: vector WidthNumbers(myArr、endof(myArr)); ' –

1

を与える(MSVC++ 2010がpartial support for C++0xを持っている)あなたはinitializer list

std::vector<int> WidthNumbers = {320, 640, 1280}; 
+0

しかし、VC++ 2010の部分的サポートはこの機能を含みません。 –

2

あなたはまた、boost::assign::list_of

#include <boost/assign/list_of.hpp> 

#include <vector> 

int 
main() 
{ 
    typedef std::vector<int> WidthNumbers; 
    const WidthNumbers foo = boost::assign::list_of(320)(640)(1280); 
} 
0

を使用することができますこれは少しより多くの仕事ですが、私はそれがVS 2010と非常によく動作します見つけます。イニシャライザリストを使用する代わりに、_vector.push_back()メソッドを使用してベクトルにアイテムを手動で追加することができます。

//forward declarations 
#include <vector> 
#include <iostream> 
using namespace std; 
// main() function 
int _tmain(int argc, _TCHAR *argv) 
{ 
    // declare vector 
    vector<int> _vector; 
    // fill vector with items 
    _vector.push_back(1088); 
    _vector.push_back(654); 
    _vector.push_back(101101); 
    _vector.push_back(123456789); 
    // iterate through the vector and print items to the console 
    vector<int>::iterator iter = _vector.begin(); 
    while(iter != _vector.end()) 
    { 
      cout << *iter << endl; 
      iter++; 
    } 
    // pause so you can read the output 
    system("PAUSE"); 
    // end program 
    return 0; 
} 

これは、ブーストを使用することができ、それは常に

関連する問題