How to write unordered set of vector of vector, namely unordered_set<vector<vector<int>> set?

Viewed 465

I wanna have a set to store several graphs, and each graph has several dots, and each dot has its own coordinate. So here is my code:

unordered_set<vector<vector<int>> set;
vector<vector<int>> graph;
graph.push_back({1,1});
graph.push_back({2,2});
set.insert(graph);

Then the failure shows that set expect two arguments, but one provided. I know for this problem, it's better to build a data structure to store dots, and graphs. But I just wanna know why this cannot be achieved by a set?

2 Answers

I would declare class or struct named: Point that contain two int variables and push every point to the graph (that now need to be vector<Point>) and then push the graph to your set (you can also declare class or struct named: Graph that contain vector) and then your code should be :

unordered_set<Graph> set;
Graph graph;
graph.push_back(Point(1,1));
graph.push_back(Point(2,2));
set.insert(graph);

In addition, I don't think you need to use unorderd_set, I think set is enough and in this case, your code will be(without the classes):

std::set < std::vector<std::vector<int>>> set;
std::vector<std::vector<int>> graph;
graph.push_back({ 1, 1 });
graph.push_back({ 1, 1 });
set.insert(graph);

if you still want to use unorderd_ser I would look here (you need to give unordered_set a hash function.): https://docs.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2280?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev16.query%3FappId%3DDev16IDEF1%26l%3DEN-US%26k%3Dk(C2280)%26rd%3Dtrue&view=vs-2019

they say that this is a deleted function, so this use of unorderd_set is iliglle check this link and get your answer for unorderd_set, I still offer you to use a regular set

hope I answered your question:)

Just to kindle your interest:

Live On Coliru

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>
#include <iostream>

int main() {
    using Graph = boost::adjacency_list<>;
    std::list<Graph> set;

    Graph graph(3);
    add_edge(1, 1, graph);
    add_edge(2, 2, graph);

    set.push_back(graph);

    for (auto& g : set) {
        print_graph(g);
    }
}

Prints

0 --> 
1 --> 1 
2 --> 2 

Using in a Set

Sets mandate that the elements are "unique". So they'll have to know how to compare the elements:

  • std::set needs a weak total order (basically a < b)
  • std::unordered_set needs a hash + equality test (basically std::hash<Graph>(a) and a == b)

It would, however be uncommon for the unique-ness to actually matter. Do you instead want to look at graph iso-morphisms? What problem are you trying to solve?

Related