vector initialization with array

can anyone please look at this code and tell me what's wrong?

#include <iostream>
#include <vector>

int a[] = { 1,2,3,4,5,6,7,8,9,10 }; //array of 10

vector<int> gv(a, a + sizeof(a)/sizeof(*a));


int main {

for (int i = 0; i < gv.size(); i++) {
cout << "gv[ " << gv[i] << "] " <<endl;
}
}


it wont compile and it says:

vec.cpp:6: error: expected constructor, destructor, or type conversion before '<' token
vec.cpp:9: error: invalid function declaration

HELP please.
You need to prefix symbols from the standard libraries with std::

 
std::vector<int> gv(a, a + sizeof(a)/sizeof(*a));

Last edited on
oh. *phew* thank you, that worked :D
I personally don't find that array notation to be particularly useful. You might as well just size it with a constant and avoid the error prone sizeof functions. What you have coded there works in that specific case but before you know it you'll end up trying that on a c-array passed to a function and find out the hard way that it doesn't work.
Hi!
I have a problem. If I write
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
int n;
cout<<"Input n: ";
cin>>n;
vector<int> V(n);
for (int i=0;i<V.size();i++)
{
cout<<"Input value V["<<i<<"]= ";
cin>>V[i];
}
for (int i=0; i<V.size(); i++)
cout << "V["<<i<<"]= " << V[i] << endl;
system("pause");
return 0;
}
Program is run but if i write

#include <iostream>
#include <vector>
#define space (char)32
using namespace std;
void Nhap(vector<int>V,int &size)
{
cout<<"Input size: ";
cin>>size;
for(int i = 0 ; i < size ; i++)
{
cout << "Input value V[" << i << " ";
cin >> V[i];
}
return;
}
void Xuat(vector<int>V,int size)
{
for(int i = 0 ; i < 5 ; i++)
cout << space << V[i];
cout << endl;
return;
}
int main()
{
int size;
vector <int> V;
Nhap (V,size);
Xuat (V,size);
system("pause");
return 0;
}

program can't complie althought no error, why?


Topic archived. No new replies allowed.