nasser
nasser

Reputation: 19

Remove element of array of list type in c++

I have the following code and I got an error during the run time, saying that iterator in not incremental. I want to remove the list items inside an array.

#include <algorithm>
#include <array>
#include <list>

using namespace std;

struct pckt
{
    float gen_time;
    int node_id;
    bool last; 
    float end_time;
    int seq;
};

int main() {
    array<list<pckt>, 50> nodelist;
    array<list<pckt>, 25> APlist;

    list<pckt>::iteratot it1; 

    for(int i=0; i < 25; ++i) {
        it1= APlist[i].begin();

        while (it1 !=APlist[i].end()) {
            APlist[i].erase (it1);
            it1++;

        }
    }
}

Upvotes: 0

Views: 183

Answers (3)

juanchopanza
juanchopanza

Reputation: 227370

Remove element of array of list type in c++

You cannot remove elements from arrays. They have a fixed size, so all you can do is modify the elements they contain.

However, looking at your code it looks like you want to remove all the elements of each of the std::lists container in an std::array<std::list,N>. To achieve this, you can simply iterate over the list and call std::list::clear() on each element. Make sure not to leave any hard-wired numbers lying around: like all containers, an std::array knows how many elements it holds:

for (auto& l : APlist)
  l.clear()

Upvotes: 1

egur
egur

Reputation: 7960

This will be fastest:

for(int i=0; i < 25; ++i) {
    APlist[i].clear();
}

With iterators:

for(int i=0; i < 25; ++i) {
    it1 = APlist[i].begin();

    while (it1 != APlist[i].end()) {
        APlist[i].erase (it1);
        it1 = APlist[i].begin();
    }
}

Upvotes: 0

TieDad
TieDad

Reputation: 9889

Use the following code to erase all elements from the list:

APlist[i].erase(APlist[i].begin(), APlist[i].end());

Upvotes: 0

Related Questions