c plus plus实现ip地址排序
时间: 2023-05-12 14:04:35 浏览: 70
可以使用STL中的sort函数来实现IP地址排序。首先将IP地址转换为整数,然后使用sort函数进行排序,最后再将整数转换回IP地址即可。
以下是示例代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
// 将IP地址转换为整数
unsigned int ipToInt(string ip) {
unsigned int num = 0;
stringstream ss(ip);
string segment;
while (getline(ss, segment, '.')) {
num = num * 256 + stoi(segment);
}
return num;
}
// 将整数转换为IP地址
string intToIp(unsigned int num) {
string ip;
for (int i = 0; i < 4; i++) {
int segment = (num >> (8 * (3 - i))) & 0xFF;
ip += to_string(segment);
if (i < 3) {
ip += ".";
}
}
return ip;
}
int main() {
vector<string> ips = {"192.168.1.1", "10.0.0.2", "172.16.0.3", "192.168.0.4"};
vector<unsigned int> nums;
for (auto ip : ips) {
nums.push_back(ipToInt(ip));
}
sort(nums.begin(), nums.end());
for (auto num : nums) {
cout << intToIp(num) << endl;
}
return 0;
}
```
输出结果为:
```
10.0.0.2
172.16.0.3
192.168.0.4
192.168.1.1
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)