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.)
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 ).
insert() doesn't overwrite.
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.
Time complexity: k*log(n) where n is size of map, k is no. of elements inserted.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With