The insert
function is used to insert an element into the set, and it returns a pair of an iterator to the inserted element (or the element that prevented the insertion) and a boolean value indicating whether the insertion took place. (It is exception for std::set, generally insert() returns iterator).
std::pair<std::set<int>::iterator, bool> result = mySet.insert(6);
if (result.second) {
std::cout << "Insertion successful. Inserted element: " << *(result.first) << std::endl;
} else {
std::cout << "Element already exists: " << *(result.first) << std::endl;
}
On the other hand, multiset::insert() function returns an iterator pointing to the inserted element in the multiset container.
-by Bard
1. Vector:
iterator insert(iterator pos, const value_type& value)
:
out_of_range
exception.iterator insert(iterator pos, initializer_list<value_type> il)
:
iterator insert(iterator pos, size_type n, const value_type& value)
:
n
copies of value
at pos
.length_error
if n
exceeds the container's maximum size.template<class InputIt> iterator insert(iterator pos, InputIt first, InputIt last)
:
[first, last)
at pos
.2. Set (Unique Elements):
iterator insert(const value_type& value)
:
(iterator, bool)
.
iterator
points to the inserted element if successful, or to an existing equivalent element.bool
is true
if insertion was successful (new element added), false
otherwise.out_of_range
exception.iterator insert(initializer_list<value_type> il)
:
il
, considering their unique properties.iterator insert(iterator hint, const value_type& value)
:
3. Multiset (Allowing Duplicates):
iterator insert(const value_type& value)
:
out_of_range
exception.iterator insert(initializer_list<value_type> il)
:
il
.iterator insert(iterator pos, const value_type& value)
:
pos
.template<class InputIt> iterator insert(iterator pos, InputIt first, InputIt last)
:
[first, last)
at pos
.4. List (Doubly Linked List):
iterator insert(iterator pos, const value_type& value)
:
value
before pos
.out_of_range
exception.iterator insert(iterator pos, initializer_list<value_type> il)
:
il
before pos
.5. Map (Unique Keys):
pair<iterator, bool> insert(const key_type& key, const mapped_type& value)
:
(iterator, bool)
.
iterator
points to the inserted element if successful, or to an existing equivalent element.bool
is true
if insertion was successful (new key-value pair added), false
otherwise.out_of_range
exception.iterator insert(initializer_list<pair<key_type, mapped_type>> il)
:
il
, considering their unique keys.iterator insert(iterator hint, const key_type& key, const mapped_type& value)
:
6. Multimap (Duplicates Keys Allowed):
iterator insert(const key_type& key, const mapped_type& value)
:
out_of_range
exception.iterator insert(initializer_list<pair<key_type, mapped_type>> il)
:
il
.iterator insert(iterator pos, const key_type& key, const mapped_type& value)
:
pos
(which may already have the same key).