C++ 中的 set 是一种关联容器,它包含一组唯一的对象。set 中的元素在插入时自动排序,并且不允许重复。以下是一些常用的 set 操作:
insert() 方法将元素插入到 set 中。std::set<int> mySet;
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
erase() 方法从 set 中删除元素。mySet.erase(20); // 删除元素 20
find() 方法查找 set 中的元素。如果找到了元素,则返回指向该元素的迭代器;否则返回指向 set 中的尾部元素的迭代器。auto it = mySet.find(30);
if (it != mySet.end()) {
std::cout << "Found: " << *it << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
set 中的所有元素。for (auto it = mySet.begin(); it != mySet.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
count() 方法检查 set 中是否存在指定元素。如果存在,则返回 1;否则返回 0。if (mySet.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: " << mySet.size() << std::endl;
clear() 方法清空 set 中的所有元素。mySet.clear();
empty() 方法检查 set 是否为空。如果为空,则返回 true;否则返回 false。if (mySet.empty()) {
std::cout << "Set is empty" << std::endl;
} else {
std::cout << "Set is not empty" << std::endl;
}