What is the usage of multiset in C++?

The multiset in C++ is a container in the STL that stores multiple identical elements in an ordered collection, automatically sorting them based on their values. It allows for duplicate elements while maintaining their order.

The usage of multiset is similar to other STL containers, and it can be used by including the header file for multiset. Here are some common uses of multiset:

  1. Create a multiset object.
std::multiset<int> mySet; // 创建一个存储int类型的multiset
  1. Insert elements:
mySet.insert(10); // 插入元素10
mySet.insert(20); // 插入元素20
mySet.insert(10); // 再次插入元素10
  1. Traverse through the multiset.
for(auto it = mySet.begin(); it != mySet.end(); ++it) {
    std::cout << *it << " ";
}
  1. Remove elements:
mySet.erase(10); // 删除元素10
  1. Search for an element:
auto it = mySet.find(20); // 查找元素20
if(it != mySet.end()) {
    std::cout << "Element found: " << *it << std::endl;
} else {
    std::cout << "Element not found" << std::endl;
}

Multiset allows for operations such as inserting, deleting, and searching elements while maintaining their order. When there is a need to store multiple identical elements and maintain sorting, multiset can be considered.

Leave a Reply 0

Your email address will not be published. Required fields are marked *