I was wondering how I can use the sort function to sort a vector which is private in a class:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class A{
private:
const vector<int> myvec;
A(vector<int>& vec) : myvec(vec) { }
public:
const vector<int>& getvec() { return myvec; }
int get_sec_element(){
int sec_ele = 0;
sort(myvec.begin(), myvec.end());
sec_ele = myvec[2];
return sec_ele;
}
};
So if I created A myvec_object and filled it with a vector which had values already inside it, caliing myvec_object.get_sec_ele() would return the 2nd element in the vector. However, the compiler is giving a huge error message with: “instantiated from here”. What could be the problem?
You declared
myvecasconst— how would you expect to modify it?Declare
myvecas: