cppman std::vector::size
std::vector::size(3) C++ Programmer's Manual std::vector::size(3)
NAME
std::vector::size - Return size
TYPE
public member function
SYNOPSIS
#include <vector>
C++98
size_type size() const;
size_type size() const noexcept;
DESCRIPTION
Returns the number of elements in the vector.
This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity.
//返回向量中的元素数量。
//这是向量中保存的实际对象的数量,不一定等于它的存储容量。
PARAMETERS
none
RETURN VALUE
The number of elements in the container.
Member type size_type is an unsigned integral type.
//容器中的元素数量。
//成员类型 size_type 是无符号整数类型。
EXAMPLE
// vector::size
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myints;
std::cout << "0. size: " << myints.size() << '\n';
for (int i=0; i<10; i++) myints.push_back(i);
std::cout << "1. size: " << myints.size() << '\n';
myints.insert (myints.end(),10,100);
std::cout << "2. size: " << myints.size() << '\n';
myints.pop_back();
std::cout << "3. size: " << myints.size() << '\n';
return 0;
}
Output:
0. size: 0
1. size: 10
2. size: 20
3. size: 19
COMPLEXITY
Constant.
ITERATOR VALIDITY
No changes.
DATA RACES
The container is accessed.
No contained elements are accessed: concurrently accessing or modifying them is safe.
EXCEPTION SAFETY
No-throw guarantee: this member function never throws exceptions.
SEE ALSO
vector::capacity(3)
Return size of allocated storage capacity (public member function)
vector::resize(3)
Change size (public member function)
vector::max_size(3)
Return maximum size (public member function)
REFERENCE
cplusplus.com, 2000-2015 - All rights reserved.
cplusplus.com 2022-05-13 std::vector::size(3)
(END)
上面文档中的代码示例
#pragma warning(disable : 4996)
#include <iostream>
#include <vector>
int main()
{
std::vector<int> myints;
std::cout << "0. size: " << myints.size() << '\n';
for (int i = 0; i < 10; i++) myints.push_back(i);
std::cout << "1. size: " << myints.size() << '\n';
myints.insert(myints.end(), 10, 100); //向末尾插入10个值为100的元素
std::cout << "2. size: " << myints.size() << '\n';
myints.pop_back();
std::cout << "3. size: " << myints.size() << '\n';
return 0;
}
运行结果:
0. size: 0
1. size: 10
2. size: 20
3. size: 19