判断ip归属地 c++

根据所给列表判断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;
}

如有建议,请在评论区指正。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值