Maximum size possible to allocate a vector

2

Folks, I have a data structure project that is used to analyze search algorithms in the largest possible vector that my machine can allocate. Can anyone help me figure out how to create a vector of maximum size?

The language is C ++

    
asked by anonymous 14.03.2018 / 17:29

1 answer

1

Use std::vector::max_size , this member function of std::vector returns the maximum number of elements that a std::vector can handle in a specific system or implementation.

For example ( see online ):

#include <iostream>
#include <vector>
int main()
{
    std::vector<char> v;
    std::cout << "Tamanho máximo: " << v.max_size() << '\n';
}

To allocate this amount of elements contiguously, use the member function reserve(size_type) with the return of max_size() , or (if you want to already construct the elements in place) resize(size_type) equally. For example:

#include <vector>
int main()
{
    std::vector<int> v;
    v.resize(v.max_size()); // 'v' agora contém 'v.max_size()' elementos
                            // inicializados com zero.
}

Be very careful with this, in fact, because this much memory is ridiculously large. Several processes in the system may start to fail due to a lack of memory (consumed by this vector).

    
14.03.2018 / 17:45