fredric
fredric

Reputation: 63

Erase a vector element from list of vectors c++

I have been searching for solution to this problem from this forum and others. The only results i found were about iterating through lists or accessing elements in lists of vectors. So i would like to access erase() function of a vector. But i need it done in a situation where vector is included in a list container. I have a sample code which should help explain.

#include<vector>
#include<list>
#include<iostream>

using namespace std;

int main()
{
    vector <int> a1 = { 1, 1, 1, 1, 1 };
    vector <int> a2 = { 2, 2, 2, 2, 2 };
    vector <int> a3 = { 3, 3, 3, 3, 3 };

    list<vector<int>> listVec;

    listVec.push_back(a1);
    listVec.push_back(a2);
    listVec.push_back(a3);

    for (auto p : listVec){

        for (auto p1 : p){
            cout << p1;
        }
        cout << "\n";
    }


}

So what would be the easiest way to erase one element lets say from vector a2 as it is included in a list. Right now i do not have even the wrong version. The piece of code should be somewhere in the traversing loop but i could not write it.

Thank you

Upvotes: 3

Views: 2879

Answers (2)

PiotrNycz
PiotrNycz

Reputation: 24412

Ok, the standard way to do it:

auto iter = listVec.begin();
std::advance(iter, 1); // get second element
iter->erase(iter->begin() + n); // erase nth element of second element of list

In your for-loop - you need to iterater over reference to elements - not over copies of elements, otherwise you remove element only from copy of vector:

int pos = 0;
for (auto& p : listVec){
//       ^
   if (++pos == 1)
   {
       p.erase(p.begin() + n); // erase nth element of second element of list
   }
}

List of references:


Bonus answer:

For your mentioned in comments question - where you have container Documentand iterator to Document - like Text_iterator - the best is to follow the stl scheme - so add erase function to your Document and make this class friend of Text_iterator, see:

class Text_iterator {   // keep track of line and character position within            a line
    list<Line>::iterator ln;
    Line::iterator pos;
    friend class Document; 

And:

struct Document {
    list<Line> line;            //doucument is a list of lines
    void erase(Text_iterator iter)
    {
        iter.ln->erase(iter.pos);
    }

Upvotes: 3

Chris Dodd
Chris Dodd

Reputation: 126378

The iteration

for (auto p : listVec){

makes a copy of each vector in the list as it iterates through. So while you can call p.erase to erase an element of that vector, that will only affect the copy p and not the vector in the list.

If you instead do

for (auto &p : listVec){

p will now be a reference to each vector in the list. So now if you call p.erase, that will affect the vector in the list.

Upvotes: 1

Related Questions