×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

Changing a particular element of a vector in C++ STL

C++ vector | changing an element: Here, we are going to learn how to change a particular element of a C++ STL Vector?
Submitted by IncludeHelp, on June 04, 2019

Given a C++ STL vector and we have to change a particular element.

Changing a particular element of a vector

We can change a particular element of a C++ STL vector using following ways

  1. Using vector::at() function
  2. And, using vector::operator[]

Note: To use vector – include <vector> header, and to use vector::at() function and vector::operator[] – include <algorithm> header or we can simply use <bits/stdc++.h> header file.

C++ STL program to change an element of a vector

//C++ STL program to change an element of a vector

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v1{ 10, 20, 30, 40, 50 };

    //printing elements
    cout << "vector elements before the change..." << endl;
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    //changing element at index 1 using at()
    v1.at(1) = 100;
    //changing element at index 2 using operator[]
    v1[2] = 200;

    //printing elements
    cout << "vector elements after the change..." << endl;
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

vector elements before the change...
10 20 30 40 50
vector elements after the change...
10 100 200 40 50

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.