Set Basics

Basic Set Operations in C++

BeginnerTopic: STL Containers Programs
Back

C++ Set Basics Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <set>
using namespace std;

int main() {
    // Create set
    set<int> numbers;
    
    // Insert elements
    numbers.insert(5);
    numbers.insert(2);
    numbers.insert(8);
    numbers.insert(1);
    numbers.insert(5);  // Duplicate, will be ignored
    numbers.insert(3);
    
    // Display set
    cout << "Set elements (sorted and unique): ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    // Check if element exists
    if (numbers.find(5) != numbers.end()) {
        cout << "Element 5 found in set" << endl;
    }
    
    // Count occurrences (0 or 1 for set)
    cout << "Count of 5: " << numbers.count(5) << endl;
    cout << "Count of 10: " << numbers.count(10) << endl;
    
    // Size
    cout << "Set size: " << numbers.size() << endl;
    
    // Erase element
    numbers.erase(5);
    cout << "\nAfter erasing 5: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;
    
    // Lower and upper bound
    set<int> s = {1, 2, 3, 5, 7, 9};
    auto it_low = s.lower_bound(4);  // First element >= 4
    auto it_up = s.upper_bound(6);   // First element > 6
    
    cout << "\nLower bound of 4: " << *it_low << endl;
    cout << "Upper bound of 6: " << *it_up << endl;
    
    return 0;
}
Output
Set elements (sorted and unique): 1 2 3 5 8
Element 5 found in set
Count of 5: 1
Count of 10: 0
Set size: 5

After erasing 5: 1 2 3 8
Lower bound of 4: 5
Upper bound of 6: 7

Understanding Set Basics

Set is a container that stores unique elements in sorted order. Duplicates are automatically removed. Operations: insert(), find(), erase(), count(), lower_bound(), upper_bound(). Sets are implemented as balanced binary search trees, providing O(log n) operations. Useful for maintaining sorted, unique collections.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents