Vector Problem

Started by
1 comment, last by Agony 17 years, 7 months ago
I just created this program using vectors, as a little refresher, and I can't seem to get it to work

#include <iostream>
#include <conio.h>
#include <vector>

using namespace std;

int main()
{
    vector <int> num( 25, 50, 75 );
    
    cout << num.at(0) << endl;
    cout << num.at(1) << endl;
    cout << num.at(2) << endl;
    
    getch();
    return 0;
}


I get the error: no matching function for call to 'std::vector<int::allocator<int> > vector(int,int,int)'
Advertisement
You can't specify the contents of the vector in the constructor. One fairly common way to work around this is to construct from an array:
#include <iostream>#include <vector>using namespace std;// a handy pair of templates for getting pointers to the// first and one-past-the-end elements of a stack arraytemplate < typename Type, std::size_t n >Type const * begin(Type (&array)[n]){	return array;}template < typename Type, std::size_t n >Type const * end(Type (&array)[n]){	return array + n;}int main(){	int num_data[] = {25, 50, 75};	// use iterator range to construct vector	vector <int> num(begin(num_data), end(num_data));    	cout << num.at(0) << endl;	cout << num.at(1) << endl;	cout << num.at(2) << endl;}

Σnigma
Not a comment providing a solution, but it might be worth knowing that in a few years, you might be able to initialize vectors and other containers just like arrays. (Google: "C++0x initializer lists")
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke

This topic is closed to new replies.

Advertisement