Maximum possible size to allocate a vector

Asked

Viewed 1,101 times

2

Guys, I have a data structure project that’s meant to analyze search algorithms on the largest possible vector that my machine can allocate. Can someone help me figure out how to create a vector of maximum size?

The language is C++

  • 1

    Dude, the answer is down, but only a warning. Be careful not to burst the memory...

1 answer

1

Utilize std::vector::max_size, that function as a member of std::vector returns the maximum number of elements that a std::vector can handle 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 build the elements in place already) resize(size_type) also. 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 that, by the way, because that much memory is ridiculously large. Various processes in the system may start to fail due to lack of memory (consumed by that vector).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.