Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I rely on std::map::operator[] to touch?

Tags:

I have a C++ program in which I want to insert default values for any keys missing in a std::map. I'm thinking the easiest way to do this would be to use std::map::operator[]() like the POSIX touch command - that is, to leave the value unchanged if it already exists, but to create it if it doesn't. For example,

#include <map> #include <vector> #include <iostream>  using namespace std;  int main() {     vector<int> keys = {0, 1};      map<int, int> m;     m[1] = 5;     m[2] = 12;      for (const int i : keys)     {         m[i]; // touch value     }      for (auto const & kv : m)     {         cout << kv.first << ", " << kv.second << endl;     } } 

Can I be sure that the compiler won't optimize out the m[i]; statements, since I'm not "doing" anything with them? (Not explicitly assigning to, not reading from.)

like image 909
cp.engr Avatar asked Oct 12 '15 21:10

cp.engr


People also ask

Does std::map use == operator?

std::relational operators (map) The equality comparison ( operator== ) is performed by first comparing sizes, and if they match, the elements are compared sequentially using operator== , stopping at the first mismatch (as if using algorithm equal ).

Does map insert overwrite?

insert() doesn't overwrite.

What is std::map used for?

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare . Search, removal, and insertion operations have logarithmic complexity.

What is the complexity of std::map :: insert () method?

Time complexity: k*log(n) where n is size of map, k is no. of elements inserted.


2 Answers

Yes you can be sure. Optimizing the call away would change the observable behavior of your program, and the compiler is not allowed to do this (except in the case of RVO).

This is known as the as-if rule.

like image 91
Baum mit Augen Avatar answered Sep 17 '22 01:09

Baum mit Augen


Yes, you can be sure. It's perhaps more intuitive when you consider that the line in question is equivalent to this:

m.operator[](i); 

…and you don't expect arbitrary function calls to be optimised out of your program, if they do anything.

like image 38
Lightness Races in Orbit Avatar answered Sep 17 '22 01:09

Lightness Races in Orbit