Hii I know that a vector allocates continuous fixed memory when it needs to push_back some elements. And if he can not fit into it, he will alllocate the new memory and copy the old values into it and delete the old memory. If so, the following code works
#include<iostream>
#include<vector>
using namespace std;
class Test
{
public :
int val;
Test()
{
val=0;
}
};
int main()
{
vector<Test>vec;
Test t[10];
for (int i=0;i<5;i++)
vec.push_back(t[i]);
cout<<vec.capacity()<<endl;
Test* obj=&vec[2];
obj->val=2;
cout<<obj<<endl;
for (int i=0;i<5;i++)
vec.push_back(t[i]);
Test* obk=&vec[2];
cout<<obk->val<<endl;
cout<<obj->val<<endl;
cout<<obj<<endl;
cout<<obk<<endl;
}
Here, if you see that obj accepts the vec [2] pointer, whose value on my machine comes 0x8bcb048. Then I insert 5 more elements, so the vector will allocate new memory. Now, if I take obk from the vector [2] its next address is 0x8bcb070. But if I try to persuade me using obj, this will not give any problem. Any reason?
source
share