Containers in C++
Containers are the backbone of the Standard Template Library (STL) in C++. They provide structures to store and organize data efficiently. This article covers the most commonly used containers: Vector, List, Deque, Stack, Queue, Set, and Map.
1. Vector
A vector is a dynamic array that can grow or shrink in size. It provides fast access to elements and is widely used when the number of elements is not fixed.
Example:
#include <iostream> #include <vector> using namespace std; int main() { vectornumbers = {1, 2, 3, 4, 5}; numbers.push_back(6); for (int num : numbers) { cout << num << " "; } return 0; }
2. List
A list is a doubly-linked list that allows fast insertion and deletion at any position but slower access compared to a vector.
Example:
#include <iostream> #include <list> using namespace std; int main() { listnumbers = {10, 20, 30}; numbers.push_back(40); numbers.push_front(5); for (int num : numbers) { cout << num << " "; } return 0; }
3. Deque
A deque (double-ended queue) allows fast insertion and deletion at both ends.
Example:
#include <iostream> #include <deque> using namespace std; int main() { dequenumbers = {20, 30}; numbers.push_front(10); numbers.push_back(40); for (int num : numbers) { cout << num << " "; } return 0; }
4. Stack
A stack follows the LIFO (Last In, First Out) principle. Elements are added and removed from the top of the stack.
Example:
#include <iostream> #include <stack> using namespace std; int main() { stacknumbers; numbers.push(10); numbers.push(20); numbers.push(30); while (!numbers.empty()) { cout << numbers.top() << " "; numbers.pop(); } return 0; }
5. Queue
A queue follows the FIFO (First In, First Out) principle. Elements are added at the back and removed from the front.
Example:
#include <iostream> #include <queue> using namespace std; int main() { queuenumbers; numbers.push(10); numbers.push(20); numbers.push(30); while (!numbers.empty()) { cout << numbers.front() << " "; numbers.pop(); } return 0; }
6. Set
A set stores unique elements in sorted order. It does not allow duplicates.
Example:
#include <iostream> #include <set> using namespace std; int main() { setnumbers = {30, 20, 10, 40}; numbers.insert(20); // Duplicate, won't be added for (int num : numbers) { cout << num << " "; } return 0; }
7. Map
A map stores key-value pairs in sorted order by the keys. Keys are unique.
Example:
#include <iostream> #include <map> using namespace std; int main() { mapages; ages["Alice"] = 25; ages["Bob"] = 30; ages["Charlie"] = 20; for (auto pair : ages) { cout << pair.first << ": " << pair.second << endl; } return 0; }
Conclusion
C++ containers provide various ways to organize and manage data, each with its unique characteristics and use cases. Understanding their features helps in choosing the right container for specific tasks.