- 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;
}
}
推薦閱讀
- Git Version Control Cookbook
- Java程序設計實戰教程
- 小創客玩轉圖形化編程
- HTML5 移動Web開發從入門到精通(微課精編版)
- Neo4j Essentials
- PostgreSQL Replication(Second Edition)
- SharePoint Development with the SharePoint Framework
- 區塊鏈底層設計Java實戰
- Python 3.7從入門到精通(視頻教學版)
- Buildbox 2.x Game Development
- Oracle數據庫編程經典300例
- Clojure High Performance Programming(Second Edition)
- MySQL數據庫應用實戰教程(慕課版)
- Java多線程并發體系實戰(微課視頻版)
- R語言實戰(第2版)