根据所给列表判断ip的归属地
如所给字符串列表为 :
"127.0.0.1 127.0.0.11 山东 潍坊",
"127.0.0.12 127.0.1.4 山东 11",
"128.0.1.1 128.0.3.11 山东 12"
测试ip为127.0.0.9,则应返回其归属地。
示例代码如下:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class ip {
private:
vector<int> duan;
public:
ip(string s);
bool operator >(const ip& ip1) const;
bool operator <(const ip& ip1) const;
};
inline bool isIn(vector<string> temp, string test) {
string s1 = temp[0];
string s2 = temp[1];
ip ip1(s1);
ip ip2(s2);
ip ip3(test);
if (ip3 > ip1 && ip3 < ip2) {
return true;
}
return false;
}
int main() {
vector<string> slist = {
"127.0.0.1 127.0.0.11 山东 潍坊",
"127.0.0.12 127.0.1.4 山东 11",
"128.0.1.1 128.0.3.11 山东 12"
};
string test = "127.0.1.2";
for (string temp: slist) {
int count = 0;
int j = 0;
int left = 0;
vector<string> rand;
while (j < temp.length()&&count<2) {
if (temp[j] == ' ') {
rand.push_back(temp.substr(left, j-left));
count++;
left = j + 1;
}
j++;
}
if (isIn(rand, test)) {
cout << temp.substr(left) << endl;
}
}
return 0;
}
ip::ip(string s)
{
this->duan.clear();
int j = 0;
int left = 0;
while (j < s.length()) {
if (s[j] == '.') {
this->duan.push_back(stoi(s.substr(left, j - left)));
left = j+1;
}
j++;
}
this->duan.push_back(stoi(s.substr(left)));
}
bool ip::operator>(const ip& ip1) const
{
for (int i = 0; i < this->duan.size(); i++) {
if (this->duan[i]>ip1.duan[i]) {
return true;
}
else if (this->duan[i] < ip1.duan[i]) {
return false;
}
}
return false;
}
bool ip::operator<(const ip& ip1) const
{
for (int i = 0; i < this->duan.size(); i++) {
if(this->duan[i] <ip1.duan[i]){
return true;
}
else if (this->duan[i] >ip1.duan[i]) {
return false;
}
}
return false;
}
如有建议,请在评论区指正。