SoFunction
Updated on 2025-05-22

Set ordered and unique way to collect sets in C++

In C++'s Standard Template Library (STL), set is a very practical associative container.

It's like an "ordered collection" where the elements are arranged in a specific order and each element is unique. Next, let's get a deeper look at all aspects of set.

1. The basic concept of set

set is essentially a class template that is implemented based on a red-black tree (a self-balancing binary search tree).

This makes the elements in set automatically sort in ascending order of key values, and no duplicate elements are allowed. Unlike vector, set does not support random access, and elements can only be accessed sequentially through iterators.

2. Definition and initialization of set

  • Before using set, you need to include the header file.
  • Here are several common definitions and initialization methods:
#include
#include

int main() {
// Define an empty set to store int type datastd::set s1;

// Initialize set with the initialization liststd::set<int> s2 = {5, 2, 3, 1, 4};

// Copy constructorstd::set<int> s3(s2);

return 0;
}

3. Common operations of set

1. Insert elements

  • The insert() function is used to insert elements into set.
  • If the inserted element already exists, the insertion operation is ignored.
#include
#include

int main() {
std::set s;
// Insert element(3);
(1);
(2);
// Try to insert duplicate elements(2);
// Output: 1 2 3for (int num : s) {
std::cout << num << " ";
}
return 0;
}

2. Delete elements

  • The erase() function is used to delete elements in set, and the elements to be deleted can be specified through a value or an iterator.
#include
#include

int main() {
std::set s = {1, 2, 3, 4, 5};
// Delete elements with a value of 3(3);
// Delete the first element(());
// Output: 2 4 5for (int num : s) {
std::cout << num << " ";
}
return 0;
}

3. Find elements

  • The find() function is used to find elements of the specified value.
  • If found, return an iterator pointing to the element; otherwise, return an end() iterator.
#include
#include

int main() {
std::set s = {1, 2, 3, 4, 5};
// Find element 3auto it = (3);
if (it != ()) {
std::cout << “Find the element:” << *it << std::endl;
} else {
std::cout << “未Find the element” << std::endl;
}
return 0;
}

4. Get size and judge empty

  • The size() function returns the number of elements currently stored in set;
  • empty() function is used to determine whether set is empty.
#include
#include

int main() {
std::set s = {1, 2, 3};
std::cout << "Size: " << () << std::endl;
std::cout << "Is it empty: " << (() ? “yes” : “no”) << std::endl;
return 0;
}

4. Iterator of set

set provides a variety of iterators, such as begin() returns an iterator pointing to the first element, end() returns an iterator pointing to the last element; rbegin() and rend() are used for reverse traversal.

#include
#include

int main() {
std::set s = {3, 1, 2};
// Forward traversalfor (auto it = (); it != (); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// Reverse traversalfor (auto rit = (); rit != (); ++rit) {
std::cout << *rit << " ";
}
return 0;
}

C++11 introduces a range-based for loop to make traversal sets more concise:

#include
#include

int main() {
std::set s = {3, 1, 2};
for (int num : s) {
std::cout << num << " ";
}
return 0;
}

5. Things to note when using set

Automatically sort elements:

  • The elements in the set will be automatically arranged in ascending order of key values, which is determined by the nature of the red and black tree.
  • If you need to customize the sorting rules, you can do it by passing in the comparison function.
#include
#include

struct Greater {
bool operator()(const int&amp; a, const int&amp; b) const {
return a &gt; b;
}
};

int main() {
// Use custom comparison function to sort in descending orderstd::set&lt;int, Greater&gt; s = {3, 1, 2};
// Output: 3 2 1for (int num : s) {
std::cout &lt;&lt; num &lt;&lt; " ";
}
return 0;
}

Elements cannot be modified:

  • The elements in the set are constants and cannot be modified directly.
  • If you need to modify the value of an element, you must first delete the element and then insert a new element.
#include
#include

int main() {
std::set s = {1, 2, 3};
// Error: The elements in the set cannot be modified directly// *() = 10;
// Correct way: delete first, then insertauto it = (1);
if (it != ()) {
(it);
(10);
}
return 0;
}

Summarize

As a powerful and flexible association container in C++, set plays an important role in processing orderly and unique data sets.

Mastering its definition, initialization, common operations and precautions can help us write more efficient and reliable code.

Whether it is daily development or algorithm competition, set is an indispensable tool for us.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.