Home  >  Article  >  Backend Development  >  How to add elements to C++ STL container?

How to add elements to C++ STL container?

WBOY
WBOYOriginal
2024-06-02 16:27:00719browse

There are 2 ways to add elements to an STL container: the container uses push_back and emplace_back to add elements, and the associated container uses insert and emplace key-value pairs to insert elements.

如何向C++ STL容器中添加元素?

#How to add elements to a C++ STL container?

The C++ Standard Template Library (STL) provides powerful container classes for storing and managing data. Adding elements to these containers can be done in a variety of ways. This article will introduce different ways to add elements using STL containers and provide practical examples.

Container Types

STL provides a variety of container types, including the following:

  • Containers: For example vector and list, which store elements in order.
  • Associative containers: Such as map and set, which allow elements to be found based on key values.

Methods to add elements

Container

Methods to add elements to a container include:

  • push_back: Adds elements to the end of the container.
  • emplace_back: Create a new element in the container to avoid unnecessary copying.
  • insert: Insert an element at a specific position.

Associated container

Methods to add elements to the associated container include:

  • insert: will Key-value pairs are inserted into the container.
  • emplace: Creates a new element and inserts it into the container.

Practical case

Add elements to vector:

#include <vector>

int main() {
  // 创建一个 vector
  std::vector<int> numbers;

  // 使用 push_back 添加元素
  numbers.push_back(1);
  numbers.push_back(3);
  numbers.push_back(5);

  // 使用 emplace_back 添加元素
  numbers.emplace_back(7);

  // 打印 vector
  for (auto& number : numbers) {
    std::cout << number << " ";
  }

  return 0;
}

Add elements to map :

#include <map>

int main() {
  // 创建一个 map
  std::map<std::string, int> ages;

  // 使用 insert 添加元素
  ages["John"] = 25;
  ages["Mary"] = 30;

  // 使用 emplace 添加元素
  ages.emplace("Bob", 35);

  // 打印 map
  for (auto& [name, age] : ages) {
    std::cout << name << ": " << age << std::endl;
  }

  return 0;
}

The above is the detailed content of How to add elements to C++ STL container?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn