How do I invoke the int operator < instead of the int* operator < ?

vector<int*> pVec;
std::sort(pVec.begin(),pVec.end(), /*????*/);

Recommended Answers

All 5 Replies

bool pComp(int* a, int* b) { return *a < *b; }

vector<int*> pVec;
std::sort(pVec.begin(),pVec.end(), pComp);
commented: thank you +2

How do I invoke the int operator < instead of the int* operator < ?

vector<int*> pVec;
std::sort(pVec.begin(),pVec.end(), /*????*/);

Why do you need to store int* anyways? Either store it as vector<int> or vector< vector<int> >

Why do you need to store int* anyways? Either store it as vector<int> or vector< vector<int> >

Well perhaps it is a bad idea, BUT I have a vector of objects which contains int values, and while I don't want to change the ordering of the objects themselves, I do wish to sort some of the int values.

class myClass
{
    // some code...

    int m_val;
};

vector<myClass> mVec;
// push_back myClass objects

vector<int*> pVec;
// push_back m_val for every myClass in mVec

std::sort(pVec.begin(), pvec.end(), pComp);

// Now use the sorted values...
// pVec then goes out of scope

It seems to me this is a efficient solution b/c I'm only creating pointers (or I might use iterators instead of pointers). Bad idea?

If you don't modify your initial vector after populating the second, I guess it's ok.
Otherwise, both approaches (pointers and iterators) are problematic.

BTW, there are ready solutions to this -> http://www.boost.org/doc/libs/1_46_1/libs/multi_index/doc/index.html

EDIT: Also, if you use decide to use pointers, you probably need pointers to myClass, not to int :P

I don't actually want to sort the myClass objects. Only the values contained in myClass. It might seem like an unusual thing to be doing, but in the real application, myClass is a glorified struct that is part of a hierarchical data grouping. I need to sort the m_vals contained in myClass, and I need to do so efficiently. A vector should be better than a multi-index for this purpose although Boost is good to have in my back pocket. Thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.