Open In App

How to Initialize a Set with an Array in C++?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, an array stores data in contiguous memory locations and can have duplicates as well whereas a set stores unique elements only in a sorted order. In this article, we will learn how to initialize a set with an array in C++.

For Example,

Input:
arr[]={2, 1, 5, 4, 3, 5};
Output:
Element in Set are: 1 2 3 4 5

Initialize a Set With Array in C++

To initialize the std::set with the elements of an array, we can use the range constructor of the set and pass the pointers of the beginning and the end of the array.

Syntax

std::set <int> mySet(arr, arr + n);

where n is the number of elements in the array.

C++ Program to Initialize a Set with an Array

The below program demonstrates how we can initialize a set with an element of an array in C++.

C++




// C++ program to initialize set with an array elements
  
#include <iostream>
#include <set>
using namespace std;
  
int main()
{
    // Defining an array
    int myArray[] = { 2, 1, 5, 4, 3, 5 };
  
    // Initializing the set with the array
    set<int> mySet(myArray, myArray + 6);
  
    // printing the content of set
    cout << "Elements in a set are:" << endl;
    for (auto& elem : mySet) {
        cout << elem << " ";
    }
  
    return 0;
}


Output

Elements in a set are:
1 2 3 4 5 

Time Complexity: O(n log(n))
Auxilliary Space: O(n)

Note: We can also use set::insert() function inside a loop to initialize set with array elements in C++.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads