📜  C++ STL-Set.operate=()函数(1)

📅  最后修改于: 2023-12-03 14:39:51.689000             🧑  作者: Mango

C++ STL Set::insert() Function

Introduction

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.

Syntax

The syntax of the insert() function is as follows:

std::pair<iterator, bool> insert(const value_type& value);
Parameters
  • value: The value to be inserted into the set.
Return Value

The insert() function returns a pair consisting of an iterator and a boolean value.

  • Iterator: It represents the position where the element is inserted or the position of an equivalent element in the set if the value already exists.
  • Boolean: It is set to true if the insertion was successful (element was not already present), and false otherwise.
Example

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;
}
Markdown Code Block
```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;
}