Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::map allocation static when possible?

Consider 3 versions of a code with the same effects:

Version 1:

int main()  {
    std::map<int,int> x = {{0,0}, {1,1}, {2,2}};
    // Do some stuff...
    return 0;
}

Version 2:

int main()  {
    std::map<int,int> x;
    x[0] = 0;
    x[1] = 1;
    x[2] = 2;
    // Do some stuff...
    return 0;
}

Version 3:

int main()  {
    std::map<int,int> x;
    x.insert(std::pair<int,int>(0,0));
    x.insert(std::pair<int,int>(1,1));
    x.insert(std::pair<int,int>(2,2));
    // Do some stuff...
    return 0;
}

What is the efficiency of each of these codes?

I think that version 1 is a fully static allocation: space required by x is allocated once and values are set. I also think that version 3 requires dynamic allocation: each call to insert will check if the key is not already used, check where to insert and allocate more space to map before assigning the value. For version 2, I am not sure. Could you help me with that?

like image 639
Benjamin Barrois Avatar asked Oct 19 '25 10:10

Benjamin Barrois


1 Answers

The C++ standard makes no requirements on whether the allocation happens at compile-time or run-time. All this means is that implementations are free to make their own optimizations (or not).

So the proper thing to do would be to test.

Most likely such optimizations have not been implemented. There is no constexpr constructor of std::map, despite the fact that the std::initializer_list you create here may be a compile-time constant (note that no aggregate initialization is being performed here either)

std::map<int,int> x = {{0,0}, {1,1}, {2,2}};
like image 123
AndyG Avatar answered Oct 21 '25 23:10

AndyG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!