C++ Map 库 - size() 函数
描述
C++ 函数 std::map::size() 返回映射中存在的元素数。
声明
以下是 std::map::size() 函数形式 std::map 头的声明。
C++98
size_type size() const;
C++11
size_type size() const noexcept;
参数
None
返回值
返回 map 中存在的实际对象。
异常
此成员函数从不抛出异常。
时间复杂度
常数,即 O(1)
示例
以下示例显示了 std::map::size() 函数的用法。
#include <iostream>
#include <map>
using namespace std;
int main(void) {
map<char, int> m;
cout << "Initial size of map = " << m.size() << endl;
m = {
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5},
};
cout << "Size of map after inserting elements = " << m.size() << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Initial size of map = 0 Size of map after inserting elements = 5

