Home > Enterprise >  Map of set of custom objects c
Map of set of custom objects c

Time:05-20

So I have a map that has user defined keys and the values in it are sets of objects too. So I'm trying to write some print function but I have no idea how to do that. (I'm kind of new to maps and sets). My problem function:

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

Here's my class:

#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 << "\n\n";
            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;
    }
};

}

So the problem is that I am getting an error "no operator "[]" match these operands". How can I output my map and set in the best way?

CodePudding user response:

The problem is that we cannot use indexing on a std::set. Thus itr.second[i] is not valid because itr.second is an std::set.

To solve this you can use a range-based for loop as shown below:

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