-1

我有一组类 Item :

std::set <Item> items; 

class Item
{
   private:
      std::string name;
      std::string serialNum; 
      int count; 
      double unitPrice;
  public :
      Item(std::string _name, std::string _serialNum, int _count, double _unitPrice); 
      Item(); // Ctor with no parameters , for compiling 
      ~Item(); //Dtor 
      double totalPrice();
      bool operator<(Item const & other)const;
      bool operator>(Item& other);
      bool operator==(Item& other);
      void operator=(const Item& other);
      void countUp();
      void countDown();
      void setup(std::string _name, std::string _serialNum, int _count, double _UnitPrice); 
      int getCount() const ;
      std::string getName() const;
      std::string  getSerial() const ;
      double getPrice() const ;
      void printItem() const ;
 };

我可以只在集合中搜索一个值吗?例如,按 item :: name 在集合中搜索。

4

2 回答 2

2

std::set是有序的(通常使用operator<它可以为您的类型重载)。通常,您决定一个特定的订单。(也许是serialNum你的情况?)

如果您使用不同的条件搜索相同的集合,例如name在您的情况下,您需要逐个元素遍历整个集合,因为集合顺序没有利润。

为此,有标准算法std::find_if,它在线性时间内执行此操作:

std::string name_to_find = "foo bar";

auto it = std::find_if(items.begin(), items.end(),
             [name_to_find](const Item & i){ return i.getName() == name_to_find; });

会给你一个迭代器it,指向集合中第一个具有名称的项目name_to_find(如果集合中不存在这样的元素,则为结束迭代器)。它独立于您提供的容器类型,因此它适用于集合、向量、数组...,并忽略容器的可能顺序。


上面的代码使用 C++11 lambda 提供了一个字面上内联的比较函数。如果你的编译器还不支持(或者如果你想支持旧的编译器),你必须使用仿函数来提供相同的功能。仿函数是一个类,其行为类似于函数(可以使用 调用operator())。

// Functor class to compare the name of an item with a specific name to look for
struct ItemByName {
    // The functor needs to remember what we're looking for in a member variable
    std::string name_to_find;

    // Constructor initializing the name to look for
    ItemByName(std::string name_to_find) : name_to_find(name_to_find) {}

    // The call-operator which is called by the algorithm find_if
    bool operator()(const Item &i) const {
        // This is the same body as in the lambda
        return i.getName() == name_to_find;
    }
};

然后find_if通过构造这个函子的一个实例来使用它:

std::set<Item>::iterator it = std::find_if(items.begin(), items.end(),
             ItemByName(name_to_find));

请注意,返回值现在被捕获在具有显式类型的变量中。在 C++11(上图)中,我们可以使用它auto来使其更易于键入。

于 2015-01-08T11:18:03.847 回答
0

设置说明设置 find设置 key comp。创建集合时,您可以提供Compare将用于比较元素的类。根据规格:

一个二元谓词,它接受两个与元素相同类型的参数并返回一个布尔值。表达式 comp(a,b),其中 comp 是这种类型的对象,a 和 b 是键值,如果在函数定义的严格弱排序中认为 a 在 b 之前,则应返回 true。(...) 默认为 less,它返回的结果与应用小于运算符 (a

默认情况下,set 用于less<T>比较元素,但您可以提供一个以您定义的方式比较项目的类。

于 2015-01-08T11:17:20.973 回答