2010-12-05 66 views

回答

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); 
1

(MSVC++ 2010具有partial support for C++0x),你可以使用initializer list

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

但是,VC++ 2010的部分支持不*包含此功能。 – 2012-04-29 14:15:29

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; 
} 

这是我个人声明和初始化向量的方式,它总是对我的作品

相关问题