Click here to Skip to main content
11,790,021 members (51,848 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C++
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...

std::map< std::pair<A, int>, std::string> myMap;
Now I want to do a look up like this...

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
std::pair<A, int>
std::pair<const A&, int>

Can anyone suggest a way to avoid the copy of A?
Posted 17-Dec-12 18:56pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

// 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> Smile | :)
_Josh_ at 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 at 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).
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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:

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;  

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

  Print Answers RSS
0 OriginalGriff 375
1 Richard MacCutchan 160
2 CPallini 115
3 ppolymorphe 114
4 Jochen Arndt 105
0 OriginalGriff 1,029
1 Maciej Los 790
2 KrunalRohit 686
3 CPallini 606
4 Richard MacCutchan 460

Advertise | Privacy | Mobile
Web04 | 2.8.1509028.1 | Last Updated 18 Dec 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100