Ayush Pandey
Ayush Pandey

Reputation: 587

Deleting a vector in vector of vectors C++

I have created and adjacency list which consist of 200 vertices , each vector correspond to row numbered i has all the vertices which share an edge with i. I want to delete 198 random vectors from the adjacency list. But i am getting an segmentation fault error

    void contract_edge(vector<vector<int> >&adjacency_list , int pos)
    {
        adjacency_list.erase(adjacency_list.begin()+pos);
    }
    int main()
    {
        vector<vector<int> > adjacency_list(200);
        int size = 200;
        while(size > 2)
        {
            int random = rand()%200;
            contract_edge(adjacency_list,random);
            size--;
        }
        return 0;
    }

I wanted to know which is a good way to delete vector from vector of vectors.

Upvotes: 0

Views: 2050

Answers (1)

Ap31
Ap31

Reputation: 3314

Segmentation failure comes from the fact that you keep picking random numbers from 0 to 199, but the size of the adjacency_list vector is rapidly decreasing, so it's only a matter of time when you pick an out-of-bounds value of random.

The solution would of course be to pick random from 0 to adjacency_list.size()-1, but I suggest just randomly picking 2 rows to keep instead, copying them, and then throwing away the whole adjacency_list, as std::vector is not too good with those random repetative removals.

Upvotes: 1

Related Questions