C++ 的 set 容器是一种关联式容器,它包含一组唯一的对象。以下是 set 容器的一些常用操作:
-
插入元素:使用
insert()方法将元素插入到set中。例如:std::set<int> my_set; my_set.insert(10); my_set.insert(20); my_set.insert(30); -
删除元素:使用
erase()方法从set中删除元素。例如:my_set.erase(20); -
查找元素:使用
find()方法查找set中的元素。如果找到了元素,则返回指向该元素的迭代器;否则返回指向set中的尾部元素的迭代器。例如:auto it = my_set.find(20); if (it != my_set.end()) { std::cout << "Found: " << *it << std::endl; } else { std::cout << "Not found" << std::endl; } -
遍历元素:使用迭代器遍历
set中的所有元素。例如:for (auto it = my_set.begin(); it != my_set.end(); ++it) { std::cout << *it << " "; } std::cout << std::endl; -
检查元素是否存在:使用
count()方法检查set中是否存在指定元素。如果存在,则返回 1;否则返回 0。例如:if (my_set.count(20) > 0) { std::cout << "20 exists in the set" << std::endl; } else { std::cout << "20 does not exist in the set" << std::endl; } -
获取集合大小:使用
size()方法获取set中元素的数量。例如:std::cout << "Set size: " << my_set.size() << std::endl; -
清空集合:使用
clear()方法清空set中的所有元素。例如:my_set.clear(); -
检查是否为空:使用
empty()方法检查set是否为空。如果为空,则返回true;否则返回false。例如:if (my_set.empty()) { std::cout << "Set is empty" << std::endl; } else { std::cout << "Set is not empty" << std::endl; }
以上就是关于“C++的set容器有哪些操作”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm