Archived

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

gimp

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

Recommended Posts

gimp    142
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

Share this post


Link to post
Share on other sites
TangentZ    450
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>> aDump
copy(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

Share this post


Link to post
Share on other sites
Void    126
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 this post


Link to post
Share on other sites
gimp    142
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

Share this post


Link to post
Share on other sites