如何修复矢量push_back中的"no instance of overloaded function"?
How to fix "no instance of overloaded function" in vector push_back?
我想编写一个函数,该函数将指向指向字符串(字典)的矢量指针和指向字符(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;
,仍然无法弄清楚问题出在哪里。
dictionnary
是std::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()
。
- "error: no matching function for call to"构造函数错误
- 调用专用模板时出错"no matching function for call to [...]"
- C++ Singleton - Prevent ::instance() to variable
- c++20[[no.unique_address]]中的新功能是什么
- 以线程安全的方式调用"QQuickPaintedItem::updateImage(const QImage&image)"(no QThread)
- DrawIndexedInstanced 具有不同的 Index Count per Instance (Directx
- "no matching function for call to 'Vector::Vector'"错误
- Android NDK clang 编译器错误在 Windows 上显示'No such file or directory'
- 处理"no operator found"
- 我在 ifstream input_file(文件名)行中收到错误"no matching function to call";
- 如何解决"no Qt platform plugin could be initialized"问题?
- cin.get() 导致"no instance of overloaded function"错误
- 尝试在虚幻引擎中通过C++添加视口时出错"No instance of overloaded function CreateWidget"
- 3D 矢量 - "No instance of overload function?"
- 不能使用矢量::插入"no instance of overloaded function..."
- 矩阵类:"No instance of overloaded function push_back matches the argument list"
- 如何修复矢量push_back中的"no instance of overloaded function"?
- "No instance of overload function"
- C++向量和错误"no instance of overloaded function"
- 如何修复 cin.getline 的"No instance of overloaded function"错误?