William M. answered 12/15/19
College Professor of C++ with 7+ years of teaching experience
OK, there are two questions here:
all of the C++ standard library collection classes (std::vector<T>, std::list<T>, ...) have that behavior built-in since C++11.
Be sure that you have that compiler setting turned on, like such
e.g., if your file is called vect.cpp, you would compile it from the command line with unix as:
g++ vect.cpp -std=c++11 -o vect
and then run it as:
./vect
Here's the code:
#include <iostream>
#include <vector>
int main(int argc, const char* argv[]) {
std::vector<int> v = { 10, 20, 30 };
for (int el : v) {
std::cout << el << " ";
}
std::cout << "\n";
return 0;
}
Second question: What if you wanted to create a CUSTOM CLASS, and have that behavior built in? Then you would do the following:
#include <iostream>
#include <vector>
#include <initializer_list>
class collection {
public:
// use default ctor (which calls default ctor for std::vector<T>)
collection() = default;
// call the default constructor BEFORE using the std::initializer_list<T>
collection(const std::initializer_list<int>& li)
: collection() {
for (int el : li) {
push_back(el);
}
}
void push_back(int val) { v.push_back(val); } // std::vector<int> does work
bool empty() const { return v.empty(); } // ditto
size_t size() const { return v.size(); } // ditto
friend std::ostream& operator<<(std::ostream& os, const collection& c) {
if (c.empty()) { return os << "collection is empty\n"; }
for (int el : c.v) {
os << el << " ";
}
return os << "\n";
}
private:
std::vector<int> v;
};
int main(int argc, const char* argv[]) {
collection c = { 4, 17, 28, 33 }; // use init list for CUSTOM collection class
std::cout << "c is: " << c << "\n";
return 0;
}