C++ deque insert() Function
Example
Insert an element into a deque:
deque<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars.insert(cars.begin() + 2, "Toyota");
for (string car : cars) {
cout << car << "\n";
}
Definition and Usage
The insert() function inserts one or more elements at a specified position in a deque. The new elements are placed before the element at that position.
The position is given with an iterator (an object that points to an element, similar to a pointer). In the example, cars.begin() + 2 points to the third element (Ford), so Toyota is inserted before it.
The insert function is defined in the <deque> header file.
Syntax
deque.insert(iterator position, <type> value);
deque.insert(iterator position, size_t amount, <type> value);
deque.insert(iterator position, iterator start, iterator end);
Use one of the three forms. The size_t data type is a non-negative integer. <type> refers to the type of the data that the deque contains.
Parameter Values
| Parameter | Description |
|---|---|
| position | Required. An iterator pointing to the position where the new elements are inserted. |
| value | Required. The value to insert. |
| amount | Required. The number of copies of the value to insert. |
| start | Required. An iterator pointing to the first element to copy from another container. |
| end | Required. An iterator pointing to the position after the last element to copy. The element at this position is not copied. |
Technical Details
| Returns: | An iterator pointing to the first inserted element. |
|---|
Related Pages
Read more about deques in our Deque Tutorial.