C++怎么统计map中key的数量

c++
651
2023/12/22 1:42:08
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

可以使用map的size()函数来统计map中key的数量。size()函数返回的是map中键值对的数量,即key的数量。以下是一个示例代码:

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> myMap;
    myMap[1] = "Apple";
    myMap[2] = "Banana";
    myMap[3] = "Orange";

    int keyCount = myMap.size();
    std::cout << "The number of keys in the map is: " << keyCount << std::endl;

    return 0;
}

输出结果为:

The number of keys in the map is: 3

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++中long的取值范围是什么