尝试比较字符串
Trying to compare strings
我正在尝试将两个字符串与存储在map<string,IPHost> Address_list
中的IP地址进行比较。我是C++新手,我认为我在头文件和实现文件方面做错了。这就是我到目前为止写的。当我编译它时,它说:
error: no matching function for call to 'IPHost::IPHost()`
有人可以指导我如何解决它吗?
这是我的头文件:
#ifndef IPHOST_H
#define IPHOST_H
#include <iostream>
class IPHost
{
public:
IPHost(int ip0, int ip1, int ip2, int ip3);
bool checkIP(const IPHost&) const;
private:
int one;
int two;
int three;
int four;
};
#endif
这是我的实现文件:
#include "IPHost.h"
#include <iostream>
#include <string>
using namespace std;
IPHost::IPHost(int ip0, int ip1, int ip2, int ip3 )
{
ip0=one;
ip1=two;
ip2=three;
ip3=four;
}
bool IPHost::checkIP(const IPHost& h)const
{
if(one == h.one && two == h.two && three == h.three && four == h.four)
{
return true;
}
else
{
return false;
}
}
我的主要功能:
#include <iostream>
#include <string>
#include <map>
#include "IPHost.h"
using namespace std;
int main
{
map<string, IPHost> Address_list;
Address_list["google.com"]=IPHost(74,125,225,20);
Address_list["m.twitter.com"]=IPHost(199,16,156,43);
if (Address_list["google.com"].checkIP(Address_list["m.twitter.com"]))
{
cout << "Two IP address are the same.n";
}
else
{
cout << "Two IP address do not match.n";
}
return 0;
}
当你这样说时:
Address_list["google.com"]=IPHost(74,125,225,20);
std::map::operator[]
默认构造一个IPHost
对象,然后通过引用返回该对象,然后复制分配一个临时IPHost
给这个对象。 编译器抱怨IPHost
因为它没有默认构造函数,因此无法实例化std::map::operator[]
方法实现。
(这是必需的,因为语法不允许std::map
知道您尝试分配的值;它只知道您想要访问可能不存在的键"google.com"
,因此它需要创建一个IPHost
对象,以便您可以为其分配值。 默认构造是唯一明智的选择。
使用此语法,则需要为 IPHost
提供默认构造函数:
public: IPHost();
// Later...
IPHost::IPHost() : one(0), two(0), three(0), four(0) { }
或者,您可以改用std::map::insert
,这不需要值类型是默认可构造的,因为您直接提供IPHost
对象用作值。
Address_list.insert(std::pair<std::string const, IPHost>(
"google.com", IPHost(74,125,225,20)));
如果您有权访问 C++11,则可以通过使用 std::map::emplace
使此操作更高效、更不冗长
Address_list.emplace("google.com", IPHost(74,125,225,20));
请注意,如果已找到键,insert
和 emplace
不会替换该值! 如果需要,您应该检查 insert
或 emplace
调用的返回值,该值包含映射中元素的迭代器和指示它是否确实创建了该项的布尔值。 这样,它们在影响地图内容方面与a[b] = c
语法并不完全相同。
如果您经常发现自己试图在映射中设置值而不考虑键是否已存在,我强烈建议您向IPHost
添加一个默认构造函数,因为它将使更简单的a[b] = c
语法成为可能,并防止您不得不编写更复杂的 if-item-已经存在-then-update-it-instead 情况。
- 为什么字符串比较的 == 运算符相对于任一字符串长度线性时间(似乎)?
- 字符串比较中的意外输出
- 如何执行不区分大小写的字符串比较?
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- <<运算符优先级与字符串比较
- ">"运算符和"<"运算符如何进行字符串比较?
- Qt C++11 字符串通过子字符串比较列出交集
- std::out_of_range字符串比较中的异常
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 字符* 与uint8_t的字符串比较
- 用字符串 c++ 比较对向量的元素
- 使用循环进行词典字符串比较
- 如何为C++映射创建自己的字符串比较对象
- 不带比较()的字符串比较
- 与 IF 语句C++的字符串比较?
- 字符串比较在与变量一起使用时给出不同的输出
- 更快的字符串比较排序,用于唯一()
- C 字符串比较“祝您好运”&gt;“再见”
- C 奇怪的行为和字符串比较
- 子字符串与 std::memcmp 或字符串::比较的比较