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

后端 未结 2 1991
一向
一向 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 <vector>
    #include <list>
    #include <string>
    
    class myClass {
    private:
      std::vector<std::string> words;
      std::vector<std::list<int> > 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<std::string>& words;
        sortFunctor(const std::vector<std::string>& 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<int> l;
        l.push_back(0);
        l.push_back(1);
        vints.push_back(l);
      }
    };
    
    int main () {
      myClass object;
      object.myFunction();
    }
    
    0 讨论(0)
  • 2021-01-13 14:15

    With lambdas:

    vints[i].sort([&words](int i, int j) { return words[i] < words[j]; });
    

    With std::bind:

    #include <functional>
    
    //...
    {
      using namespace std::placeholders;
      vints[i].sort(std::bind(&myClass::sortFunc, this, _1, _2));
    }
    
    0 讨论(0)
提交回复
热议问题