Home >Backend Development >C++ >How to add elements to C++ STL container?
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.
#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:
vector
and list
, which store elements in order. 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:
Associated container
Methods to add elements to the associated container include:
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!