Below are simple examples of using each of the requested STL structures in C++, along with a list of member functions for vector, which also apply with variations to many of the other container types:
- array
#include <array>
int main() {
std::array<int, 3> arr = {1, 2, 3};
for (int i : arr) {
std::cout << i << std::endl;
}
}
- vector
#include <vector>
int main() {
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
for (auto& val : vec) {
std::cout << val << std::endl;
}
}
Member functions of std::vector:
assign, at, back, begin, capacity, cbegin, cend, clear,
crbegin, crend, data, emplace, emplace_back, empty, end,
erase, front, get_allocator, insert, max_size, pop_back,
push_back, rbegin, rend, reserve, resize, shrink_to_fit,
size, swap.
- list
#include <list>
int main() {
std::list<int> lst = {1, 2, 3};
for (auto& val : lst) {
std::cout << val << std::endl;
}
}
- queue
#include <queue>
int main() {
std::queue<int> q;
q.push(1);
q.push(2);
q.push(3);
while (!q.empty()) {
std::cout << q.front() << std::endl;
q.pop();
}
}
- map
#include <map>
int main() {
std::map<std::string, int> m;
m["one"] = 1;
m["two"] = 2;
m["three"] = 3;
for (const auto& pair : m) {
std::cout << pair.first << " => " << pair.second << std::endl;
}
}
- unordered_map
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> um;
um["one"] = 1;
um["two"] = 2;
um["three"] = 3;
for (const auto& pair : um) {
std::cout << pair.first << " => " << pair.second << std::endl;
}
}
- set
#include <set>
int main() {
std::set<int> s = {1, 2, 3};
s.insert(4);
for (int val : s) {
std::cout << val << std::endl;
}
}
- deque
#include <deque>
int main() {
std::deque<int> d;
d.push_back(2);
d.push_front(1);
d.push_back(3);
for (int val : d) {
std::cout << val << std::endl;
}
}
- priority_queue
#include <queue>
int main() {
std::priority_queue<int> pq;
pq.push(3);
pq.push(1);
pq.push(2);
while (!pq.empty()) {
std::cout << pq.top() << std::endl;
pq.pop();
}
}
- multiset
#include <set>
int main() {
std::multiset<int> ms = {1, 2, 2, 3};
ms.insert(2);
for (int val : ms) {
std::cout << val << std::endl;
}
}
- STL sort, find example
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec = {4, 1, 3, 2};
std::sort(vec.begin(), vec.end()); // Sort the vector
auto it = std::find(vec.begin(), vec.end(), 3); // Find the number 3
if (it != vec.end()) {
std::cout << "Found " << *it << std::endl;
}
}
- STL iterator example
#include <vector>
#include <iostream>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// Using iterator to access vector elements
for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << std::endl;
}
}
Remember to include the corresponding headers <iostream> for I/O operations and other specific headers such as <vector>, <list>, <queue>, <map>, <unordered_map>, <set>, <deque>, <algorithm> for the respective containers.