Reputation: 75
i've got a issue with std::vector
class, i created a struct
struct Triplet{
int first;
int second;
int third;
};
And i created a vector<Triplet> T
.
My problem is that it won't contain as many elements as i need, even though T.max_size() = 357913941
i got only T.size() = 60540697
or T.size() = 40360465
using that function
vector<Triplet> T;
while(true)
{
Triplet t;
t.first = 1; t.second = 1 ; t.third = 1;
try {
T.push_back(t);
} catch (...) {
break;
}
}
qDebug() << T.size();
can anyone explain why is it doing that please ? i'm running on Windows 10 and 16Go of RAM, with Qt and VSC++ 2017 x86 (due to Lemon library which i couldn't compile for x64),
Upvotes: 1
Views: 582
Reputation: 30832
An std::vector
needs a contiguous (=no holes) chunk of memory to exist in.
Furthermore, when pushing elements to a vector you can overshoot the internal capacity, meaning that it has to allocate memory for another std::vector
(usually double the size) and copy the elements over.
Keep in mind that in 32-bit Windows programs, you only have 2 GB of available memory space to play with in a single process, regardless of how much memory your system has. Your vector with size 60540697 * 12 is taking up 700+ MB of that. There is simply no place to allocate the next size (1.4GB) because the memory space is too small.
The simplest solution is to compile in 64-bit mode, which has plenty of virtual memory. As a stop-gap solution you could try pre-allocating space in the std::vector
with T.reserve(80000000)
or so. This will avoid an intermediate copy but probably will not be enough. It might even fail if your memory space is fragmented in a bad way!
Upvotes: 8