Home > database >  How to store unordered_set to a vector?
How to store unordered_set to a vector?

Time:01-01

I want to use a vector to store several unordered_set.

Here is my test codes:

#include <unordered_set>
#include <vector>
using namespace std;

int main(){
    vector<unordered_set<int>> v1;
    unordered_set<int> s1 = {1,2}, s2 = {3,2};
    v1[0] = s1;
    v1[1] = s2;
    for (auto &s : v1[0]) {
        cout << s << " ";
    }
}

And I get Segmentation fault (core dumped) .

My question is: How should I modify my codes?

CodePudding user response:

The problem with your code is that your vectors does not have elements 0 and 1. Either initialize the vector with required number of elements, or insert the elements into an empty vector as below:

int main(){
        vector<unordered_set<int>> v1;
        unordered_set<int> s1 = {1,2}, s2 = {3,2};
        v1.push_back(s1);
        v1.push_back(s2);
        for (auto &s : v1[0]) {
            cout << s << " ";
        }
    }
  • Related