Operator overloading
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 21

Thread: Operator overloading

  1. #1
    Join Date
    Oct 2006
    Posts
    128

    Operator overloading

    HI All,
    This doubt could be simple but i can't figure out myself.
    Basically my task is to go through a list of names (with associated int values), check if it already exists in a std::set , if not add it.

    So std::set<myclass> goes like this...
    Code:
    cmyclass{
    
    cmyclass(CString str, int int1, int int2){
    m_str = str;
    m_int1 = int1;
    m_int2 = int2;
    }
    cmyclass operator<(const cmyclass &right) const;
     
    Cstring m_str;
    int m_int1;
    int m_int2;
    
    }
    my main class would go

    Code:
    std::set<cmyclass> m_myclass;
    cmyclass myclass(str1, int1, int1);
    std::set<myclass>::iterator Iter1 = m_myclass.find(myclass);
    if(Iter1 == m_myclass.end()){
    
    //if doesn't exist in the set add it.
    std::pair<std::set<cmyclass>::iterator, bool> IterAdd = m_myclass.insert(myclass);
    }
    I can understand what i am doing in the main program...but not sure why i need to override operator< here and what goes in there? Can someone help me here?

    thanks

  2. #2
    Join Date
    Oct 2008
    Posts
    116

    Re: Operator overloading

    you have to operator< because this structure store your data like AVL ( balance tree ).
    My English is very bad. So tell me if Something I talked make u confuse.
    My Ebook Store: www.coding.vn/book.php

  3. #3
    Join Date
    Oct 2006
    Posts
    128

    Re: Operator overloading

    thanks for your reply. Can you please give me some clue as to what goes in there?

  4. #4
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,565

    Re: Operator overloading

    1) It should be a member function (with return type bool, not cmyclass).

    2) Assuming that you just want to match the CString variable:


    Code:
    bool operator<(const cmyclass &right) const
    {
        return m_str < right.m_str;
    }

  5. #5
    Join Date
    Oct 2006
    Posts
    128

    Re: Operator overloading

    I understood that the operator < overloading is used for indexing purpose when i use the std::set.

    Now my next question is I want to be able to input same string with different int values(either of them) but i don't seem to get it.
    I am using the sample program
    Code:
    class Person {
    public:
      CString _first;
      int _i1, _i2;
    public:
    	Person(){}
      Person(const CString first, int i1, int i2)
        : _first(first), _i1(i1), _i2(i2)
      {}
    
      bool operator<(const Person& p) const
      {
        
    	  return _first < p._first ;
                     		
      }
    my main class
    Code:
    std::set<Person> m;
    		Person p(_T("Johnd"), 1,2);
    		Person p1(_T("Ja ne"), 2,3);
    		Person p2(_T("sss"), 3,1);
    		Person p3(_T("John"), 1, 2);
    		Person p4(_T("John"), 1, 3);
    		m.insert(p);
    		m.insert(p1);
    		m.insert(p2);
    		m.insert(p3);
    		m.insert(p4);
    		Person p5(_T("Jan"), 3,5);
    		
    		Person xx(_T("John"), 1,4);
    			std::set<Person>::iterator it = m.find(xx);
    
    			if (it == m.end()) {
    		 
    				m.insert(xx);
    			
    			}
    1. I can't get to add p4 to the set m. I know i need to change the operator <, tried different ways like this
    Code:
    return _first < p._first && _i2 < p._i2;
    if i do this, in the main program it adds only 1 object to the std::set object.

    The logic is compare the name, and the int values , also i tried, if name is same compare the rest, again doesn't work.



    2. My second question is if i try this code in < overloading function

    Code:
     return _first < p._first && _i2 < p._i2;
    it just adds one object to the std::set object. but if i try this
    Code:
    if(_first < p._first && _i2 < p._i2)
    		return true;
    it adds 4 Person objects to the std::set object. Though i don't have explicit else, doesn't the function return false if the if fails?


    thanks

  6. #6
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,888

    Re: Operator overloading

    I don't know if the return is specified if you don't give it one. If it's a random value, it's far more likely to be true than false.....

    Your conditionals should not be checking both variables at the same time. You need to do something like
    Code:
    if (_first < p._first)
        return true;
    if (_first > p._first)
        return false;
    if (_i2 < p._i2)
        return true;
    etc
    so that you only consider additional variables if the ones you've seen so far are all equal.

  7. #7
    Join Date
    Oct 2006
    Posts
    128

    Re: Operator overloading

    Thanks for the reply... I tried this
    Code:
    if( _first < p._first )
    		  return true;
    	  else
    		  return false;
    	  if(_i1 < p._i1)
    		  return true;
    	  else
    		  return false;
    	  if(_i2 <p._i2)
    		  return true;
    	  else 
    		  return false;
    I don't seem to add p4 to the list still.......

  8. #8
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,888

    Re: Operator overloading

    Read that code more carefully. How could the execution path *ever* get past those first two return statements?

  9. #9
    Join Date
    Oct 2006
    Posts
    128

    Re: Operator overloading

    Sorry i tried exactly what you said > <, that seems to work...though i don't understand how...
    1.If it's less than return true, else return false,
    2. if it's less than return true, if greater than return false....works

  10. #10
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,888

    Re: Operator overloading

    What happens if they're equal?

  11. #11
    Join Date
    Oct 2006
    Posts
    128

    Re: Operator overloading

    what happens if the find return true? doesn't it mean i need a == operator overloading?
    I am doing this for the first time , so it's a learning curve for me.

  12. #12
    Join Date
    Mar 2002
    Location
    NY, USA
    Posts
    12,097

    Re: Operator overloading

    For sorting you only need "<".

    The reason is that for both "==" and ">" you would NOT "swap" the elements, as they are allready sorted. Therefore you do not need to differentiate.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009
    In theory, there is no difference between theory and paractice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  13. #13
    Join Date
    Oct 2006
    Posts
    128

    Re: Operator overloading

    To make it simpler i tried

    Code:
    return _first < p._first || _i1 < p._i1 || _i2 <p._i2;
    but this gives a runtime error with debug assertion failed: Invalide < operator.

    any suggestion?

  14. #14
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,888

    Re: Operator overloading

    The < operator must represent a strict weak ordering. That means it must be impossible for A < B and B < A to be true at the same time; and if they are false at the same time, that is interpreted as equality.

    In your above case, it's certainly possible for them to be true at the same time. What you want is:

    1) Compare _first. If not equal, report true or false. If equal, proceed to #2.
    2) Compare _i1. If not equal, report true or false. If equal, proceed to #3.
    3) Compare _i2. If not equal, report true or false. If equal, report false (since they're completely equal).

    This is called a lexicographic ordering, also sometimes called a dictionary ordering for reasons that will become obvious if you think about it.

  15. #15
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,565

    Re: Operator overloading

    Lindley's post has the basic info. (see post # 6)

    Edit: and his latest post completely describes what to do.

    It would be something like:

    Code:
    if( _first < p._first ) return true; 
    if( _first > p._first ) return false;
    
    // "_first" are equal ... check second variable
    
    if( _i1 < p._i1 ) return true; 
    if( _i1 > p._i1 ) return false;
    
    // _first and _i1 are equal ... check 3rd variable
    
    return _i2 < p._i2;
    Last edited by Philip Nicoletti; November 19th, 2008 at 07:17 AM.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center