Home  >  Article  >  Backend Development  >  How to get the size of a C++ STL container?

How to get the size of a C++ STL container?

WBOY
WBOYOriginal
2024-06-05 18:20:00402browse

By using the size() member function of the container, you can get the number of elements in the container. For example, the size() function of the vector container returns the number of elements, the size() function of the list container returns the number of elements, the length() function of the string container returns the number of characters, and the capacity() function of the deque container returns the number of allocated memory blocks.

如何获取C++ STL容器的大小?

#How to get the size of a C++ STL container?

Introduction

The C++ Standard Template Library (STL) provides a set of containers for storing and organizing data. STL containers typically have a size() member function that retrieves the number of elements in the container.

Syntax

size_t size() const;
  • Return type: Unsigned integer (size_t), representing the size of the elements in the container quantity.

Practical case

Consider a vector container containing an integer array:

#include <vector>

int main() {
  // 创建一个包含 5 个整数的 vector
  std::vector<int> myVector = {1, 2, 3, 4, 5};

  // 获取 vector 的大小
  size_t vectorSize = myVector.size();

  // 打印 vector 的大小
  std::cout << "Vector size: " << vectorSize << std::endl;

  return 0;
}

Output:

Vector size: 5

Other STL container size acquisition functions

The following are other common STL container size acquisition functions:

  • size() - vector, list, stack
  • ##length() - string
  • capacity() - deque

The above is the detailed content of How to get the size of a 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