问题描述:
一组IP地址可能包含有A,B,C,D,E五类地址,请按照IP地址类型输出,相同的Ip地址类型按照IP地址大小排序,按照IP对应整数的大小从小到大排序,错误的IP地址不参与排序
A类IP地址 最高位必须为”0”
B类IP地址 最高位为”10“
C类IP地址 最高位”110“
D类IP地址 最高位为”1110”
E类IP地址 最高位必须为“11110”
错误的IP地址,任意一个IP地址任意一个字节大于255
输入描述:
输入5行。每行均为一个IP地址,IP地址可以是错误,错误的IP地址不参与排序
输出N行,每行输出相同类型的IP地址大小排序,使用“[]”包围所有值,使用,分割
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int stringtoint(string str)
{
int begin = 0;
vector<int> vec;
for (int i = 0; i != str.size(); ++i)
{
if (str[i] == '.')
{
int temp=atoi(str.substr(begin, i).c_str());
if (temp < 0 || temp>255)
return -1;
vec.push_back(atoi(str.substr(begin, i).c_str()));
begin = i + 1;
}
}
int temp = atoi(str.substr(begin, str.size()).c_str());
if (temp < 0 || temp>255)
return -1;
vec.push_back(temp);
int n = (vec[0] << 24) | (vec[1] << 16) | (vec[2] << 8) | vec[3];
return n;
}
string value_to_ip(int& nValue)
{
char strTemp[20];
sprintf_s(strTemp, "%ld.%ld.%ld.%ld",
(nValue & 0xff000000) >> 24,
(nValue & 0x00ff0000) >> 16,
(nValue & 0x0000ff00) >> 8,
(nValue & 0x000000ff));
return string(strTemp);
}
int main()
{
int n = 0;
vector<int> vec;
int x = stringtoint("80.1.1.1");
cout << value_to_ip(x) << endl;
vec.push_back(stringtoint("80.1.1.1"));
vec.push_back(stringtoint("90.1.1.1"));
vec.push_back(stringtoint("180.1.1.1"));
vec.push_back(stringtoint("190.1.1.1"));
vec.push_back(stringtoint("200.1.1.1"));
vector<int> A,B,C,D,E;
for (auto n : vec){
if ((n & 0x80000000) == 0x00000000)
A.push_back(n);
else if ((n & 0xC0000000) == 0x80000000)
B.push_back(n);
else if ((n & 0xE0000000) == 0xC0000000)
C.push_back(n);
else if ((n & 0xF0000000) == 0xD0000000)
D.push_back(n);
else if ((n & 0xF8000000) == 0xF0000000)
E.push_back(n);
}
sort(A.begin(), A.end());
sort(B.begin(), B.end());
sort(C.begin(), C.end());
sort(D.begin(), D.end());
sort(E.begin(), E.end());
if (!A.empty()){
cout << "A:[";
for (auto c : A)
cout << value_to_ip(c) << ",";
cout << "]" << endl;
}
if (!B.empty())
{
cout << "B:[";
for (auto c : B)
cout << value_to_ip(c) << ",";
cout << "]" << endl;
}
if (!C.empty())
{
cout << "C:[";
for (auto c : C)
cout << value_to_ip(c) << ",";
cout << "]" << endl;
}
if (!D.empty())
{
cout << "D:[";
for (auto c : D)
cout << value_to_ip(c) << ",";
cout << "]" << endl;
}
if (!E.empty())
{
cout << "E:[";
for (auto c : E)
cout << value_to_ip(c) << ",";
cout << "]" << endl;
}
return 0;
}