I have a class with a std::map used as a container. I want to add a function to copy the map between two objects. Since the map was declared as a private member of the class, I need a friend function to do so. Here is my code:
class Data;
void copyData(Data &, Data &);
class Data
{
private:
map<int, int> _data;
public:
friend void copyData(Data &, Data&);
};
void copyData(Data &a, Data &b)
{
std::copy(a._data.begin(), a._data.end(), b._data.begin());
}
main()
{
// initialization here
Data A, B;
copyData(A, B);
}
But there are many warnings while compiling with mingw32. How do I do this correctly?
The
std::map<K,V>::value_typeis defined asstd::pair<const K,V>. This ensures thatstd::map<K,V>::iteratorobjects can’t be used to assign to the key (or else you could use this to break the container invariants).This means that map iterators don’t satisfy the
OutputIteratorconcept requirements and you can’t use them as the third parameter of thestd::copy()function. On the same note, there are lots of situations that would make this code break anyways, such as if one map has more associations than the other.Besides, there is a much easier way to write your function: