1. vector 기본 예제
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> items;
items.push_back(1);
items.push_back(8);
items.push_back(15);
items.push_back(20);
items.pop_back();
// items.insert(시작점, 개수, 값);
items.insert(items.end(), 2, 30);
cout << "[size] : " << items.size() << endl;
cout << "[first item] : " << items.front() << endl;
cout << "[last item] : " << items.back() << endl;
return 0;
}
2. vector 순열
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
vector<int> items{3, 4, 6, 8, 12};
int len = items.size();
for (int i = items.size() - 1; i >= 0; i--) {
vector<bool> states(i, false);
states.insert(states.begin(), len - i, true);
do {
cout << "[items] ";
string value = "";
for (int j = 0; j < states.size(); j++) {
cout << states[j] << " ";
if (states[j]) {
value += to_string(items[j]) + " ";
}
}
cout << ">> " << value << endl;
}
while (prev_permutation(states.begin(), states.end()));
}
return 0;
}
3. vector 개수 세기
#include <vector>
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main() {
vector<int> items{3, 3, 5, 8, 5, 2, 8, 10};
set<int> item_set(items.begin(), items.end());
for (int item : item_set) {
int item_count = count(items.begin(), items.end(), item);
cout << item << " >> " << item_count << "\n";
}
return 0;
}
4. vector heap
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int answer = 0;
vector<int> items{5, 3, 8, 9, 2};
int count = 4;
make_heap(items.begin(), items.end());
while (count > 0) {
pop_heap(items.begin(), items.end());
int max_value = items.back();
if (max_value <= 0) break;
items.pop_back();
items.push_back(max_value - 1);
count--;
}
for (int i = 0; i < items.size(); i++) {
cout << items[i] << "\t";
}
cout << endl;
return 0;
}