【问题标题】:How can I return an iterator for a vector of unique pointers to objects using a string to find the object?如何使用字符串返回指向对象的唯一指针向量的迭代器以查找对象?
【发布时间】:2019-11-19 09:19:45
【问题描述】:

我有一个 List 类,其中包含一个带有指向 ListItem 对象的唯一指针的向量。我想创建一个将迭代器返回到特定 ListItem 的函数。将使用字符串参数与 ListItem 字符串名称变量进行比较。

我尝试过使用 std::find、find_if 等,但没有成功。当我遍历向量时,我不知道如何访问 ListItem 对象中的 name 变量来进行比较。

#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");

}

【问题讨论】:

  • 你能说明你是如何使用find_if的吗?这是这项工作的“标准”工具。
  • 有了这个,其中 str 是我传递给函数的字符串: return std::find_if(mylist.begin(), mylist.end(), [](ListItem a) { return a .getName() == str; });
  • 您的向量包含unique_ptr&lt;ListItem&gt;'s。这就是你的 lambda 需要采取的(通过引用)。
  • 我已经改变了它,但我仍然收到错误,如果我无法弄清楚如何将它与 str 参数进行比较:'return std::find_if(mylist.begin() , mylist.end(), [](const std::unique_ptr& a) { return a->getName() == "beef"; });'

标签: c++ class vector iterator unique-ptr


【解决方案1】:

您需要在用作谓词的 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);
    }

还要注意 lambda 中的参数类型将是 unique_ptr&lt;ListItem&gt;。 (在 c++14 中你可以使用 auto

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    相关资源
    最近更新 更多