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.
#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;
size_t
), representing the size of the elements in the container quantity.Practical case
Consider avector
container containing an integer array:
#includeint 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; }
Output:
Vector size: 5
Other STL container size acquisition functions
The following are other common STL container size acquisition functions:
size()
-vector
,list
,stack
-
string
-
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!