写得很烂(不是谦虚),你参考一下吧
程序代码:
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;
struct iprange
{
unsigned long ip1, ip2;
string province;
explicit iprange( unsigned long ip1_=0, unsigned long ip2_=0, string prvc="" ) : ip1(ip1_), ip2(ip2_), province(prvc)
{
}
};
inline bool iprange_sortcomp( const iprange& a, const iprange& b )
{
return a.ip1 < b.ip1;
}
istream& operator>>( istream& is, iprange& ipr )
{
unsigned long a,b,c,d, e,f,g,h;
char ap,bp,cp, ep,fp,gp;
string province;
is >> a >> ap >> b >> bp >> c >> cp >> d
>> e >> ep >> f >> fp >> g >> gp >> h >> province;
if( is
&& a<256 && ap=='.'&& b<256 && bp=='.' && c<256 && cp=='.' && d<256
&& e<256 && ep=='.'&& f<256 && fp=='.' && g<256 && gp=='.' && h<256 )
{
ipr.ip1 = a<<24 | b<<16 | c<<8 | d;
ipr.ip2 = e<<24 | f<<16 | g<<8 | h;
ipr.province = province;
}
return is;
}
int main()
{
ifstream fa( "a.txt" );
ifstream fb( "b.txt" );
if( !fa || !fb )
return 1;
vector<iprange> iprs( (std::istream_iterator<iprange>(fb)), std::istream_iterator<iprange>() );
sort( iprs.begin(), iprs.end(), &iprange_sortcomp );
while( fa )
{
string id;
unsigned long a,b,c,d;
char ap,bp,cp;
fa >> id >> a >> ap >> b >> bp >> c >> cp >> d;
if( !fa || a>255 || ap!='.' || b>255 || bp!='.' || c>255 || cp!='.' || d>255 )
break;
unsigned long ip = a<<24 | b<<16 | c<<8 | d;
cout << id << '\t'
<< a << '.' << b << '.' << c << '.' << d << '\t';
if( ip>=iprs.back().ip1 && ip<=iprs.back().ip2 )
{
cout << iprs.back().province << '\n';
}
else
{
vector<iprange>::const_iterator itor = upper_bound( iprs.begin(), iprs.end(), iprange(ip), &iprange_sortcomp );
if( itor!=iprs.begin() && itor!=iprs.end() && itor->ip2>=ip )
cout << (--itor)->province << '\n';
else
cout << "???" << '\n';
}
}
return 0;
}