开发者

how to fix error in std::vector<int> WidthNumbers = 320, 640, 1280;?

So I try to do something like std::vector<int> WidthNumber开发者_开发百科s = 320, 640, 1280; but compiler gives me error C2440: 'int' to 'std::vector<_Ty>'


You cannot initialize a vector using that syntax. C++0x allows initializer lists which allow you to use the following:

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

But this has not been implemented in VS2010. The alternatives are:

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


You can also use 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);
}


If your compiler supports C++0x (MSVC++2010 has partial support for C++0x) you can use an initializer list

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


This is slightly more work, but I find it works very well with VS 2010. Instead of using an Initializer List, you can manually add items to the vector using the _vector.push_back() method like so:

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

This is the way I personally declare and initialize vectors, it always works for me

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜