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

WBOY
Release: 2024-06-05 18:20:00
Original
375 people have browsed it

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 asize()member function that retrieves the number of elements in the container.

Syntax

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

Practical case

Consider avectorcontainer containing an integer array:

#include  int main() { // 创建一个包含 5 个整数的 vector std::vector myVector = {1, 2, 3, 4, 5}; // 获取 vector 的大小 size_t vectorSize = myVector.size(); // 打印 vector 的大小 std::cout << "Vector size: " << vectorSize << std::endl; return 0; }
Copy after login

Output:

Vector size: 5
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!