example2_use_with_custom_objects.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <vector>
#include <string>

class Person {
private:
    std::string name;
    int age;

public:
    Person(const std::string& n, int a) : name(n), age(a) {}

    void display() const {
        std::cout << name << " (" << age << " years old)" << std::endl;
    }
};

int main() {
    std::vector<Person> people;

    // Adding Person objects to the vector
    people.push_back(Person("Alice", 30));
    people.push_back(Person("Bob", 25));
    people.emplace_back("Charlie", 35);  // Using emplace_back for in-place construction

    // Displaying all persons
    std::cout << "People in the vector:" << std::endl;
    for (const auto& person : people) {
        person.display();
    }

    return 0;
}
Back to push_back