Modify the value of a std::unordered_map element in C++ - c++

I have the following problem. I have a std::unordered_map that contains an object as the value. Now I want to modify an object that I previously inserted.
class Point
{
public:
Point(float _x, float _y) : x(_x), y(_y) {}
float x;
float y;
};
std::unordered_map<int, Point> points;
// ... add some values to it ...
points[1].x = 20.f; // error?
I get a weird long compile error about point not being able to be default constructed. The way I understand it operator [] returns a reference to the mapped type (aka the value), so why can't I modify it?

If the key isn't in the map, operator [] is required to create one. The expression
points[1]
needs to be able to default-insert a Point in case of lookup failure (regardless of whether lookup failure ever occurs - this is a compile-time requirement not a run-time check). That requirement cannot be satisfied by Point because Point is not default constructible. Hence the compile error. If you want to use unordered_map::operator[] , you'll need to add a default constructor.
If a default constructed Point doesn't make sense for your usage - then you simply cannot use operator[] and will have to use find throughout (or at() if you're okay with exceptions):
auto it = points.find(1);
if (it != points.end()) {
it->second.x = 20.f;
}
points.at(1).x = 20.f; // can throw

operator[] constructs an object of mapped type in-place if no element exists with the given key. In a map with a default allocator, operator[] requires the mapped type to be default constructible. More generally, the mapped type must be emplace constuctible.
The easy solution is to add a default constructor to your class.
Point() : Point(0.f, 0.f) {}
If this isn't possible, you will have to use other functions to access map elements.
To access an existing mapped object, you can using at, which will throw a std::out_of_range exception if no element exists with the given key.
points.at(1).x = 20.f;
Alternatively, you can use find, which returns an iterator to the element with the given key, or to the element following the last element in the map (see end) if no such element exists.
auto it = points.find(1);
if (it != points.end())
{
it->second = 20.f;
}

operator[] cannot be used on a map or unordered_map without the data being default-constructible. This is because if the object is not found, it will create it via default-construction.
The easy solution is to make your type default-constructible.
if not:
template<class M, class K, class F>
bool access_element( M& m, K const& k, F&& f ) {
auto it = m.find(k);
if (it == m.end())
return false;
std::forward<F>(f)(it->second);
return true;
}
then:
std::unordered_map<int, Point> points;
points.emplace(1, Point(10.f, 10.f));
access_element(points, 1, [](Point& elem){
elem.x = 20.f;
});
will do what points[1].x = 20.f; does without risking exception code or having to make Point default-constructible.
This pattern -- where we pass a function to mutate/access an element to a container -- is stealing a page from Haskell monad design. I would make it return optional<X> instead of bool, where X is the return type of the passed in function, but that is going a bit far.

Related

`auto` for the result of `std::set::find` in non-const context resolves to `std::_Rb_tree_const_iterator` in g++ (GCC) 7.3.0 with `-std=c++11` [duplicate]

I find the update operation on std::set tedious since there's no such an API on cppreference. So what I currently do is something like this:
//find element in set by iterator
Element copy = *iterator;
... // update member value on copy, varies
Set.erase(iterator);
Set.insert(copy);
Basically the iterator return by Set is a const_iterator and you can't change its value directly.
Is there a better way to do this? Or maybe I should override std::set by creating my own (which I don't know exactly how it works..)
set returns const_iterators (the standard says set<T>::iterator is const, and that set<T>::const_iterator and set<T>::iterator may in fact be the same type - see 23.2.4/6 in n3000.pdf) because it is an ordered container. If it returned a regular iterator, you'd be allowed to change the items value out from under the container, potentially altering the ordering.
Your solution is the idiomatic way to alter items in a set.
C++17 introduced extract, see Barry's answer.
If you're stuck with an older version, there are 2 ways to do this, in the easy case:
You can use mutable on the variable that are not part of the key
You can split your class in a Key Value pair (and use a std::map)
Now, the question is for the tricky case: what happens when the update actually modifies the key part of the object ? Your approach works, though I admit it's tedious.
In C++17 you can do better with extract(), thanks to P0083:
// remove element from the set, but without needing
// to copy it or deallocate it
auto node = Set.extract(iterator);
// make changes to the value in place
node.value() = 42;
// reinsert it into the set, but again without needing
// to copy or allocate
Set.insert(std::move(node));
This will avoid an extra copy of your type and an extra allocation/deallocation, and will also work with move-only types.
You can also extract by key. If the key is absent, this will return an empty node:
auto node = Set.extract(key);
if (node) // alternatively, !node.empty()
{
node.value() = 42;
Set.insert(std::move(node));
}
Update: Although the following is true as of now, the behavior is considered a defect and will be changed in the upcoming version of the standard. How very sad.
There are several points that make your question rather confusing.
Functions can return values, classes can't. std::set is a class, and therefore cannot return anything.
If you can call s.erase(iter), then iter is not a const_iterator. erase requires a non-const iterator.
All member functions of std::set that return an iterator return a non-const iterator as long as the set is non-const as well.
You are allowed to change the value of an element of a set as long as the update doesn't change the order of elements. The following code compiles and works just fine.
#include <set>
int main()
{
std::set<int> s;
s.insert(10);
s.insert(20);
std::set<int>::iterator iter = s.find(20);
// OK
*iter = 30;
// error, the following changes the order of elements
// *iter = 0;
}
If your update changes the order of elements, then you have to erase and reinsert.
You may want to use an std::map instead. Use the portion of Element that affects the ordering the key, and put all of Element as the value. There will be some minor data duplication, but you will have easier (and possibly faster) updates.
I encountered the very same issue in C++11, where indeed ::std::set<T>::iterator is constant and thus does not allow to change its contents, even if we know the transformation will not affect the < invariant. You can get around this by wrapping ::std::set into a mutable_set type or write a wrapper for the content:
template <typename T>
struct MutableWrapper {
mutable T data;
MutableWrapper(T const& data) : data(data) {}
MutableWrapper(T&& data) : data(data) {}
MutableWrapper const& operator=(T const& data) { this->data = data; }
operator T&() const { return data; }
T* operator->() const { return &data; }
friend bool operator<(MutableWrapper const& a, MutableWrapper const& b) {
return a.data < b.data;
}
friend bool operator==(MutableWrapper const& a, MutableWrapper const& b) {
return a.data == b.data;
}
friend bool operator!=(MutableWrapper const& a, MutableWrapper const& b) {
return a.data != b.data;
}
};
I find this much simpler and it works in 90% the cases without the user even noticing there to be something between the set and the actual type.
This is faster in some cases:
std::pair<std::set<int>::iterator, bool> result = Set.insert(value);
if (!result.second) {
Set.erase(result.first);
Set.insert(value);
}
If the value is usually not already in the std::set then this can have better performance.

Who deletes previous nlohmann json object resources when value is replaced?

I have a key and I want to change the value of the key with another json object.
json newjs = ...;
json tempjs = ...;
newjs["key"] = tempjs["key"];
What will happen to the data existed in newjs["key"] previously?
Will nlohmann class automatically destroy it or is it a memory leak?
OR do I need to manually erase the key first and assign as above?
Internally it's a kept by an "ordered_map: a minimal map-like container that preserves insertion order".
The actual standard container used in this ordered_map is a std::vector<std::pair<const Key, T>, Allocator> and the assignment you do is performed via
T& operator[](const Key& key)
{
return emplace(key, T{}).first->second;
}
where emplace is defined as:
std::pair<iterator, bool> emplace(const key_type& key, T&& t)
{
for (auto it = this->begin(); it != this->end(); ++it)
{
if (it->first == key)
{
return {it, false};
}
}
Container::emplace_back(key, t);
return {--this->end(), true};
}
This means that operator[] tries to emplace a default initialized T into the internal map. If key isn't present in the map, it will succeed, otherwise it will fail.
Regardless of which, when emplace returns, there will be a T in the map and it's a reference to that T that is returned by operator[] and it's that you then copy assign to.
It's a "normal" copy assignment and no leaks should happen.

C++ , how to return a reference to the member variable from iterator

There is the following class B derived from std::vector
class B: public std::vector <unsigned int>
{
public:
B() : std::vector <unsigned int> ( 0 ) {}
};
and a class A witten as follows:
class A
{
private:
B b;
double x;
public:
B & getB () {return b;}
B const & getB() const {return b;}
bool operator() ( const A & a ) const
{
return a < a.x;
}
};
Why it is impossible to return a refererence to the variable b of some object A stored in std::list from its iterator (and how to do that)?
int main ()
{
std::set <A > alist;
std::set <A> ::iterator i_alist = alist.begin();
for (; i_alist != alist.end(); i_list++)
{
B &il = (*i_alist).getB(); //Compiler error
B &il2 = i_alist->getB(); //Compiler error
il.push_back(10); //Modify il and concurrently B
}
}
Compiler error:
Error 1 error C2440: 'initializing' : cannot convert from 'const B' to 'B &' d:\test.cpp
Thanks for your help...
Edit question:
The possible solution using const_cast :
B &il2 = const_cast <B&> ( i_alist->getB() );
This has very little to do with std::vector and everything to do with std::set. You store your objects in a std::set. Elements of std::set are not modifiable from the outside. Once you inserted an element into a set, you cannot change it.
For this reason, std::set::iterator might (and will) evaluate to a constant object, even if it is not a const_iterator (the language specification actually allows std::set::iterator and std::set::const_iterator to refer to the same type, but does not require it). I.e. in your example *i_list is a const-qualified object of type const A. The compiler will call the const version of getB, which returns const B &. You are apparently hoping to break through that constness, expecting the non-const version of getB to be called.
There's no way around it, unless you decide to use some sort of hack (const_cast etc.) to remove the constness from the set element and thus make the compiler to call non-const version of getB.
The const_cast-based hack-solution would look as
B &il = const_cast<A &>(*i_alist).getB();
or you can remove the constness later, from the returned B reference
B &il = const_cast<B &>((*i_alist).getB());
B &il2 = const_cast<B &>(i_alist->getB());
There are some things that look weird about your example:
Never derive from std::vector. It's not designed for that use. And there normally is no reason to do so, except laziness, i.e. to avoid some typing.
What is that A::operator() for? Looks like some strange way to provide a Comparator for the std::set you are using. Normally you don't alter a class just because you stuff it into a std::set somewhere. If you really want to be able to compare your A's (generally, not just for the set), then write a proper free bool operator<(A const&, A const&); If it's just for the set, write a custom Comparator in the place where you use the set. (That comparator should not need to access A's privates)
What is the A::x used for? Only for comparison or even only for the comparison inside the set? If it's just that, consider to use a std::map<double, A> or even a std::map<double, B> where you put your x as the keys and the actual objects as the values.
You see, there are a lot of open questions I ask, and maybe the solution (using a map) does not even fit your problem. That is because you did not show us the real code you have but only some example with meaningless names. So we only see what you are trying to do, not what you actually want to achieve with your code.
PS: maybe you don't even need an ordered container in the first place, it could suffice to stuff all the objects into a std::vector and then std::sort it. Depends on the kind of objects you really have (the A's of your example are cheap to copy/swap) and of the ways you use the container - how the insertions are interleaved with the loops and so on.

invoking constructors of struct in functions, C++

Here is the approximate code of my question. First, we have a struct with a constructor:
struct Pair{
Pair(int a, int b): (first (a) , second (b) ) {}
int first;
int second;
};
which is used in a map
map<string, Pair> mymap;
I would like to initialize this map in a function
void f(map<string, Pair>* mymap, string c,int x, int y )
{
(*mymap)[c]=Pair(x,y);
}
But the compiler says first that it could not find an appropriate constructor and then the next lines are that not enough arguments are provided for the constructor.
A friend of mine told me that I should write the function like this:
void f(map<string, Pair>& mymap, const string& c,int x, int y )
{
if (mymap.find(c) != mymap.end()) {
mymap[c] = Pair(x,y);
}
}
But he could not explain why Type& should be used here instead of Type *, and I would like to clarify this point. Can anybody explain?
The problem is that operator[] in a map requires that the value type is default constructible. If you don't want your Pair to be default constructible, you will have to avoid using operator[]:
void f(map<string, Pair>& mymap, string c,int x, int y )
{
mymap.insert( std::make_pair(c,Pair(x,y)) );
}
You may have misunderstood what your friend suggested. The problem with operator[] is not that it requires the default constructor if it needs to create a new element, but that it requires it in case it might need to. That is, whether the element exists before hand or not does not really matter.
If you also mean to update, then you need to consider also that option:
void f(map<string, Pair>& mymap, string c,int x, int y )
{
auto res = mymap.insert( std::make_pair(c,Pair(x,y)) );
if ( !res.second )
res.first->second = Pair(x,y);
}
Basically the insert operation returns a pair of the iterator pointing at the key and a bool indicating if this insert created the object or if it was already there (in which case the value in the map is unmodified). By storing the result, we can test and if the insert did not create the value, we can update it through the returned iterator.
Calling operator[] on map will require your type to be default constructible. You can avoid that by using map::insert or map::emplace
You will need a default contrructor:
Pair(): first () , second () {}
This is needed for the map's operator[], which creates a default-constructed mapped_type
when called with a non-existent key-
and a less-than operator that implements strict weak ordering:
struct Pair {
// as before
bool operator<(const Pair& rhs) const {
/ some code to implement less-than
}
};
or you can pass a comparison functor or function implementinf strict weak ordering as a
third template argument.
The standard containers need a default constructor. They will use the operator= to set the correct value at some point after construction.

Overloading [] in C++ to return lvalue

I'm writing a simple hash map class:
template <class K, class V> class HashMap;
The implementation is very orthodox: I have a heap array which doubles in size when it grows large. The array holds small vectors of key/value pairs.
Vector<Pair<K, V> > *buckets;
I would like to overload the subscript operator in such a way that code like this will work:
HashMap<int, int> m;
m[0] = 10; m[0] = 20;
m[2] = m[1] = m[0];
In particular,
For m[k] = v where m does not contain k, I'd like a new entry to be added.
For m[k] = v where m does contain k, I'd like the old value to be replaced.
In both of these cases, I'd like the assignment to return v.
Presumably the code will look something like
V& operator[](K &key)
{
if (contains(key))
{
// the easy case
// return a reference to the associated value
}
else
{
Vector<Pair<K, V> > *buck = buckets + hash(k) % num_buckets;
// unfinished
}
}
How should I handle the case where the key is not found? I would prefer to avoid copying values to the heap if I can.
I suppose I could make a helper class which overloads both the assignment operator and a cast to V, but surely there is a simpler solution?
Edit: I didn't realize that std::map required that the value type have a zero argument constructor. I guess I will just default-construct a value as well.
How should I handle the case where the key is not found?
Insert a new element with that key and return a reference to the value of that new element. Effectively, your pseudocode becomes something equivalent to:
if (!contains(key))
insert(Pair<K, V>(key, V()));
return reference_to_the_element_with_that_key;
This is exactly what your requirement is, too. You said "For m[k] = v where m does not contain k, I'd like a new entry to be added."
How should I handle the case where the key is not found?
std::map creates a new object, and inserts it into the map, and returns its reference. You can also do the same.
Alternatively, you can throw an exception KeyNotFoundException like the way .NET map throws. Of course, you've to define KeyNotFoundException yourself, possibly deriving from std::runtime_exception.
By the way, as a general rule, always implement operator[] in pair as:
V &operator[](const K &key);
const V &operator[](const K &key) const;
Just for the sake for const-correctness. However, if you decide to create a new object and insert it into the map, when the key is not found, then this rule is not applicable here, as const version wouldn't make sense in this situation.
See this FAQ:
What's the deal with "const-overloading"?
It sounds like what you want is a "smart reference", which you cannot generically implement in C++ because you cannot overload the dot operator (among other reasons).
In other words, instead of returning a reference to a V, you would return a "smart reference" to a V, which would contain a pointer to V. That smart reference would implement operator=(const V &v) as this->p = new V(v), which only requires a copy constructor (not a zero-argument constructor).
The problem is that the smart reference would have to behave like an actual reference in all other ways. I do not believe you can implement this in C++.
One not-quite-solution is to have your constructor take a "default" instance of V to use for initializing new entries. And it could default to V().
Like this:
template<class K, class V> class HashMap {
private:
V default_val;
public:
HashMap(const V& def = V()) : default_val(def) {
...
}
...
};
When V lacks a zero-argument constructor, HashMap h will not compile; the user will need to provide a V object whose value will be returned when a key is accessed for the first time.
This assumes V has a copy constructor, of course. But from your examples, that seems like a requirement anyway.
The simple solution is to do as std::map does: construct a new entry,
using the default constructor of the value type. This has two
drawbacks: you won't be able to use [] on a HashMap const, and you
can't instantiate HashMap with a value type which doesn't have a default
constructor. The first is more or less implicit in the specification,
which says that [] may modify the map. There are several solutions
for the second: the simplest is probably to pass an instance of a
"default" value to the constructor, which saves it, and uses it to copy
construct the new instance, e.g.:
template <typename Key, typename Value>
class HashMap
{
// ...
Value m_defaultValue;
public:
HashMap( ..., Value const& defaultValue = Value() )
: ... , m_defaultValue( defaultValue )...
Value& operator[]( Key& key )
{
// ...
// not found
insert( key, m_defaultValue );
// return reference to newly inserted value.
}
};
Alternatively, you can have operator[] return a proxy, something like:
template <typename Key, typename Value>
class HashMap::Helper // Member class of HashMap
{
HashMap* m_owner;
Key m_key;
public:
operator Value&() const
{
if ( ! m_owner->contains( m_key ) )
m_owner->createEntryWithDefaultValue( m_key );
return m_owner->getValue( m_key );
}
Helper& operator=( Value const& newValue ) const
{
m_owner->insert( m_key, newValue );
return *this;
}
};
Note that you'll still need the default value for the case where someone
writes:
v = m[x];
and x isn't present in the map. And that things like:
m[x].f();
won't work. You can only copy the entire value out or assign to it.
(Given this, I'd rather prefer the first solution in this case. There
are other cases, however, where the proxy is the only solution, and we
have to live with it.)