1. insert(์ฝ์
ํ ์์น, ๊ฐ) : ์ค๊ฐ์ ์ฝ์
vector<int> v;
for (int i = 0; i < 10; i++) {
v.push_back(i);
}
v.insert(v.begin()+3, 123); //v[3]์ 123์ถ๊ฐ
for (const auto& i : v) cout << i << endl;
//0, 1, 2, 123, 3, ...
2. pop_back() : ๋งจ ๋ ์์ ์ญ์
3. erase() : ํน์ ์์(๋ฒ์) ์ญ์
- ์ค๊ฐ ์ญ์ ๋ ๋ค์ ์์๋ค์ด ํ ์นธ์ฉ ์๋น๊ฒจ์ง๊ธฐ ๋๋ฌธ์ ๋นํจ์จ์
- erase(์์น)
- erase(first, end) : [first, end) ๋ฒ์ ์ญ์
vector<int> v;
for (int i = 0; i < 10; i++) {
v.push_back(i);
}
v.insert(v.begin()+3, 100);
for (const auto& i : v) cout << i<<", ";
cout << endl;
v.erase(v.begin()+2);//v[2]์ญ์
for (const auto& i : v) cout << i<<", ";
cout << endl;
v.erase(v.begin() + 2, v.begin() + 7);//v[2]~v[6]์ญ์
for (const auto& i : v) cout << i << ", ";
4. sort() : ์ ๋ ฌ
- #include <algorithm>
- sort(v.begin(), v.end()) : ์ค๋ฆ์ฐจ์ ์ ๋ ฌ ex) 1, 2, 3, 4, 5
- sort(v.begin(), v.end(), ๋น๊ตํจ์) : ์ฌ์ฉ์ ์ ์ ํจ์, return ๊ฐ์ด ์ฐธ์ด ๋๋๋ก ์ ๋ ฌ
vector<int> v;
for (int i = 0; i < 10; i++) {
v.push_back(i);
}
v.insert(v.begin()+3, 100);
sort(v.begin(), v.end());//๊ธฐ๋ณธ ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
sort(v.begin(), v.end(), compare);//compare ํจ์๋๋ก ์ ๋ ฌ
bool compare(int x, int y) return x>y;//๋ด๋ฆผ์ฐจ์์ผ๋ก ์ ๋ ฌ
5. max_element(), min_element() : ์ต๋, ์ต์
- #include <algorithm>
- iterator๋ฅผ ๋ฐํํ๊ธฐ ๋๋ฌธ์ *๋ก ๊ฐ์ ์ฝ์ด์ผ ํจ(๋ฐฐ์ด์ ํฌ์ธํฐ์ ์ ์ฌ)
- ๋ฒกํฐ โ *max_element(v.begin(), v.end());
- ์ ์ ๋ฐฐ์ด โ *max_element(arr, arr+sizeof(arr)/sizeof(int));
cout << *max_element(v.begin(), v.end()) << endl;
cout << *min_element(v.begin(), v.end()) << endl;
6. next_permutation() : ์์ด ์ ๋ ฌ
- #include <algorithm>
- bool next_permutation(์์ด์ ๊ตฌํ๊ณ ์ถ์ ๋ฒกํฐ.begin(), end())
- ๋ค์ ์์ด ์กด์ฌโtrue return, ๋ค์ ์์ด ์กด์ฌx โ false return
- ๋ชจ๋ ๊ฒฝ์ฐ์ ์์ด์ ๊ตฌํ๊ณ ์ถ์ผ๋ฉด ์ ๋ ฌ์ ๋จผ์ ํด์ผ ํจ
- ์ด์ ์์ด ๊ตฌํ๊ธฐ : prev_permutation()
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
for (const auto& i : v) cout << i << ", ";
cout << endl;
cout << "-----์์ด-----" << endl;
do {//๋ค์ ์์ด์ ๊ตฌํ๊ธฐ ๋๋ฌธ์ ๋จผ์ ์ถ๋ ฅํด์ฃผ๊ณ
for (const auto& i : v) cout << i << ", ";
cout << endl;
} while (next_permutation(v.begin(), v.end()));
7. find() : ์์ ์ฐพ๊ธฐ
- find(v.begin(), v.end(), ์ฐพ๊ณ ์ถ์ ๊ฐ);
- ์ฐพ์ ๊ฐ์ ์ฒซ ๋ฒ์งธ ์ธ๋ฑ์ค iterator๋ฅผ ๋ฐํํ์ฌ *๋ก ๊ฐ์ ์ฝ์ด์ผ ํจ
//์ ์
vector<int> num = { 1, 2, 3, 4, 5 };
auto i = find(num.begin(), num.end(), 3);
//i๋ vector<int>::iteratorํ
if (i == num.end()) {
cout << "์ฐพ์ ์ ์์" << endl;
}
else {
cout << "index : " << i - num.begin() << endl;//i=2
cout << "number : " << *(i+2) << endl;//5
}
//๋ฌธ์์ด
vector<string> alpha = { "abc", "d", "efg", "hijklm", "nopq" };
vector<string>::iterator iter = find(alpha.begin(), alpha.end(), "efg");
cout << *iter << endl;//"efg"
*iter = "abc"; //alpha[2] = "abc"๋ก ๋ณ๊ฒฝ
for (const auto& i : alpha) {
cout << i << endl;
//"abc","d","abc","hijklm","nopq"
}