Welcome to the exciting world of C++11 std::initializer_list! In this lesson, we'll dive deep into understanding this powerful feature and learn how to use it effectively in your C++ projects.
std::initializer_list is a template class introduced in C++11. It provides a simple and efficient way to initialize containers and other classes with a list of values.
Before C++11, initializing containers with a list of values required writing a loop or using the push_back method. With std::initializer_list, we can initialize a container with a list of values in a single line, making the code more concise and easier to read.
Let's see how to use std::initializer_list with an example.
#include <iostream>
#include <vector>
#include <initializer_list>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5}; // Using std::initializer_list
for (int number : numbers) {
std::cout << number << std::endl;
}
return 0;
}In the above example, we've initialized a std::vector<int> named numbers with the help of std::initializer_list. We can see that the code is more readable and easier to understand compared to initializing the same vector using a loop.
std::initializer_list can also be used to initialize custom classes. Here's an example of a simple class Person with an initializer list constructor:
#include <iostream>
#include <string>
#include <initializer_list>
class Person {
public:
Person(std::initializer_list<std::string> names) : names_(names) {}
void printNames() {
for (const auto& name : names_) {
std::cout << name << std::endl;
}
}
private:
std::vector<std::string> names_;
};
int main() {
Person person = {"John", "Doe"}; // Using std::initializer_list to initialize a Person object
person.printNames();
return 0;
}In this example, we've defined a Person class with an initializer list constructor. We can create a Person object and initialize it with a list of names using std::initializer_list.
What is the purpose of `std::initializer_list` in C++?
That's it for today! We've covered the basics of std::initializer_list and seen examples of using it with both containers and classes. As you practice more, you'll find that std::initializer_list can greatly improve the readability and efficiency of your C++ code.
Happy coding! š»š»š»