Jump to content
  • Advertisement
Sign in to follow this  
DesignerX

STL question

This topic is 4702 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I want to hold a data structure that can compare two elements using two keys i.e. If the first key equals to the compared key than comparision will be on the second key How can I do that ? P.S. I'm programming with c++

Share this post


Link to post
Share on other sites
Advertisement
Well, for one thing, what you are describing (if I'm understanding you properly) is more of an algorithm than a data structure. Anyway, what do you want to do with the result of these comparisions?

Share this post


Link to post
Share on other sites
Using the STL for comparison works through overloading the less-than ('<') operator. The implementation is up to you. If you have, for example, a class that holds two integer values, you can compare both in the implementation of that operator:

struct SData
{
int nOne;
int nTwo;

bool operator<( SData& data )
{
if ( nOne < data.nOne )
return true;
else if ( nOne > data.nOne )
return false;
else
{
if ( nTwo < data.nTwo )
return true;
else
return false;
}
}
}


You could use this to sort a vector of SData-objects for example.

std::sort( vData.begin(), vData.end() );


Illco

Share this post


Link to post
Share on other sites
std::pair also implements lexicographic sorting. For instance:



typedef std::pair<int,int> p;

assert( p(10,20) < p(10,19) );
assert( p(10,20) < p(9,20) );
assert( p(1,2) < p(2,1) );

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!