如何在 C++ 中搜索集合

how to search in a set in c++

本文关键字:搜索 集合 C++      更新时间:2023-10-16

我有一组类项目:

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 ;
 };

我可以只按一个值在集合中搜索吗?例如,在"按项目集 :: 名称"中搜索。

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 使其更容易键入。

设置描述。设置查找,设置键组合。创建集合时Compare可以提供将用于比较元素的类。根据规格:

一个

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

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