1

I'm trying to make a list of stacks in C++ using the code below , but I'm getting the error

main.cpp:17:13: error: ‘__gnu_cxx::__alloc_traits > >::value_type {aka class std::stack}’ has no member named ‘push_back’
 vs[i-1].push_back(s);

Code:

#include <bits/stdc++.h>
using namespace std;

int main()
{
vector<stack<int>> vs;

for(int i=1; i<4; i++)
{
stack<int> s;
s.push(i*2);
s.push(i*3);
s.push(i*4);
vs[i-1].push_back(s);
}

return 0;
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • By doing ```vs[i-1]``` you are indexing the vector that stores stacks. Stacks don't have ```push_back()```. –  Sep 23 '20 at 04:45
  • Please [don't include ``](https://stackoverflow.com/Questions/31816095/Why-Should-I-Not-Include-Bits-Stdc-H.). And please learn how to *indent* your code to make it easier to read. – Some programmer dude Sep 23 '20 at 04:50

3 Answers3

1

you can't use this line:-

vs[i-1].push_back(s);

Either define the size of the list earlier. For Eg

vector<stack<int> > vs(100);

else only write

vs.push_back(s);

Updated Solution

#include <iostream>
#include<stack>
#include<vector>
using namespace std;
 
int main()
{
    vector< stack<int> > vs;
 
for(int i=1; i<4; i++)
{
    stack<int> s;
    s.push(i*2);
    s.push(i*3);
    s.push(i*4);
    vs.push_back(s);
}
 
return 0;
}
Dhruv Kothari
  • 103
  • 2
  • 7
1

First of all, your vector is empty, any indexing in it will be out of bounds and lead to undefined behavior.

Secondly, vs[any_valid_index] is a stack and not a vector.

What you probably want is

vs.push_back(s);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Its not a fact for only vector of stacks. It is actually basic property of vector. You have two options to add value into vector.

  1. If you don't declare size of vector (what you did) like

     vector<stack<int>> vs;
     stack<int>s;
    

Then you can insert by using vs.push_back(s) It will automatically handle the index.

  1. Another way is you can declare the size of the vector first. like

    vector<stack<int>> vs(sz); //size(sz) is defined by user
    stack<int>s;
    

Then you can insert by using vs[index]= s This time you have to manually handle the index.

Hridoy_089
  • 318
  • 3
  • 11