给定以下代码:
map<int,multiset<string>,greater<int>> m;
int n;
cin>>n;
for(int i=0;i<n;i++){
string s;
int x;
cin>>s>>x;
m[x].insert(s);
}
for(auto &it:m){
cout<<it.second<<" "<<it.first<<endl;
}
谁能给我解释一下为什么我在中得到一个错误。部分?错误是:no operator "<<" matches these operands
.
second"std::map
的一部分是std::multiset
。这
- 没有重载插入操作符
<<
- ,可以包含多个元素
<<
如何处理multiset?
您需要做的是添加第二个循环,输出std::multiset
的值。
类似:
#include <iostream>
#include <map>
#include <set>
int main() {
std::map<int, std::multiset<std::string>, std::greater<int>> m;
int n;
std::cin >> n;
for (int i = 0; i < n; i++) {
std::string s;
int x;
std::cin >> s >> x;
m[x].insert(s);
}
for (auto& it : m) {
for (auto& sec : it.second)
std::cout << sec << " " << it.first << 'n';
std::cout << "nn";
}
}
但这也没有多大意义,因为,如前所述,std::multiset
可以包含多个值。
并且你总是只赋一个值,因此,给map的一个键赋一个有值的multiset。您可以在示例中提交完整的std::multiset
。
但也许你以后会签署更多的值。那么我的代码片段就有意义了。
it.second
是传递给std::cout
的multiset<string...>
。正如消息所说,没有为该类型定义operator<<
,这就是得到错误消息的原因。std::cout
需要这个运算符才能输出给定的东西。它只预定义了std::string
,基本类型(int, float,…)和其他一些基本类,但不是std::multiset
。
它不是预定义的,因为每个拥有这样一个multiset的人可能会做不同的事情,例如operator<<
应该如何处理它可以包含的多个元素(用空格,逗号,…分隔它们)。在下面的代码中,我们根本没有将它们分开,因为无论如何那里只有一个元素。
您需要为该类型重载operator<<
,例如:
#include <iostream>
#include <map>
#include <set>
template <class T, class U>
std::ostream& operator<<(std::ostream& out, std::multiset<T, U>& c)
{
for (auto e: c)
{
out << e;
}
return out;
}
int main()
{
std::map<int,std::multiset<std::string>, std::greater<int>> m;
int n;
std::cin>>n;
for(int i=0;i<n;i++){
std::string s;
int x;
std::cin>>s>>x;
m[x].insert(s);
}
for(auto it: m){
std::cout<<it.second<<" "<<it.first<<std::endl;
}
}