【发布时间】:2021-08-29 23:41:48
【问题描述】:
尝试从主函数调用我的函数add() 时出现以下错误。
C:\studies\NMB1231_Question5\main.cpp:25:23: 错误:没有匹配函数调用'Dictionary<:vector>, std::vector<:__cxx11::basic_string char> > >::add(int&, std::__cxx11::string&)'
.h 文件
#include <vector>
#include <string>
#include <iostream>
using namespace std;
template <class A,class B>
class Dictionary
{
public:
Dictionary();
void add(A key, const B &value);
B find (A key) const;
void display();
private:
vector<A> keys;
vector<B> values;
};
.cpp
#include "Dictionary.h"
#include <vector>
#include <iostream>
using namespace std;
template <class A,class B>
Dictionary<A,B>::Dictionary()
{
//nothing to do, vector member variables are empty on declaration
};
template <class A,class B>
void Dictionary<A,B>::add(A key, const B &value)
{
keys.push_back(key);
values.push_back(value);
}
template <class A,class B>
B Dictionary<A,B>::find (A key) const
{
B value = " ";
for (unsigned int i = 0; i < keys.size(); i++)
if (key == keys[i])
value = values[i];
if (value == " ")
return "no such key can be found";
else return value;
}
template <class A,class B>
void Dictionary<A,B>::display()
{
for (unsigned int i = 0; i < keys.size(); i++)
cout << keys[i] << ' ' << values[i] << endl;
return;
}
主要
#include <iostream>
#include <cstdlib>
#include "Dictionary.h"
#include <vector>
using namespace std;
int main()
{
Dictionary <vector<int>, vector<string > > part1;
string part;
int key;
//add 4 values to the parts dictionary
for (int i = 0; i <= 3; i++)
{
cout << "Please enter a part name and a key to add to the parts dictionary." << endl;
cout << "Part name: ";
getline(cin, part);
cout << "Key for part name: ";
cin >> key;
part1.add(key,part);
cin.get();
}
cout << endl;
part1.display();
cout << endl;
//find the part for a key
cout << "For which key do you want to find the part? ";
cin >> key;
cout << "The part for key " << key << " is ";
cout << part1.find(key) << endl;
// cout << parts.find(100002);
return 0;
}
【问题讨论】:
-
@Sneftel 重复的问题与此问题中的错误无关。
-
你想要 std::map 而不是 std::vector。