如何在 C++ 中搜索集合
how to search in a set in c++
我有一组类项目:
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>
来比较元素,但您可以提供一个类,用于以您定义的方式比较项目。
- 处理多个异常集合的C++方法
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- 有根的二进制搜索树.保留与其父级的链接
- 如何将ampl中的集合表示为c++中的向量
- 检查值是否在集合p1和p2中,但不在p3中
- 带过滤器的现代迭代c++集合
- 在C++中搜索嵌套多映射值
- 如何将结构插入到集合中并打印集合的成员
- 基于函数而不是集合的二分搜索或迭代器?
- C++到Java:高效地搜索集合
- 在 c++ 中搜索集合的最有效方法是什么
- 如何在C++派生对象的集合中进行搜索和赋值
- 如何在 C++ 中搜索集合
- 如何搜索字符串是否是存储在集合中的字符串的前缀
- 在C++中定义和搜索相关订单上的集合
- 在具有非关键字类型的集合中进行有效搜索
- 搜索集合中某项的一部分
- 在集合中搜索
- 基于数据集合执行二叉树搜索
- 使用 STL 映射/集合/多重集/多重映射,如何查找大于或等于搜索键的第一个值