How to insert elements in 2-D list like vector?

153 Views Asked by At

So, i have this code here...i tried 2D list and searched for how to insert in 2d list and found nothing.

vector<int> dynamicArray(int n, vector<vector<int>> queries) {
vector<int>temp;
list<list<int>>seqList(n);
int lastans=0;
for(int i=0;i<queries.size();i++){
    int x=queries[i][1],y=queries[i][2];
    if(queries[i][0]==1){
        int temp2=(x^lastans)%2;
        seqList[temp2].push_back(y);
    }
    else{
        lastans=seqList[(x^lastans)%2][y];
        temp.push_back(lastans);
    }
}
return temp;
}

Now here if i change list<list>seqList(n); to vector<vector>seqList(n) i get 0 errors and the code works fine

Here's what the error is for using list

error: no match for ‘operator[]’ (operand types are ‘std::__cxx11::list<std::__cxx11::list<int> >’ and ‘int’)
         seqList[temp2].push_back(y);

so i thought it was the brackets but i am not really sure what the problem is.. i tried using curly brackets and it said:-

warning: statement has no effect [-Wunused-value]
         seqList{temp2}.push_back(y);

Forgive me if i am doing a grave mistake here but,...i couldn't find the solution anywhere and it worked fine with vector

edit:-

I know there is no operator...I want to know how can i insert elements in this 2d list? or is there any other way to insert in 2d list.

1

There are 1 best solutions below

4
463035818_is_not_an_ai On

A std::list is not a std::vector. That should not be a big surprise.

If you read documentation for std::list (for example here), you can find that std::list has no operator[].

To insert into a list you can use std::list::insert.

Note that also if seqList is a std::vector<std::vector<int>> then operator[] is not inserting elements. You have

std::vector<std::vector<int>> seqList(n); // outer vector has n element
seqList[temp2].push_back(y);
      // access element at index temp2 in outer vector
              // push an element to that element