CArray SetSize and vector resize – How it behaves?
#include <iostream>
#include <vector>
#include <string>
#include <afxtempl.h>
using namespace std;
int main()
{
// MFC Array
CArray<CString,CString> mfcArray;
mfcArray.SetSize( 10 );
mfcArray.Add(“Test Data”);
mfcArray.Add(“Test Data”);
mfcArray.Add(“Test Data”);
mfcArray.Add(“Test Data”);
mfcArray.Add(“Test Data”);
cout<<”CArray size after operations”<<mfcArray.GetSize()<<endl;
// STL Array
vector<string> stlArray;
stlArray.resize( 10 );
stlArray.push_back(“Test Data”);
stlArray.push_back(“Test Data”);
stlArray.push_back(“Test Data”);
stlArray.push_back(“Test Data”);
stlArray.push_back(“Test Data”);
cout<<”STL Array size”<<stlArray.size();
return 0;
}
I’m using the above code to insert some items from the location 0 in the mfcArray. What’s the problem with the MFC array code? The above code will not serve our purpose. This is a common mistake to happen while we use the MFC templates. “SetSize” function will reserve the items and allocates the memory. We have to use “SetAt” function (it will not grow the array size) to insert for the proper allocation. If we use “InsertAt” function, again we are making bug because InsertAt function will also grow the array size. The “Add” function will append data to the end of array. So after the complete operations, the mfcArray will have 15 items and the 5 items I inserted will be there at the end of array. The first 10 elements will be blank. STL also behaves same as MFC templates. Just be aware about this.
about 1 year ago
Your’re my hero! Thanks for pointing this out.
Cheers, Jonas
PS: for the lucky ones that don’t have to use MFC: use stlArray.reserve(10) to allocate the memory, but not create any elements.
PPS: The stl will create elements 0-9 of stlArray using the standard constructor of it’s element type. In this case they will be empty strings. Any Ideas on how MFC behaves?