简体   繁体   English

如何使用字符串查找对象的对象的唯一指针向量返回迭代器?

[英]How can I return an iterator for a vector of unique pointers to objects using a string to find the object?

I have a List class that contains a vector with unique pointers to ListItem objects. 我有一个List类,其中包含一个带有指向ListItem对象的唯一指针的向量。 I would like to create a function that returns an iterator to a specific ListItem. 我想创建一个将迭代器返回到特定ListItem的函数。 The comparison would be made using a string argument to compare against the ListItem string name variable. 比较将使用字符串参数与ListItem字符串名称变量进行比较。

I've tried using std::find, find_if, etc. with no luck. 我尝试使用std :: find,find_if等,但没有运气。 When I've iterated over the vector I can't figure out how to access the name variable in the ListItem object to make the comparison. 当我遍历向量时,我不知道如何访问ListItem对象中的名称变量以进行比较。

#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <iterator>
#include <algorithm>

class ListItem {
private:
    double quantity{ 0 };
    std::string weightUnit;
    std::string name;

public:
    ListItem(double quantity, std::string weightUnit, std::string name) : quantity{ quantity }, weightUnit{ weightUnit }, name{ name } {}
    ~ListItem() {}

    double getQuantity() { return quantity; }
    std::string getWeightUnit() { return weightUnit; }
    std::string getName() { return name; }

};

class List {
private:
    std::vector<std::unique_ptr<ListItem>>mylist;

public:
    std::vector<std::unique_ptr<ListItem>>::iterator search(std::string str) {
    /* This is where I'm stuck */

    }

    void removeListItem(std::string &name) {
        auto it = search(name);
        if (it != mylist.end()) {
            mylist.erase(it);
        }
    }

    void addListItem(double quantity, std::string weightUnit, std::string name) {

        mylist.push_back(std::make_unique<ListItem>(quantity, weightUnit, name));
    }

};



int main() {
    auto list = std::make_unique<List>();
    list->addListItem(2, "kg", "beef");
    list->addListItem(4, "lbs", "eggs");
    list->search("test");

}

You need to capture the str argument in the lambda that you're using as a predicate. 您需要在用作谓词的lambda中捕获str参数。

   std::vector<std::unique_ptr<ListItem>>::iterator search(std::string str) {
        auto tester = [str](std::unique_ptr<ListItem>& li) { return li->getName() == str; };
        return std::find_if(mylist.begin(), mylist.end(), tester);
    }

Note also the argument type in the lambda will be a unique_ptr<ListItem> . 还要注意,lambda中的参数类型将是unique_ptr<ListItem> (In c++14 you could just use auto ) (在c ++ 14中,您可以只使用auto

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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