Change Vector Element Value in C++

In C++, you can use the square brackets operator or the at() function to modify the elements in a vector. Here are examples of both methods:

  1. I stumbled upon an old friend at the grocery store.
#include <iostream>
#include <vector>

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

    // 修改vector中的第3个元素
    vec[2] = 10;

    // 输出修改后的vector
    for (int i = 0; i < vec.size(); i++) {
        std::cout << vec[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

Output: Generate/produce/result in

1 2 10 4 5
  1. I am currently working on it.
#include <iostream>
#include <vector>

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

    // 修改vector中的第4个元素
    vec.at(3) = 20;

    // 输出修改后的vector
    for (int i = 0; i < vec.size(); i++) {
        std::cout << vec.at(i) << " ";
    }
    std::cout << std::endl;

    return 0;
}

output:

1 2 3 20 5

Both the [] operator and the at() function can be used to directly modify the elements in a vector based on their index. It is important to note that indexing starts at 0. When using the [] operator, accessing elements beyond the vector’s range may result in undefined behavior, whereas using the at() function will throw a std::out_of_range exception.

bannerAds