我正在学习C++STL的一些技巧,我写了一个基本的地图插入/删除代码。
下面是代码。 它从用户那里获取一些输入,并相应地插入/删除。 非常简单的代码。
但问题是我必须为每个映射变体编写单独的打印函数。
我能做些什么来使它像我们在模板中做的那样通用吗?
如有任何帮助,我们将不胜感激。
#include <iostream>
#include <map>
#include <unordered_map>
using namespace std;
void print(const map<int, string>& mp)
{
cout << "Contents of map: { ";
for(auto& it: mp)
{
cout << it.first << " -> " << it.second << " ";
}
cout << "}" << endl;
}
void print(const multimap<int, string>& mp)
{
cout << "Contents of multi map: { ";
for(auto& it: mp)
{
cout << it.first << " -> " << it.second << " ";
}
cout << "}" << endl;
}
void print(const unordered_map<int, string>& mp)
{
cout << "Contents of unordered map: { ";
for(auto& it: mp)
{
cout << it.first << " -> " << it.second << " ";
}
cout << "}" << endl;
}
void print(const unordered_multimap<int, string>& mp)
{
cout << "Contents of unordered multi map: { ";
for(auto& it: mp)
{
cout << it.first << " -> " << it.second << " ";
}
cout << "}" << endl;
}
int main()
{
map<int, string> mp1;
multimap<int, string> mp2;
unordered_map<int, string> mp3;
unordered_multimap<int, string> mp4;
int value = 0;
string str;
cout << "Inserting..." << endl;
while(value >= 0)
{
cout << "Enter number: ";
cin >> value;
if(value >= 0)
{
cout << "Enter string: ";
cin >> str;
mp1.insert(pair<int, string>(value, str));
mp2.insert(pair<int, string>(value, str));
mp3.insert(pair<int, string>(value, str));
mp4.insert(pair<int, string>(value, str));
}
}
print(mp1);
print(mp2);
print(mp3);
print(mp4);
value = 0;
cout << "Removing..." << endl;
while(value >= 0)
{
cout << "Enter number: ";
cin >> value;
if(value >= 0)
{
// removing by value
mp1.erase(value);
mp2.erase(value);
mp3.erase(value);
mp4.erase(value);
}
}
print(mp1);
print(mp2);
print(mp3);
print(mp4);
return 0;
}
嗯,对,就是确实,模板是用来做什么的,对吧?
template<typename T>
void print(const T& mp)
{
cout << "Contents of map: { ";
for(auto& it: mp)
{
cout << it.first << " -> " << it.second << " ";
}
cout << "}" << endl;
}
只要只将映射或其合理的传真传递给print()
(并且映射中的键和值都有一个工作的<<<
重载),就可以工作。 否则,可能需要使用SFINAE或C++20概念来约束重载解析。