C++ std list sort with custom comparator that depends on an member variable for the object instance

后端 未结 2 2028
一向
一向 2021-01-13 13:44

Class:

Class:
  private:
    ...
    vector words; 
    vector< list > vints;
  public:
    myFunction(...)

2条回答
  •  长情又很酷
    2021-01-13 14:06

    @Kerrek's answer involving lambdas is better. But, if you must avoid C++11 features, then replace your sort function with a functor. Allow that functor to store a reference to whatever data is required, as so:

    #include 
    #include 
    #include 
    
    class myClass {
    private:
      std::vector words;
      std::vector > vints;
    
      // Instead of sortFunc, use sortFunctor. A functor can be used in place 
      // of a function in many places, and it can carry state (like a reference
      // to the data it needs).
      struct sortFunctor {
        const std::vector& words;
        sortFunctor(const std::vector& words) : words(words) { }
        bool operator()(int i, int j) { return words[i] < words[j]; }
      };
    
    public:
      void myFunction() {
        vints[0].sort(sortFunctor(words));
      }
      myClass() {
        words.push_back("apple");
        words.push_back("berry");
        std::list l;
        l.push_back(0);
        l.push_back(1);
        vints.push_back(l);
      }
    };
    
    int main () {
      myClass object;
      object.myFunction();
    }
    

提交回复
热议问题