Sorting vector of objects with respect to std::variant field

Viewed 35

I have a vector of Row objects, which I need to sort based on a field which is a std::variant.

Below is the program

#include <iostream>
#include <variant>
#include <sstream>
#include <memory>
#include <vector>
#include <variant>
using namespace std;
using Value = std::variant<int,std::string>;
class Row{
    public:
    Row(Value data):data(data){}
    Row(const Row &aCopy){
        this->data = aCopy.data;
    }
    Row& operator=(const Row &aCopy){
        this->data = aCopy.data;
        return *this;
    }
    ~Row(){}
    
    Value getData(){
        return this->data;
    }
    
    protected:
    Value data;
    
};


std::vector<std::unique_ptr<Row>>& printUnique(std::vector<std::unique_ptr<Row>> &theRow){
    return theRow;
}



int main()
{

    std::vector<Row> theRow;
    Row a(1);
    Row b(-2);
    Row c(3);
    theRow.push_back(a);
    theRow.push_back(b);
    theRow.push_back(c);
    Value v = theRow.at(1).getData();
    sort(theRow.begin(),theRow.end(),[](const auto& lhs, const auto& rhs){
      Value v1 = lhs.getData();
      Value v2 = rhs.getData();
      return v1<v2;
    });
    
    
    
    return 0;
}

I am getting error in the sort function

main.cpp:65:13: error: passing ‘const Row’ as ‘this’ argument discards qualifiers [-fpermissive]
   65 |       Value v1 = lhs.getData();
      |             ^~

I am completely clueless here what to do. Any help here will be highly appreciated.

0 Answers
Related