Home  >  Article  >  Backend Development  >  What are the common types in C++ STL containers?

What are the common types in C++ STL containers?

WBOY
WBOYOriginal
2024-06-02 14:11:56626browse

The most common container types in C++ STL are Vector, List, Deque, Set, Map, Stack and Queue. These containers provide solutions for different data storage needs, such as dynamic arrays, doubly linked lists, and key- and value-based associative containers. In practice, we can use STL containers to organize and access data efficiently, such as storing student grades.

C++ STL容器中常见类型有哪些?

Common types in C++ STL containers

The Standard Template Library (STL) is a set of common containers provided in the C++ standard library and algorithms. These containers are used to store and organize data, and STL contains various container types to meet different data storage needs.

The most common STL container types include:

  • Vector: Dynamic arrays that efficiently store and access elements.
  • List: Doubly linked list, allowing fast insertion and deletion of elements.
  • Deque: Double-ended queue, supports efficient insertion and deletion operations.
  • Set: A set sorted by value and does not contain duplicate elements.
  • Map: An associative container sorted by key, with each key mapping to a value.
  • Stack: Last-in-first-out (LIFO) data structure that allows fast insertion and deletion of elements.
  • Queue: First-in-first-out (FIFO) data structure that allows fast insertion and deletion of elements.

Practical case:

Consider a program that needs to store student scores. We can use STL containers to manage and access data efficiently.

#include <iostream>
#include <vector>
#include <map>

using namespace std;

int main() {
  // 创建一个学生成绩的vector
  vector<int> grades;

  // 加入一些成绩
  grades.push_back(90);
  grades.push_back(85);
  grades.push_back(75);

  // 创建一个学生姓名到成绩的map
  map<string, int> student_grades;

  // 加入一些学生姓名和成绩
  student_grades["John"] = 90;
  student_grades["Jane"] = 85;
  student_grades["Jim"] = 75;

  // 访问学生成绩
  cout << "John's grade: " << student_grades["John"] << endl;

  // 遍历vector中的成绩
  for (int grade : grades) {
    cout << grade << " ";
  }
  cout << endl;

  return 0;
}

The above is the detailed content of What are the common types in C++ STL containers?. 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