예시코드)
https://github.com/GbLeem/CPP_Study/tree/main/NoCode
62.cpp ~ 66.cpp
#include<iostream>
#include<list>
int main()
{
std::list<int> nums{ 1,2,3,4,5 };
nums.emplace_back(6);
nums.emplace_front(0);
auto it = std::find(nums.begin(), nums.end(), 3); //O(n)의 find
if (it != nums.end())
{
nums.emplace(it, 100); //O(1)의 emplace
}
for (auto num : nums)
{
std::cout << num << " "; //0 1 2 100 3 4 5 6
}
std::cout << std::endl;
return 0;
}
#include<algorithm>
#include<iostream>
#include<forward_list>
int main()
{
std::forward_list<int>nums{ 1,2,3,4,5 };
nums.emplace_front(0);
for (auto num : nums)
{
std::cout << num << " ";// 0 1 2 3 4 5
}
std::cout << std::endl;
return 0;
}
random access | insert, delete | insert,delete at the end | find | |
---|---|---|---|---|
vector | O(1) | O(n) | O(1) | O(n) |
list | O(n) | O(1) | O(1) | O(n) |
#include<iostream>
#include<stack>
int main()
{
std::stack<int> nums;
nums.emplace(1);
nums.emplace(3);
nums.emplace(5);
std::cout << nums.top() << std::endl;
nums.pop();
std::cout << nums.top() << std::endl;
nums.pop();
std::cout << nums.top() << std::endl;
nums.pop();
std::cout << "size: " << nums.size() << std::endl;
return 0;
}
#include<iostream>
#include<queue>
int main()
{
std::queue<int> nums;
nums.emplace(1);
nums.emplace(3);
nums.emplace(5);
std::cout << nums.front() << " " << nums.back() << std::endl;
nums.pop();
std::cout << nums.front() << " " << nums.back() << std::endl;
nums.pop();
std::cout << nums.front() << " " << nums.back() << std::endl;
nums.pop();
std::cout << "size: " << nums.size() << std::endl;
return 0;
}
#include<iostream>
#include<queue>
int main()
{
std::priority_queue<int> q;
q.emplace(1);
q.emplace(3);
q.emplace(5);
q.emplace(7);
q.emplace(9);
std::cout << q.top() << std::endl; //9
q.emplace(10); // O(log n)
std::cout << q.top() << std::endl;//O(1) 10
q.pop();
q.pop();
q.pop();
std::cout << q.top() << std::endl; //5
}
#include <algorithm>
#include <functional>
#include <iostream>
#include <string_view>
#include <vector>
void print(std::string_view text, std::vector<int> const& v = {})
{
std::cout << text << ": ";
for (const auto& e : v) std::cout << e << ' ';
std::cout << '\n';
}
int main()
{
print("Max heap");
std::vector<int> v{ 3, 2, 4, 1, 5, 9 };
print("initially, v", v);
std::make_heap(v.begin(), v.end()); //O(n)
print("after make_heap, v", v); //9 5 4 1 2 3
std::pop_heap(v.begin(), v.end()); //O(log n)
print("after pop_heap, v", v); //5 3 4 1 2 9
auto top = v.back();
v.pop_back();
print("former top element", { top }); //9
print("after removing the former top element, v", v); //5 3 4 1 2
v.emplace_back(100); //숫자 넣기
print("after emplace_back, v", v); //5 3 4 1 2 100
std::push_heap(v.begin(), v.end()); //다시 heap으로 정렬 O(log n)
print("after push_heap, v", v); //100 3 5 1 2 4
return 0;
}