Initializer_List Tutorial and Examples

The Initializer List is used to initialise the data members of a class. The constructor specifies the list of members to be initialised as a comma-separated list followed by a colon.

In this article we are going to discuss about initializer_list with examples

Initializer_List Tutorial with examples

We can make a light weight std::initializer listT> property. that will apply to a T-type array of elements

std::initialzer_list<int> given_data = {8,9,3,4};

So, if the compiler encounters elements in braces, such as a, b, and c, it generates a std::initializer list<T>, where T is the type of the list’s elements. All containers, such as vectors and lists, now have a parameterized  constructor that takes this std::initializer list<T> as an argument and inserts it.

As a result, we can use default elements to initialize a vector or some other container.

1)Initialize a vector using initializer list

We can initialize the vector using initializer list as given below:

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // given vector
    vector<string> vect(
        { "hello", "this", "is", "BTechGeeks" });
    // printing the value
    for (string value : vect)
        cout << value << "  ";
}

Output:

hello  this  is  BTechGeeks

2)Initialize a unordered_set using initializer list

unordered set has a constructor that takes an initialzer list as an argument and uses it to initialise the set.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    //  initialize the set with the initializer_list
    unordered_set<string> arrayset(
        { "hello", "this", "is", "BTechGeeks" });
    // printing the set
    for (string value : arrayset)
        cout << value << "  ";
}

Output:

is  this  BTechGeeks  hello

3)Initialize a unordered_map using initializer list

Unordered map has a overloaded constructor that takes an initializer list as an argument and can initialise an unordered map.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // creating new unordered map using initializer list
    unordered_map<std::string, int> stringmap(
        { { "Hello", 400 },
          { "This", 100 },
          { "is", 200 },
          { "BTechGeeks", 300 } });
    // printing the unordered map
    for (auto i : stringmap)
        cout << i.first << " " << i.second << endl;
    return 0;
}

Output:

BTechGeeks 300
This 100
is 200
Hello 400

4)Initialize a list using initializer_list

We can initialize the list using initializer list as given below:

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    // given stringlist
    list<string> stringlist(
        { "hello", "this", "is", "BTechGeeks" });
    // printing the value
    for (string value : stringlist)
        cout << value << "  ";
}

Output:

hello  this  is  BTechGeeks

Related Programs: