user1285419
user1285419

Reputation: 2225

error while copying std::map defined in a class

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?

Upvotes: 0

Views: 91

Answers (1)

Andr&#233; Caron
Andr&#233; Caron

Reputation: 45224

The std::map<K,V>::value_type is defined as std::pair<const K,V>. This ensures that std::map<K,V>::iterator objects 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 OutputIterator concept requirements and you can't use them as the third parameter of the std::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:

void copyData(Data &a, Data &b)
{
  b._data = a._data;
}

Upvotes: 1

Related Questions