C++ How to change the values of vector elements?

To change the values of vector elements in C++, you can use the subscript operator [] or the at() method.

The subscript operator [] allows you to access the elements of a vector using an index, and you can assign a new value to the element at the specified index. Here's an example:

refer‮tfigi:ot ‬idea.com
#include <iostream>
#include <vector>

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

    // change the value of the element at index 2
    v[2] = 100;

    // print the updated vector
    for (int i : v) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output:

1 2 100 4 5

In the above example, we first initialize a vector v with 5 elements. We then use the subscript operator [] to change the value of the element at index 2 from 3 to 100.

The at() method is similar to the subscript operator [], but it also performs bounds checking and throws an exception if the index is out of range. Here's an example:

#include <iostream>
#include <vector>

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

    // change the value of the element at index 2
    v.at(2) = 100;

    // print the updated vector
    for (int i : v) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output:

1 2 100 4 5

In the above example, we use the at() method to change the value of the element at index 2 from 3 to 100. Since the index is valid, the program runs without any errors. However, if we try to access an out-of-range index using the at() method, the program will throw an out_of_range exception.