• Announcements

Archived

This topic is now archived and is closed to further replies.

[STL] Normal [] for a std::map

Recommended Posts

I have a class that stores pairs of strings CKeypair. It exports simple interfaces, like insert, get, etc. I have a new requirement to be able to get a dump of every pair in the class. I''d love to put a operator[] on Ckeypair, but how to I interface that with a std::map? I cant just reexport [] as that''ll try to insert. I was thinking about using iterators like this :
  inline std::pair CKeypair::operator[] (int i) const { return m_Pairs.begin() + i; } 
...but I''m betting that’s kind of wrong. All suggestions welcome... Chris Brodie http:\\fourth.flipcode.com

Share on other sites
Hmm... One way is to export the begin() and end() pair
of iterators so that you can use copy(...) outside,
for example:

  vector> aDumpcopy(MyKeyPair.begin(), MyKeyPair.end(), back_inserter>(aDump));

Another way is to dump everything into a vector and let
the caller decide how to use the vector.

  vector JustADump;MyKeyPair.Dump(JustADump);MyKeyPair::Dump(vector &aDump) { copy(m_Map.begin(), m_Map.end(), back_inserter>(aDump); }

Premature optimizations can only slow down your project even more.

Edited by - tangentz on January 30, 2002 11:04:07 AM

Share on other sites
IMHO such a overloaded operator is misleading. You are using a map so the order of elements inserted are undefined. Yet you are using [] to access them via an int, which some user might assume an order with insertion.

Share on other sites

The result(HTML mangling aside)
  void CKeypair::Copy(std::vector >& a_Keys){ std::copy(m_Pairs.begin(), m_Pairs.end(), std::back_inserter > >(a_Keys));}

Chris Brodie
http:\\fourth.flipcode.com

• Forum Statistics

• Total Topics
627704
• Total Posts
2978716

• 21
• 14
• 12
• 10
• 12