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

Started by
2 comments, last by gimp 22 years, 2 months ago
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<std::string,std::string> 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
Chris Brodie
Advertisement
Hmm... One way is to export the begin() and end() pair
of iterators so that you can use copy(...) outside,
for example:

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


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

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


Premature optimizations can only slow down your project even more.

Edited by - tangentz on January 30, 2002 11:04:07 AM
神はサイコロを振らない!
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.
Excellent advice guys. Thanks.

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


Chris Brodie
http:\\fourth.flipcode.com
Chris Brodie

This topic is closed to new replies.

Advertisement