📅  最后修改于: 2023-12-03 14:39:51.689000             🧑  作者: Mango
In C++, std::set
is an ordered associative container that stores unique elements. It is part of the C++ Standard Template Library (STL) and provides efficient operations for inserting, searching, and erasing elements.
The insert()
function is a member function of std::set
that allows programmers to insert elements into the set.
The syntax of the insert()
function is as follows:
std::pair<iterator, bool> insert(const value_type& value);
value
: The value to be inserted into the set.The insert()
function returns a pair consisting of an iterator and a boolean value.
true
if the insertion was successful (element was not already present), and false
otherwise.Here is an example that demonstrates the usage of the insert()
function:
#include <iostream>
#include <set>
int main() {
std::set<int> mySet;
// Inserting elements
std::pair<std::set<int>::iterator, bool> result1 = mySet.insert(42);
if (result1.second) {
std::cout << "Element 42 inserted at position: " << *result1.first << std::endl;
}
std::pair<std::set<int>::iterator, bool> result2 = mySet.insert(42);
if (!result2.second) {
std::cout << "Element 42 not inserted as it already exists at position: " << *result2.first << std::endl;
}
// Printing the set
std::cout << "Elements in the set: ";
for (const auto& element : mySet) {
std::cout << element << ", ";
}
return 0;
}
```cpp
#include <iostream>
#include <set>
int main() {
std::set<int> mySet;
// Inserting elements
std::pair<std::set<int>::iterator, bool> result1 = mySet.insert(42);
if (result1.second) {
std::cout << "Element 42 inserted at position: " << *result1.first << std::endl;
}
std::pair<std::set<int>::iterator, bool> result2 = mySet.insert(42);
if (!result2.second) {
std::cout << "Element 42 not inserted as it already exists at position: " << *result2.first << std::endl;
}
// Printing the set
std::cout << "Elements in the set: ";
for (const auto& element : mySet) {
std::cout << element << ", ";
}
return 0;
}