While std::stack
and std::vector
can both be used to store a collection of elements, they are designed for different use cases.
You would choose std::stack
 when:
You would choose std::vector
 when:
back()
 to get the last element.Here's an example showing cases where stack and vector are appropriate:
#include <iostream>
#include <stack>
#include <vector>
int main() {
// Use a stack when LIFO access is needed
std::stack<int> s;
s.push(1);
s.push(2);
s.push(3);
while (!s.empty()) {
std::cout << s.top() << ' '; // prints 3 2 1
s.pop();
}
// Use a vector when random access is needed
std::vector<int> v{1, 2, 3};
std::cout << '\n' << v[1] << '\n'; // prints 2
for (int i : v) {
std::cout << i << ' '; // prints 1 2 3
}
}
3 2 1
2
1 2 3
So in summary - use std::stack
for LIFO access to the top element only, and std::vector
for random access, iteration, or access to the last element. The best choice depends on your specific access and usage requirements.
Answers to questions are automatically generated and may not have been reviewed.
std::stack
An introduction to the stack data structure, and the standard library implementation - std::stack