Re: STL map issue
On Tue, 26 Aug 2008 21:14:00 -0700, George
<George@discussions.microsoft.com> wrote:
If pair is always making an additional copy, why and when should we use it?
Some best practices?
You can't avoid the copying, and it shouldn't matter, because the map has
to make its own copy of the data anyway. That is, if you can afford one
copy, you ought to be able to afford two. If you can't afford even one,
then you should store pointers, which are cheap to copy. (Move semantics
may help with this in a future standard, but that's just a guess.)
That said, there is one copy you can avoid. Here's an excerpt from your
code:
map<int, string> Employees;
pair<int, string> p(2, DavidName);
Employees.insert(p);
Even though your map is map<int, string>, the pair type it uses is
pair<const int, string>. Therefore, when you call insert, the pair you
created will be converted to this type, making yet another copy of the data
it contains. You can avoid this by using the correct pair type, which is
conveniently declared as map::value_type.
--
Doug Harrison
Visual C++ MVP