#include <iostream>
#include <vector>
class MyClass {
public:
int data;
MyClass(int d) : data(d) {}
};
int main() {
std::vector<MyClass> myVec;
myVec.push_back(MyClass(1));
myVec.push_back(MyClass(2));
myVec.push_back(MyClass(3));
for (auto& obj : myVec) {
std::cout << obj.data << std::endl;
}
return 0;
}
- Including necessary libraries:
iostream
and vector
. - Declaring a class named
MyClass
with a public int
member variable data
. - Defining a constructor for
MyClass
that initializes the data
member with the provided argument. - In the
main()
function: - Declaring a vector named
myVec
that stores objects of type MyClass
. - Adding three
MyClass
objects with data values 1, 2, and 3 into the myVec
vector using push_back()
. - Entering a
for
loop that iterates through each object (denoted by auto& obj
) in the myVec
vector. - Inside the loop, printing the
data
member of each object using std::cout
. - Finally, returning 0 to indicate successful program execution.