elements of set c++
The elements of a set in C++ can be represented using the set container provided by the Standard Template Library (STL). The set container is an ordered collection of unique elements, where each element is stored only once. Here's a step-by-step explanation of working with sets in C++:
Include the necessary header file: To use the set container, you need to include the
header file in your C++ program. Declare the set: Declare a set variable by specifying the element type enclosed in angle brackets, followed by the name of the set variable. For example, to declare a set of integers, you can write:
cpp
set<int> mySet;
- Insert elements into the set: Use the
insert()
function to add elements to the set. Theinsert()
function takes the value to be inserted as an argument. For example, to insert the values 10, 20, and 30 into the set, you can write:
cpp
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
Note that the elements in the set are automatically sorted in ascending order.
- Accessing the elements: Since sets are ordered collections, you can access their elements using iterators. The iterator
begin()
points to the first element in the set, and the iteratorend()
points to the position just after the last element. Here's an example of accessing the elements in the set:
cpp
for (auto it = mySet.begin(); it != mySet.end(); ++it) {
cout << *it << " ";
}
This will output: 10 20 30
, as the elements are sorted in ascending order.
- Removing elements from the set: Use the
erase()
function to remove elements from the set. Theerase()
function takes the value to be removed as an argument. For example, to remove the value 20 from the set, you can write:
cpp
mySet.erase(20);
After this operation, the set will contain only the values 10 and 30.
- Checking the size of the set: Use the
size()
function to get the number of elements in the set. For example, to get the size of the set, you can write:
cpp
cout << "Size of the set: " << mySet.size() << endl;
This will output: Size of the set: 2
.
- Checking if an element exists in the set: Use the
find()
function to check if a specific element exists in the set. Thefind()
function returns an iterator pointing to the element if found, orend()
if the element is not found. For example, to check if the value 30 exists in the set, you can write:
cpp
auto it = mySet.find(30);
if (it != mySet.end()) {
cout << "Element found in the set." << endl;
} else {
cout << "Element not found in the set." << endl;
}
This will output: Element found in the set.
These are the basic steps for working with sets in C++. Remember that sets only store unique elements, so inserting duplicate elements will have no effect on the set.