5 ms·
Isn't that pretty common? The [] operator acts like find or insert default value, so you can do nice things like ++map[key]. The map.find(key) works if you don'
by camel-cdr 4y ago
Isn't that pretty common? The [] operator acts like find or insert default value, so you can do nice things like ++map[key]. The map.find(key) works if you don't want to insert, it will return map.end() if the key couldn't be found.
- deredede 4y agoMy only gripe with find() is that you can't do `if (auto it = map.find(key))`. Otherwise yes, that's the way.
- masklinn 4y ago> Isn't that pretty common? AFAIK basically just 3 wide-spread languages which do this, and they're all known for their idiosyncratic behaviour: C++, Perl, and PHP. A few languages provide this as opt-in via a subtype (Python's defaultdict) or init (Ruby's Hash.new with a block parameter). Some more will do it via an opt-in callsite API e.g. Python's `setdefault`, Java's `computeIfAbsent`, Rust's `entry` API.
- kragen 4y agoperl only does this in some cases; unlike with std::map, this is safe: my $x = $h{$v}; this is not safe because it autovivifies $h{$v} as an ARRAY ref: my $x = $h{$v}[$i]; with respect to idiosyncratic behavior, if a language doesn't have idiosyncratic behavior, it has no reason to exist; it's just gratuitously incompatible syntax for already-available semantics