Search code examples
c++sortingstl-algorithm

Calling sort() on a vector that's a member of a class "No matching function for call to swap()"


I have a class A declared as:

class A {
public:
    vector<int> vec;
};

Running the following code:

const A *a = new A();
sort(a->vec.begin(), a->vec.end());

gives me the error:

algorithm: No matching call to swap()

in Xcode.

Any clue as to why this is happening?


Solution

  • const A *a means "pointer to const A, and that means the object pointed at by a cannot be modified via a. sort modifies the elements of the iteration range passed to it. Since these elements are owned by the object pointed at by a, they cannot be modified via a.

    So, you cannot call sort the vector a->vec. You need to find a different approach.