Search code examples
c++pointersdereference

Passing vector to function (pointers/addresses)


In the following situation, how does the parameter-list for sortMyVectors have to look like, and how do I call it from within myFunction ?

std::vector<Vector2> myFunction ( MyObj * myObj ) {

    std::vector<Vector2> myVectors;
    // fill with lots of Vector2(double x, double y) objects

    sortMyVectors( ???-myVectors, ???-myObj);

    return myVectors;
} 


void sortMyVectors( vector<Vector2> &myVectors, const MyObj &myObj) {

    // sort the std::vector using myObj
    // modifies order of Vector2s within the passed-in myVectors
    // does not modify myObj
    // need to be able to access with myVectors[0].x here...
}

The way this is called is myFunction(&(*myObj));, where myObj is a list<MyObj>::iterator. Is there a cleaner way to write this?


Solution

  • sortMyVectors( ???-myVectors, ???-myObj);
    

    Answer:

    sortMyVectors(myVectors, *myObj);
    

    As it seems you are having some basic trouble with pointers at the moment (and I suspect this is practice for some kind of homework), it would probably be a bit too advanced to suggest you learn iterators, but you should look into that later along with std::sort which would be quite hard to beat with any handrolled sort.

    As an attempt to improve your understanding of pointers:

    MyObj* myObjPtr = ...;
    

    This is a pointer. It points to a memory address. Assuming it points to a valid one, we can do this:

    MyObj& myObjRef = *myObjPtr;
    

    Now we dereferenced the pointer to get the pointee, and assigned it to a reference which is also like a pointer but hides the pointer/pointee distinction (not requiring operator* to access the pointee/referenced object).

    In response to a comment you made:

    The "sorting" basically sorts these vectors by their distance from another vector, but only in a particular case, so I don't know if there is a standard way of doing that..

    std::sort accepts a strict weak ordering predicate (basically a function or function object which returns true/false based on whether element1 < element2). Example:

    bool length_is_less(const string& str1, const string& str2)
    {
        return str1.size() < str2.size();
    }
    
    vector<string> my_strings = ...;
    sort(my_strings.begin(), my_strings.end(), length_is_less);
    

    The above code sorts strings based on their length from shortest string to longest string, rather than the default behavior (default operator< implementation for strings) of sorting them by string order (alphabetical order, crudely speaking).

    Given this ability to define your own predicate for comparing objects, you can basically sort anything by any condition using std::sort.