Inside the for
loop body, you have:
(*pVectorTemp_)[index1] = (pvecTemp);
But note that the index of the for
loop is i
(index1
is the upper bound).
So, I think you have a typo or bug, and you may want to use i
(not index1
) as index inside [...]
.
Note also that you have a signed
/unsigned
mismatch, since in the loop you have unsigned int
as index, and you compare that with index1
, which is a signed integer.
But, anyway, your code is uselessly complicated.
You don't need to allocate all these vectors on the heap with new
.
Just use automatic ("stack") allocation, e.g.:
int main()
{
int index1 = 2;
int index2 = 2;
// Your original code is commented out:
//
// vector<vector<float>*>* pVectorTemp_ = NULL;
// pVectorTemp_ = new vector<vector<float>*>();
vector<vector<float>> vectorTemp;
// pVectorTemp_->resize(index1);
// Just consider calling push_back.
for (int i = 0; i < index1; i++)
{
// vector<float>* pvecTemp = new vector<float>();
// pvecTemp->resize(index2);
// (*pVectorTemp_)[index1] = (pvecTemp);
vectorTemp.push_back(vector<float>(index2));
}
// No need for return 0 in main().
// return 0;
}
See how the code gets simplified!
(Code without comments follows.)
int main()
{
int index1 = 2;
int index2 = 2;
vector<vector<float>> vectorTemp;
for (int i = 0; i < index1; i++)
{
vectorTemp.push_back(vector<float>(index2));
}
}
As a further improvement, assuming that your C++ STL implementation provides that, you may want to use emplace_back()
instead of push_back()
, to build the nested vectors:
// Instead of vectorTemp.push_back(vector<float>(index2));
//
vectorTemp.emplace_back(index2);
In this case, a vector
of size index2
is built directly into the vectorTemp
("outer" vector) container, without temporaries.
You may want to read also this thread on StackOverflow for further details:
push_back vs. emplace_back