.insert()
Anonymous contributor
Published Oct 17, 2024
Contribute to Docs
In C++, the .insert()
method inserts an element at a specified position in the deque.
Syntax
There are some variations in the syntax for the .insert()
method:
dequeName.insert(iterator position, const value_type& val)
deque_name.insert(iterator position, size_type n, const value_type& val)
deque_name.insert(iterator position, InputIterator first, InputIterator last)
position
: An iterator pointing to the location where the new element(s) should be inserted.val
: The element to be added to the deque. It can be of any data type thatdeque_name
holds.n
: Specifies the number of elements to insert into the deque, each initialized to a copy ofval
.first
: An iterator pointing to the beginning of a range of elements to be inserted into the deque.last
: An iterator pointing to one past the last element in the range to be inserted, indicating that all elements fromfirst
(inclusive) tolast
(exclusive) will be added.
Example
The example below showcases the use of the .insert()
method:
#include <iostream>#include <deque>int main() {// Create a deque of integersstd::deque<int> numbers;// Add elements to the dequenumbers.push_back(10);numbers.push_back(30);// Insert 20 at index 1 using .insert()numbers.insert(numbers.begin() + 1, 20);// Display the elements of the dequestd::cout << "Deque contents: ";for (int num : numbers) {std::cout << num << " ";}std::cout << std::endl;return 0;}
The above code generates the following output:
Deque contents: 10 20 30
Codebyte Example
Run the following codebyte example to understand the use of the .insert()
method:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours