简体   繁体   中英

C++ std::find_if on a custom class

I have a std::vector of a custom class (Term). I'm trying to find terms in that class using the std::find_if construct. I'm missing something:

 

    #ifndef _TERM_H_
    #define _TERM_H_

    #include <string>

    class Term {
        public:
                Term() {}
                Term(std::string, float);

                void setTerm(std::string myTerm) {this->term   = myTerm;}
                void setWeight(float myWeight) {this->weight = myWeight;}

                std::string getTerm() const {return this->term;}
                float getWeight() {return this->weight;}

                bool operator<(Term &t) {return t.getWeight() <  this->getWeight();}
                bool operator==(const Term *t) const {return this->getTerm().compare(t->getTerm()) == 0;}

        private:
                std::string term;
                float weight;
    }; // end class

    #endif

Then, later in the code, I have another class (Document) where I'll be comparing vectors of those terms:



    /***
     Defined in the header file:
     std::vector<Term *> terms;

     For brevity, I've removed other function definitions....***/

    void Document::compareToDoc(Document *myDoc) {
        for(auto const& term : myDoc->getTerms()) {
                //auto it = find(terms.begin(), terms.end(), term);
                auto it = find_if(terms.begin(), terms.end(),
                                  [](const Term *t1){return t1->getTerm() = term->getTerm();});

                if(it != terms.end()) {
                        std::cout << " .. found" << std::endl;
                } // end if
        } // end for
    } // compareToDoc

I'm pretty confused on what the lambda expression should look like to find terms that are the same. I tried the std::find route (commented out), but it never finds when two terms match. I believe find_if is the correct function, but I'm now struggling with the lambda.

Can anyone point me in the right direction? Thanks!

I figured it out. The std::find_if line must look like this:

auto it = find_if(terms.begin(), terms.end(),
                              [&term](const Term *t1){return t1->getTerm() == term->getTerm();});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM