C++ How to add new elements to the vector?

To add new elements to a vector in C++, you can use the push_back() method or the emplace_back() method.

The push_back() method adds an element to the end of the vector and copies or moves the given value into the vector. Here's an example:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v {1, 2, 3};
    v.push_back(4);
    v.push_back(5);

    for (int i : v) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    return 0;
}
So‮u‬rce:www.theitroad.com

Output:

1 2 3 4 5

In the above example, we first initialize a vector v with 3 elements. We then add two more elements to the end of the vector using the push_back() method.

The emplace_back() method constructs an element in place at the end of the vector using the given arguments. This can be more efficient than the push_back() method, especially for objects with expensive copy or move constructors. Here's an example:

#include <iostream>
#include <vector>

class Person {
public:
    Person(std::string name, int age) : name_(name), age_(age) {}
    std::string name_;
    int age_;
};

int main() {
    std::vector<Person> people;
    people.emplace_back("Alice", 25);
    people.emplace_back("Bob", 30);

    for (const auto& person : people) {
        std::cout << person.name_ << " is " << person.age_ << " years old." << std::endl;
    }

    return 0;
}

Output:

Alice is 25 years old.
Bob is 30 years old.

In the above example, we define a Person class with a constructor that takes a name and an age. We then create a vector of Person objects and add two new Person objects to the end of the vector using the emplace_back() method. Note that we use const auto& to avoid making unnecessary copies of the Person objects when iterating over the vector.