- The Modern C++ Challenge
- Marius Bancila
- 187字
- 2021-06-25 22:01:27
16. Enumerating IPv4 addresses in a range
To be able to enumerate IPv4 addresses in a given range, it should first be possible to compare IPv4 values. Therefore, we should implement at least operator<, but the following listing contains implementation for all comparison operators: ==, !=, <, >, <=, and >=. Also, in order to increment an IPv4 value, implementations for both the prefix and postfix operator++ are provided. The following code is an extension of the IPv4 class from the previous problem:
ipv4& operator++()
{
*this = ipv4(1 + to_ulong());
return *this;
}
ipv4& operator++(int)
{
ipv4 result(*this);
++(*this);
return *this;
}
friend bool operator==(ipv4 const & a1, ipv4 const & a2) noexcept
{
return a1.data == a2.data;
}
friend bool operator!=(ipv4 const & a1, ipv4 const & a2) noexcept
{
return !(a1 == a2);
}
friend bool operator<(ipv4 const & a1, ipv4 const & a2) noexcept
{
return a1.to_ulong() < a2.to_ulong();
}
friend bool operator>(ipv4 const & a1, ipv4 const & a2) noexcept
{
return a2 < a1;
}
friend bool operator<=(ipv4 const & a1, ipv4 const & a2) noexcept
{
return !(a1 > a2);
}
friend bool operator>=(ipv4 const & a1, ipv4 const & a2) noexcept
{
return !(a1 < a2);
}
With these changes to the ipv4 class from the previous problem, we can write the following program:
int main()
{
std::cout << "input range: ";
ipv4 a1, a2;
std::cin >> a1 >> a2;
if (a2 > a1)
{
for (ipv4 a = a1; a <= a2; a++)
{
std::cout << a << std::endl;
}
}
else
{
std::cerr << "invalid range!" << std::endl;
}
}
推薦閱讀
- .NET之美:.NET關(guān)鍵技術(shù)深入解析
- Mastering Adobe Captivate 2017(Fourth Edition)
- Java入門(mén)很輕松(微課超值版)
- Selenium Design Patterns and Best Practices
- Java從入門(mén)到精通(第4版)
- Visual C++數(shù)字圖像處理技術(shù)詳解
- Learning Python Design Patterns
- 3ds Max印象 電視欄目包裝動(dòng)畫(huà)與特效制作
- uni-app跨平臺(tái)開(kāi)發(fā)與應(yīng)用從入門(mén)到實(shí)踐
- 深度探索Go語(yǔ)言:對(duì)象模型與runtime的原理特性及應(yīng)用
- Backbone.js Testing
- ArcGIS Blueprints
- Learning Predictive Analytics with R
- Instant Highcharts
- 數(shù)據(jù)結(jié)構(gòu)案例教程:C語(yǔ)言版