酷代码 AI
菜单
服务商

C++ 一招搞定:从 100 万个 IP 中找出最多的 100 个!附哈希表解决方案

这个问题可以通过使用哈希表或者优先队列来解决。以下是一个使用哈希表的解决方案: ```cpp #include <iostream> #include <unordered_map> #include <vector> #include <algorithm> std::vector<std::pair<int, std::string>> getTop100(const std::vector<std::string>& ips) { std::unordered_map<std::string, int> count; for (const auto& ip : ips) { count[ip]++; } std::vector<std::pair<int, std::string>> result; for (const auto& pair : count) { result.push_back(pair); } std::sort(result.begin(), result.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); result.resize(100); return result; } int main() { std::vector<std::string> ips = {"192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4", ..., "192.168.1.1000000"}; std::vector<std::pair<int, std::string>> top100 = getTop100(ips); for (const auto& pair : top100) { std::cout << pair.second << ": " << pair.first << std::endl; } return 0; } ``` 这个程序首先遍历所有的IP地址,将它们的出现次数存储在一个哈希表中。然后,它将哈希表中的所有元素添加到一个向量中,并按照出现次数进行排序。它只保留前100个元素。 注意,这个程序假设IP地址的格式是"xxx.xxx.xxx.xxx",并且所有的IP地址都是有效的。如果IP地址的格式不正确,或者有无效的IP地址,那么这个程序可能会出错。 ######[AI写代码神器 | 435点数解答 | 2023-11-09 00:44:19]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]