How to print a list array (a pointer to a list)

Asked

Viewed 261 times

0

Hello, I would like to know how I can print a pointer to a list, as a vector of lists. I made a pointer pointing to list and do not know how to print these values. I tried using an iterator for each vector position and printing from the beginning to the end of the list, but I could not. It sounds simple, but I’m not able to do it. Does anyone know a way to do it? Follow the code:

#include <cstdlib>
#include <stdlib.h>
#include <stdio.h>
#include <list>
#include<iostream>

using namespace std;

int main(int argc, char** argv) {

    list<int> *adjV;
    list<int>::iterator it;

    adjV[0].push_back(10);
    adjV[0].push_front(20);
    adjV[0].push_back(30);

    adjV[1].push_back(45);
    adjV[1].push_front(55);
    adjV[1].push_back(65);

    adjV[2].push_back(80);
    adjV[2].push_front(90);
    adjV[2].push_back(100);

    for (it = adjV[0].begin(); it != adjV[0].end(); it++)
        cout << *it << endl;

    for (it = adjV[1].begin(); it != adjV[1].end(); it++)
        cout << *it << endl;

    for (it = adjV[2].begin(); it != adjV[2].end(); it++)
        cout << *it << endl;


    return 0;
}

Error Segmentation fault (core dumped) when running.

1 answer

1

List array initialization is missing:

list<int> *adjV = new list<int>[3];

With this initialization you already get the expected result.

However now you can take advantage and turn writing into only 2 for dazzled to simplify and make more flexible:

for(int i = 0; i < 3; ++i) {
    for (list<int>::iterator it = adjV[i].begin(); it!= adjV[i].end(); ++it){
        cout<<*it<<endl;
    }
}

See this solution in Ideone

  • It worked out! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.