An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C++.
Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos.
Here’s how to do it.
- First get the element to be inserted, say x
- Then get the position at which this element is to be inserted, say pos
- Then shift the array elements from this position to one position forward, and do this for all the other elements next to pos.
- Insert the element x now at the position pos, as this is now empty.
Below is the implementation of the above approach:
1 2 3 4 5 6 7 8 9 10 1 2 3 4 50 5 6 7 8 9 10
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Queries to insert, delete one occurrence of a number and print the least and most frequent element
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- Reverse an array upto a given position
- Inserting elements in std::map (insert, emplace and operator )
- std::string::insert() in C++
- emplace vs insert in C++ STL
- multimap insert() in C++ STL
- set insert() function in C++ STL
- map insert() in C++ STL
- vector insert() function in C++ STL
- multiset insert() function in C++ STL
- deque insert() function in C++ STL
- unordered_set insert() function in C++ STL
- unordered_multiset insert() function in C++ STL
- list insert() in C++ STL
- unordered_map insert in C++ STL
- unordered_multimap insert() in C++ STL
- Set position with seekg() in C++ language file handling
- How to find the maximum element of an Array using STL in C++?
- How to find the minimum and maximum element of an Array using STL in C++?