如何修复矢量push_back中的"no instance of overloaded function"?

How to fix "no instance of overloaded function" in vector push_back?

本文关键字:instance no of overloaded function 中的 何修复 push back      更新时间:2023-10-16

我想编写一个函数,该函数将指向指向字符串(字典)的矢量指针和指向字符(p)的指针作为输入。该函数将检查字符是否在字典中,如果不存在,它将在向量字典中添加 p。

我的代码:

#include <iostream>
#include <string>
#include <vector>
using std::string;
using std::vector;
std::vector<string *> dictionary;
void manageDictionary(vector<string *> * dictionary, char *p) {
for (unsigned int i = 0; i < (*dictionary).size(); i++) {
string * pstring = (*dictionary).at(i);
if ((*pstring).compare(p)) {
(*dictionary).push_back(p);
}
}
}

但是,Visual Studio 编译器显示我在 push_back 方法(.)之前的 if 语句中有一个错误。当我将鼠标悬停在错误上时,它说"没有重载函数的实例"。

我在开头添加了std::vector<string *> dictionary;,仍然无法弄清楚问题出在哪里。

dictionnarystd::string*的向量。std::string*char*是完全不相关的类型。若要从char*转换为std::string*,需要为字典创建一个包含p值的新string,而不是直接传递char*。此更改将允许编译示例,但生成的函数容易出错。

#include <string>
#include <vector>
using std::string;
using std::vector;
void manageDictionnary(vector<string *> * dictionnary, char *p) {
for (unsigned int i = 0; i < (*dictionnary).size(); i++) {
string * pstring = (*dictionnary).at(i);
if ((*pstring).compare(p)) {
(*dictionnary).push_back(new string(p));
// Make a new string     ^^^^^^^^^^
}
}
}

此解决方案将要求您手动删除字符串,这不是 c++ 中完成操作的方式。从std::vector<std::string*>改为简单的std::vector<std::string>将解决这个问题,并避免您将来头疼。还有其他不必要的指针可以删除。由于at(i)返回一个string&那么我们应该将pstring更改为string&。由于dictionnary不是可选的(不能nullptr),并且始终指向相同的vector因此我们也可以将其更改为vector<string>&.

void manageDictionnary(vector<string> & dictionnary, char *p) {
for (unsigned int i = 0; i < dictionnary.size(); i++) {
string & pstring = dictionnary.at(i);
if (pstring.compare(p)) {
dictionnary.push_back(p);
}
}
}

这个最新版本可以正常工作,并且更符合 c++ 的资源管理理念。我建议您阅读几个主题:

  • 标准算法,如std::find.
  • 基于范围的 for 循环。
  • 恒常正确性。
  • 指针与引用。

此外,请考虑使用std::set<string>std::unordered_set<string>来更方便地表示字典。

将来,请注意,访问指针方法的首选方法是ptr->foo()而不是(*ptr).foo()