locked
Sorting IVector

    Question

  • I know i can use std::sort to sorting a vector, but what about IVector ?
    Tuesday, June 12, 2012 7:32 PM

Answers

  • I've managed to make it work.

    Example:

    struct compareMyObjectByNumber {
        bool operator ()(MyObject^ left, MyObject^ right) const {
    return left->number < right->number;
        }
    };

    std::sort(begin(myIVector),end(myIVector), compareMyObjectByText());

    Wednesday, June 13, 2012 2:59 PM

All replies

  • Hi,

    I hope this works for you :-

    IVector<int>^ SortVector(IVector<int>^ vec) { std::sort(begin(vec), end(vec)); return vec; }

    Regards,

    Sagar


    Wednesday, June 13, 2012 12:45 AM
    Moderator
  • Thanks Sagar. I have a IVector of classes, so it is a bit more complex:

    std::sort(begin(m_albums), end(m_albums), [](MyObject^ prop1, MyObject^ prop2)
    {
       return _wcsicmp( prop1->text->Data(), prop2->text->Data()); // sort by text field of String
    });

    but user need to have defined some operators in MyObject.

    Edit: even when operator < is defined, sorting doesn't work and throw an exception :-/
    Wednesday, June 13, 2012 8:53 AM
  • I see it work fine with simple type stored in vector (like IVector<int>), but not with referenced object (like IVector<Object^>).
    Wednesday, June 13, 2012 1:58 PM
  • I've managed to make it work.

    Example:

    struct compareMyObjectByNumber {
        bool operator ()(MyObject^ left, MyObject^ right) const {
    return left->number < right->number;
        }
    };

    std::sort(begin(myIVector),end(myIVector), compareMyObjectByText());

    Wednesday, June 13, 2012 2:59 PM