C++/Library
2021. 3. 26. 15:23
STL 알고리즘 (Algorithms)
예제
클래스를 원소로 넣을 경우 대부분 비교 연산자 오버로딩을 해놔야 한다.
#include <iostream> #include <vector> #include <algorithm> int main() { using namespace std; vector<int> container; for (int i = 0; i < 10; ++i) container.push_back(i); auto itr = min_element(container.begin(), container.end()); cout << "Min element : " << *itr << endl; itr = max_element(container.begin(), container.end()); cout << "Max element : " << *itr << "\n\n"; itr = find(container.begin(), container.end(), 3); container.insert(itr, 128); for (auto& e : container) cout << e << ' '; cout << endl; sort(container.begin(), container.end()); for (auto& e : container) cout << e << ' '; cout << endl; reverse(container.begin(), container.end()); for (auto& e : container) cout << e << ' '; cout << endl; } /* stdout stderr Min element : 0 Max element : 9 0 1 2 128 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 128 128 9 8 7 6 5 4 3 2 1 0 */
list
의 경우sort()
함수를 쓸 수 없고, 클래스 멤버 함수인list::sort()
를 사용해야 한다.#include <iostream> #include <list> #include <algorithm> int main() { using namespace std; list<int> container; for (int i = 0; i < 10; ++i) container.push_back(i); auto itr = min_element(container.begin(), container.end()); cout << "Min element : " << *itr << endl; itr = max_element(container.begin(), container.end()); cout << "Max element : " << *itr << "\n\n"; itr = find(container.begin(), container.end(), 3); container.insert(itr, 128); for (auto& e : container) cout << e << ' '; cout << endl; container.sort(); for (auto& e : container) cout << e << ' '; cout << endl; container.reverse(); for (auto& e : container) cout << e << ' '; cout << endl; } /* stdout stderr Min element : 0 Max element : 9 0 1 2 128 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 128 128 9 8 7 6 5 4 3 2 1 0 */
참고
'C++ > Library' 카테고리의 다른 글
C++ sstream (0) | 2021.03.26 |
---|---|
C++ string (0) | 2021.03.26 |
C++ STL 반복자 (Iterators) (0) | 2021.03.26 |
C++ multimap (0) | 2021.03.26 |
C++ map (0) | 2021.03.26 |