Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Suppose you have a type A which has some cost associated with copying it that we'd like to avoid.

I want to have a collection where A forms part of the key, say...

C++
std::map< std::pair<A, int>, std::string> myMap;

Now I want to do a look up like this...

C++
void SomeMethod(const A& a, int b)
{
   iterator it = myMap.find(std::make_pair(a, b));
}


...make_pair(...) copies the A because the map's key type is
C++
std::pair<A, int>
not
C++
std::pair<const A&, int>


Can anyone suggest a way to avoid the copy of A?
Posted

// not std::pair<const A&, int>

Why not ?

It could be also std::pair<const A*, int>
or std::pair<std::auto_ptr<A>&, int> :)
 
Share this answer
 
v2
Comments
[no name] 18-Dec-12 2:27am    
But then I'd have to manage memory for the pointers and ill get worse cache performance because things will be all over the place in memory.
Eugen Podsypalnikov 18-Dec-12 2:56am    
// worse cache performance, because things will be all over the place in memory
First - please remember that the all objects are in the memory (once or twice ;-))

I think, it (worse cache performance) is wrong :) ,
because a map will work with pointer- (or reference-) keys in its hash-table _more_faster_
as with full full-dumped-copies keys.

Above all, your code will be more canny (in the memory usage context).
Typically you don't want to use large object for a key.

You might also be able to keep a std::pair<a,> somewhere and pass it by reference to SomeMethod to avoid extra construction particulary in a loop.

Are you using the whole A object for ordering ? If not, then maybe a better design would be to have a simpler key and a more complete value.

Generally your key should be simple and a small object and the value would have all the information. Something similar to this:

C++
struct PairAndString 
{
    A first;
    int second;
    std::string third;
};

// Only fields necessary for sorting and comparison in key. Everything else moved to the value part.
std::map<a_key,> myMap;  
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900