0

Hi

I am developing a program that uses Breadth First Search to map a grid(2d array) out. Breadth First Search involves storing nodes in a stack and then exploring these nodes based on Breadth or level. I know how to create a vector array which I shall use as a stack. I need to know how to store array elements in the stack using the

push_back()

method. This is what I have so far..

vector<int>stack; //stack initialization.
stack.push_back(array[1][1]) //store array element itself, not Value held in array!

The value stored is not the array element, but the value which happens to be some integer x.

Thanks for helping.

3
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by aravind rao
1

if you want to store the address of that element in you vector than you can do

vector<int*> stack
stack.push_back(&(array[1][1]))

if you are trying to store the value of x and y values you can use a 2d vector like

vector< vector<int> > stack
vector<int> temp;
if (array[x][y] == something)
{
    temp.push_back(x);
    temp.push_back(y);
    stack.push_back(temp);
    temp.clear();
}

although this might not be the best way to do it.

Votes + Comments
Great helpful post
0

Why would you want to simulate a stack for a vector if there is already an implemented stack?!

#include <stack>
#include <iostream>
int main()
{
 std::stack<int>  st;
 st.push(1);
 st.push(3);
 std::cout << st.top() << std::endl; // outputs 3;
 st.pop();
 std::cout << st.top() << std::endl; //outputs1
}
0

Why would you want to simulate a stack for a vector if there is already an implemented stack?!

#include <stack>
#include <iostream>
int main()
{
 std::stack<int>  st;
 st.push(1);
 st.push(3);
 std::cout << st.top() << std::endl; // outputs 3;
 st.pop();
 std::cout << st.top() << std::endl; //outputs1
}

Well I looked into it, but for a Breadth First Search I need a FIFO(First In First Out) type stack. The one above is LIFO. So unless there is actually a FIFO stack, which I think only exists in a queue, I wont be using any stacks.

Thanks for replying.

0

if you want to store the address of that element in you vector than you can do

vector<int*> stack
stack.push_back(&(array[1][1]))

if you are trying to store the value of x and y values you can use a 2d vector like

vector< vector<int> > stack
vector<int> temp;
if (array[x][y] == something)
{
    temp.push_back(x);
    temp.push_back(y);
    stack.push_back(temp);
    temp.clear();
}

although this might not be the best way to do it.

Great post, both methods worked, although the pointer method is more efficient. I knew pointers were the answer, thanks for showing me how!

Thanks for replying.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.