gpt4 book ai didi

c++ - 如何使用迭代器和 find/find_f 在类的 C++ vector 中查找实际值

转载 作者:行者123 更新时间:2023-11-28 08:13:33 24 4
gpt4 key购买 nike

我在尝试让类关联正常工作时遇到了一些麻烦。

我有一个名为 Items 的类对象 vector 。每个项目都有一个值,例如名称、价格等。在 Items 类中,有 setter 和 getter 来更改值并返回它们。

std::string choice; // users choice
ListOfOrders::iterator iter = orderList->end(); iter--;
// the last order inserted, ignore this this is used to get the last order so
//we can pass the items to it (the order class has a vector of pointers
//(items) that we are trying to pass to now.)

ListOfItems::iterator itemiter; // make the items iter
listItems(itemList); // function in the main that returns the list of items using the getters and a vector iterator.
while(choice != "x") // until the user quits
{
// here is my prob, ofc, i can just compare the users entered choice of item (name) to the iterator because thats just returning a pointer to the class object, what i need to do it call the getName() getter from each of the objects and comparer that
(*itemiter)->getName() = find (itemList->begin(), itemList->end(), choice);

if (itemiter == itemList->end())
{
std::cout << "sorry item not found please try again." << std::endl;
}
else
{
(*iter)->addItem(*itemiter); // pass the item object off to the order object's vector of items.
}
}

我知道类似这样的东西(见下文(还没有编译它,只是快速输入它给你一个想法))可以使用并且它会起作用,但一定有更好的方法吧?

std::string choice; // users choice
cin >> choice;
ListOfOrders::iterator iter = orderList->end(); iter--; // the last order inserted
if(lookForItem(choice))
{
std::cout << "Yes\n";
}
else
{
std::cout << "no\n";
}

bool lookForItem(std::string choice)
{
ListOfItems::iterator itemiter; // make the items iter

itemiter = itemList->begin();
while(itemiter != itemList->end())
{
if((*itemiter)->getName() == choice)
{
(*iter)->addItem(*itemiter);
}
iter++;
}
return false;
}

最佳答案

在现代 C++ 中,使用 lambda 非常简单:

auto it = std::find_if(itemList.begin(), itemList.end(),
[&choice](Item const & x) { return x.name == choice; } );

当然,将 lambda 拼写为传统谓词并不难:

struct FindItemByName
{
FindItemByName(std::string const & s) : choice(s) { }
bool operator()(Item const & x) const { return x.name == choice; }
private:
std::string const & choice;
};

ListOfItems::iterator it
= std::find_if(itemList.begin(), itemList.end(), FindItemByName(choice));

关于c++ - 如何使用迭代器和 find/find_f 在类的 C++ vector 中查找实际值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8379640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com