Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

map searching

Status
Not open for further replies.

shetlandbob

Programmer
Mar 9, 2004
528
GB
Morning all,

This is more a general question that an actual problem to solve:

I set up the following:
Code:
 myOwnStructure mystruct; [green]//  this is defined elsewhere[/green]

 map<int, mystuct>  myMap;
[green]
// then elsewhere in my code 
// i loop through this and add in multiple mystructs.
[/green]
 int myInt;
 typedef pair <int, mystruct> mapPair;

 myMap.insert ( mapPair ( myInt, mystruct ) );
[green]
// my int is an integer that varies between 1 - 100000
//
// then elsewhere in my code I want to access my map
[/green]
 int myIntToRecall;
 myOwnStructure* pStruct;

 pStruct = &myMap[myIntToRecall];

Is the above code legal? It compiles and so far it works, I only came across it by accident as I used to use:

Code:
 int myIntToRecall;
 myOwnStructure* pStruct;
 map < int, mystruct >::iterator it;

 for ( it = myMap.begin(); it != myMap.end(); it++ )
 {
   if ( it->first == myIntToRecall ) 
   {
     pStruct = it->second;
   }
 }

If they are both acceptable and legal ways to access. Is there a performance overhead in using one way over the other? Some of my code has multi million elements in my map so this may have an implication?

Any comments much appreciated

 
1. Obviously, the 1st snippet is illegal. You must include your class name as the 2nd template arg. The 1st line is
Code:
myOwnStructure mystruct; //  this is defined elsewhere
It's a declaration of mystruct variable of type (class) myOwnStructure (or misprint;). Now you may write:
Code:
typedef map<int,myOwnStructure> MyMap;
...
MyMap myMap;
2. The 2nd snippet: why not:
Code:
it = myMap.find(myIntToRecall);
if (it != myMap.end())...
This is a map - a very effective search tree...
3. Don't forget to check carefully your value class copy constructor and destructor. The map<> has copies of its elements...
4. If you have elemetkeys in 1..100000 range, you can't save multi million elements in my map! 100000 only - that's all. Use multimap<> for millions.

Summary: you may process your data in such manner (but see point 4 above). A simple map scanning is the worst method if you want to find mapped values. Direct access is more effective.
 
thanks for the reply, I did think the first was illegal, but was surprised that it compiled in the first place.

in your summary are you saying that the best way to find my value is using

it = myMap.find(myIntToRecall);
if (it != myMap.end())...


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top