I receive failure notice during compiling. Do I have to use pushback command or I can avoid it?Code:# include<vector>
....
main()
{
vector <int> k;
k[0]=1;
k[1]=2;
}
Printable View
I receive failure notice during compiling. Do I have to use pushback command or I can avoid it?Code:# include<vector>
....
main()
{
vector <int> k;
k[0]=1;
k[1]=2;
}
The vector name is a handle and only contains enough memory to allow the vector to manage the storage of it's elements. A vector internally allocates storage on the free store for the space to store the elements. So, if you don't tell a vector initially how many elements to create storage for, you have to use the vector class methods, like push_back() to create storage for a new element.
Code:#include <iostream>
#include <vector>
using namespace std;
int main()
{
int a[10];
cout<<sizeof a<<endl; //int's are 4 bytes each, so size=40
vector <int> v(10);
cout<<sizeof v<<endl; //size is only 16
v[0]=1;
v[1]=2;
cout<<v[0]<<endl<<v[1]<<endl;
vector <int> k; //doesn't create any memory for the elements
k.push_back(10);
k.push_back(20);
cout<<k[0]<<endl<<k[1]<<endl;
return 0;
}
What 7stud says is correct, but it can't be the cause for your error, because that stuff is not detected until runtime.
What is the error message you get? I see that you forgot to give main a return type.
Does it mean that size of a vector with one element is 0?
Maybe you forgot a using directive?Quote:
Originally Posted by strickey
Code:#include<vector>
using std::vector;
int main()
{
vector <int> k(2);
k[0]=1;
k[1]=2;
return 0;
}
The size (as returned by the size member function) will be 1. Internally however, the size of a vector object (as returned by sizeof) is fixed. The vector object maintains what are essentially some pointers to the data area (which grows as needed), along with a couple extra data variables that it needs:Quote:
Originally Posted by strickey
Output on my machine:Code:vector<int> v;
cout << sizeof(v) << ',' << v.size() << endl;
v.push_back(10);
cout << sizeof(v) << ',' << v.size() << endl;
v.push_back(20);
cout << sizeof(v) << ',' << v.size() << endl;
Code:16,0
16,1
16,2