by colonwqbang · 3y ago · 0 comments
std::map<std::string, std::string> m;
(void) m["nonexistent"];
m.size(); // => 1
Is there a historic reason for this strange specification? Or is it just a concession make the "operator=" sugar work better?operator[] returns a reference to a slot in the map which can be read from or assigned to. Since the reference must be valid, you better have allocated a slot in the map that can be written to if the value didn’t exist.
- what is the dummy value? does the value type even have one?
- I don't think index-assignment (or attribute-assignment) is overloadable in C++, so you need `a[b]` to return something which can be assigned to, and proxy values tend to be really wonky (see: `vector<bool>`), so assigning to the result of the indexing would replace the dummy value
m["nonexistent"] = 1;
This would not work if you return a dummy value. from collections import defaultdict
m = defaultdict(int)
m["nonexistent"]
len(m) # => 1
There are examples of the opposite too, though. Ruby's Hash does not insert the entry: m = Hash.new(0)
m["nonexistent"]
m.length # => 0It does if you initialise the hash with a block to do so:
m = Hash.new {|h, k| h[k] = 0}
m["nonexistent"]
m.length # => 1
That is, essentially, what defaultdict does. Just through subclassing (because `dict` does not provide such a fallback, but it has a magic method you can override to customise the mapping's behaviour in that case).if norvig isn't smart enough to use defaultdict without introducing bugs then i'm not either
(I am sure I never reported anything about the sudoku solver, since I never studied it.)
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.
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 semanticsEspecially annoying when looking up something in a const& map.
The alternative approach could have been to make operator[]= and operator[] different.
foo[bar] += baz;
... needs to provide operator+= with a mutable reference to foo[bar], and a maybe immutable reference to baz.
auto [it, newly_created] = m.try_emplace(key);
Does the same, and gives back more information. For something like `m[key] = value`, you can do `m.insert_or_assign(key, value)`, and save the default construction + assignment when the key was not there.For ordinary lookup you don't want to randomly mutate the map anyway. If your reference to the map is const, you can't use operator[] anyway, fortunately. However `m.at(key)` is not great either when the key not being present is really not exceptional, and the dance with `m.find(key)` is often not too ergonomic. I still suggest to just use `find` here.
operator[] does more than lookup, but there are other functions for the other stuff. It should be pretty clear...?
Comparing to other languages I know, I couldn't think of another where collection[key] denotes insertion.
C++ simply generalized this model to all collections, in line with the overall "better C" design. But then for maps it means that [] has to proactively create an entry if you want []= to work like it does everywhere else.
Similarly, C++ iterators are generalized C pointers, which is also not an ideal abstraction in practice (and why few other languages do it that way).
It is just very convenient (hence the existence of defaultdict in python).
if(auto i = x.find(y); i!=x.end()){
// use i->{first,second}
}
Also ideally you should be able to do this: for(auto [key, value]: x.equal_range(y)) {
}
But infuriatingly, x.equal_range returns a pair instead of some range view so you need some additional infrastructure (either convert the result of equal range into a range or add some begin/end overloads for pair).The equal_range solution looks nice from a genericity perspective (look ma I do multimaps!) but is really unintuitive with regular maps imo. Unless I'm mistaken it also does not allow an else branch for when the value is not there, which is often needed.
In practice C++ APIs where you'd naturally write Option<&T> use pointers and are consequently easier to use wrong, this is an example of Rust actually providing improved safety technology (whereas many commonly identified safety differences like bounds checking in Rust are cultural differences)
The reason std::optional doesn't allow references is because someone in the commitee objected that some users might be confused by the assignment semantics (will assignment rebind or assign through the reference?) and the proposal authors dropped it instead of spending too long discussing pro and cons. It can still be easily re-added if the commitee wants to.
No need to drag the rust in the discussion.