How to insert an element at a specific index in a vector with C++

2 Answers

0 votes
#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {4, 9, 8, 6, 5, 7};
    int index = 2; 
    int newElement = 100; 

    // Insert the new element at the specified index
    vec.insert(vec.begin() + index, newElement);

    for (int elem : vec) {
        std::cout << elem << " ";
    }
}


  
/*
run:
  
4 9 100 8 6 5 7 
  
*/

 



answered Feb 20, 2025 by avibootz
0 votes
#include <iostream>
#include <vector>

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

    // Define position and value to insert
    int pos = 2; // Index where the element will be inserted
    int value = 888;

    // Ensure position is valid
    if (pos >= 0 && pos <= vec.size()) {
        vec.insert(vec.begin() + pos, value);
    }

    // Print the updated vector
    for (int num : vec) {
        std::cout << num << " ";
    }
}



/*
run:

1 2 888 3 4 5 

*/

 



answered May 3, 2025 by avibootz

Related questions

1 answer 159 views
1 answer 116 views
1 answer 104 views
1 answer 199 views
...