Home » C++ STL

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.