Home > Blockchain >  accessing elements of dynamic array of lists
accessing elements of dynamic array of lists

Time:11-12

So, I don't know how can I print elements of such a list.

list<int>* a;
a = new list<int>(4);
a[0].push_back(1);
a[0].push_back(3);
a[2].push_back(5);
a[2].push_back(7);

cout << a[0].front() << '\n';
cout << a[1].back() << '\n';

Firstly, I tried to print it via range-based for loop, but it didn't work either.

for(auto element: a[0]) cout << element << '\n';    // doesn't work

CodePudding user response:

I would use a std::vector instead of new (which should technically be new[] in this case anyway).

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

int main() {
    std::vector<std::list<int>> a(4);
    a[0].push_back(1);
    a[0].push_back(3);
    a[2].push_back(5);
    a[2].push_back(7);

    for (std::list<int> const& l : a) {
        for (int i : l) { 
            std::cout << i << ' ';
        }
        std::cout << '\n';
    }
}

Output

1 3

5 7
 

CodePudding user response:

Are you trying to store a list of integer lists? Because this implementation will not work since you only have a list of integers and no push_back() operation is available for the elements.

Remove the index operator for all those push_back() operations and take out the index operator for the front() and back() as those are not available to the elements either.

  • Related