0

I'm novice to C++.Recently,teacher tell us.vector::reserve() and vector::resize() has similar function.But recently,I met a strange question.Any help is appreciate.

The problem is that:

struct SumStruct {
int operator ()(int v1, int v2) {
    return v1 + v2;
}
};
void test5()
{
vector<int> srcVec0;
srcVec0.push_back(3);

vector<int> srcVec1;
srcVec1.push_back(8);

vector<int> dstVec;
//use resize ok.
//dstVec.resize(2);
dstVec.reserve(2);
transform(srcVec0.begin(), srcVec0.end(), srcVec1.begin(), dstVec.begin(), SumStruct());

for_each(dstVec.begin(), dstVec.end(), [](const int & value) { cout << setw(4) << value; });
}

The problem is that. If you use dstVec.resize(2) ok,use dstVec.reserve(2) crash ,info as that(“vector iterator + offset out of range”).

I have google like

Choice between vector::resize() and vector::reserve()

Is “vector iterator + offset out of range” assertion useful at all?

Community
  • 1
  • 1
Chuanhang.gu
  • 870
  • 9
  • 13
  • 1
    The question you linked to should answer this one. Can you clarify what it is you need help with? – Borgleader Apr 28 '17 at 13:57
  • 1
    Seems like you have done some research and found out the answer. Not sure what your question is? If your " _teacher tell us.vector::reserve() and vector::resize() has similar function_" your teacher is wrong. – Happy Green Kid Naps Apr 28 '17 at 13:57
  • @FrançoisAndrieux This is not iterator invalidation because in the code all iterators are created *after* the resize/reserve operations. – Borgleader Apr 28 '17 at 13:57
  • @Borgleader I've misread the question and removed my comment. – François Andrieux Apr 28 '17 at 13:58
  • @Borgleader The answer possible in it.But can you clearly tell which sentence it is? They never info that vector::reserve() can cause crash. – Chuanhang.gu Apr 28 '17 at 14:12
  • @Borgleader My English is poor.I info that you don't think use reserve will crash. – Chuanhang.gu Apr 28 '17 at 14:14
  • 1
    `reserve()` doesn't cause a crash; writing to elements that do not exist is what may cause a crash (and is wrong/broken, even if it doesn't outright crash). The difference is that `resize()` created those elements, but `reserve()` didn't. The two functions are completely different so your teacher is wrong & dangerous. Furthermore, even if you'd used the right function, `dstVec` wouldn't big enough. 2 is less than 3. – Lightness Races in Orbit Apr 28 '17 at 14:32
  • Sorry, my answer is not quite right before, your code is OK with my computer. In STL, the memory management is not using `new`, instead, it use allocator and `placement new`, which means to allocate the memory first, the construct the object. `reserve()` just allocates the memory but doesn't construct the object, and `resize()` not only allocates the memory but also construct the object. When you access the memory that haven't been initialized, it is very dangerous. – Jiahao Cai Apr 28 '17 at 14:48

0 Answers0