std::string_view 的使用

This commit is contained in:
2026-06-29 09:40:55 +08:00
parent ccf7eecc29
commit c25e58ae17
40 changed files with 532 additions and 522 deletions
+10 -9
View File
@@ -3,10 +3,11 @@
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string_view>
bool check_port(long long port) { return port >= 0 && port <= 65535; }
bool check_ipv4(const std::string &ip) {
std::istringstream ss(ip);
bool check_ipv4(std::string_view ip) {
std::istringstream ss{std::string(ip)};
std::string segment;
int count = 0;
@@ -53,9 +54,9 @@ bool check_ipv4(const std::string &ip) {
// return count == 4; // IPv4 应该有 4 个段
// }
unsigned int ip_to_int(const std::string &ip) {
unsigned int ip_to_int(std::string_view ip) {
unsigned int result = 0;
std::stringstream ss(ip);
std::stringstream ss{std::string(ip)};
std::string byte;
for (int i = 0; i < 4; ++i) {
std::getline(ss, byte, '.');
@@ -65,8 +66,8 @@ unsigned int ip_to_int(const std::string &ip) {
}
// 判断 IP 地址是否在子网内
bool is_in_subnet(const std::string &ip, const std::string &netmask,
const std::string &gateway) {
bool is_in_subnet(std::string_view ip, std::string_view netmask,
std::string_view gateway) {
unsigned int ipInt = ip_to_int(ip);
unsigned int netmaskInt = ip_to_int(netmask);
unsigned int gatewayInt = ip_to_int(gateway);
@@ -77,8 +78,8 @@ bool is_in_subnet(const std::string &ip, const std::string &netmask,
}
// check 函数,验证 IP、子网掩码和网关
bool check_ip_netmask_gateway(const std::string &ip, const std::string &netmask,
const std::string &gateway) {
bool check_ip_netmask_gateway(std::string_view ip, std::string_view netmask,
std::string_view gateway) {
// 验证 IP 地址、子网掩码和网关是否合法
if (!check_ipv4(ip)) {
std::cerr << "Invalid IP address: " << ip << std::endl;
@@ -166,4 +167,4 @@ TEST(CheckIPv4Test, InvalidIPv4Addresses) {
// }
// }
#endif
#endif