c++中集合自定义对象映射的输出



我有一个映射,它有用户定义的键,其中的值也是对象的集合。所以我试着写一些打印函数,但我不知道怎么做。(我对地图和集合有点陌生)。My problem function:

void print() const 
{
for (auto& itr : my_mmap)
{
std::cout << "Key for this set:" << itr.first << "nn";
for (int i = 0; i< itr.second.size(); i++)
{
std::cout << itr.second[i] << std::endl;
}
}
}

这是我的类:

#include <iostream>
#include <map>
#include <string>
#include <tuple>
#include <utility>
#include <set>
class Enclosing {
private:
class Key {
int m_number;
std::string m_name;
public:
Key(int num, std::string name) :m_number(num), m_name(std::move(name)) {};
bool operator<(const Key& rhs) const {
return std::tie(m_number, m_name) < std::tie(rhs.m_number, rhs.m_name);
}
friend std::ostream& operator<<(std::ostream& os, const Key& k) {
return os << '{' << k.m_number << ',' << k.m_name << '}';
}
};
class Nested {
std::string m_str;
double m_dbl;
bool m_boolean;
public:
Nested(std::string str, double dbl, bool boolean) :m_str(std::move(str)), m_dbl(dbl), m_boolean(boolean) {};
friend std::ostream& operator<<(std::ostream& os, const Nested& n) {
return os << '{' << n.m_str << ',' << n.m_dbl << ',' << n.m_boolean << '}';
}
};
std::multimap<Key, std::set<Nested>> my_mmap;
public:
template <class... Args>
void add_new_object_to_mmap(Args&&... args) {
my_mmap.emplace(std::piecewise_construct, std::forward<Args>(args)...);
}
/*
THAT PROBLEM FUNCTION
*/
void print() const 
{
for (auto& itr : my_mmap)
{
std::cout << "Key for this set:" << itr.first << "nn";
for (int i = 0; i< itr.second.size(); i++)
{
std::cout << itr.second[i] << std::endl;
}
}
}
static Enclosing& get_singleton() {
static Enclosing instance;
return instance;
}
};
}

所以问题是我得到一个错误"没有操作符"[]"匹配这些操作数。我如何以最佳方式输出我的地图和设置?

问题我们不能使用索引std::set上。因此,itr.second[i]是无效的,因为itr.secondstd::set

要解决这个问题,您可以使用基于范围的for循环,如下所示:

for (const auto&elem:itr.second)
{
std::cout << elem << std::endl;
}

相关内容

  • 没有找到相关文章