STL 알고리즘 ( algorithm )
STL 알고리즘 ( algorithm )
1. 일반 함수
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
list<int> s = {1,2,3,4,5,6,7,8,9,10};
vector<int> v = {1,2,3,4,5,6,7,8,9,10};
//s.find(5);
//v.find(5); // 같은 알고리즘을 컨테이너마다 가지고 있어야 하나는 의문으로 멤버 함수로 있지 않고 일반 함수로 있음.
// 핵심 1. 멤버 함수가 아니고 일반함수 이다.
find(s.begin(), s.end(), 5);
find(v.begin(), v.end(), 5);
}
2. 검색 리턴 값
int main()
{
vector<int> v = {1,2,3,4,5,6,7,8,9,10};
vector<int>::iterator p = find(v.begin(), v.end(), 5); // C++11 : auto p = find(v.begin(), v.end(), 5);
cout << *p << endl;
auto p1 = find(v.begin(), v.end(), 15);
if (p1 == v.end())
cout << "검색실패" << endl;
auto p3 = v.begin();
auto ret = find(p3, p3+5, 6); // 검색실패함.
if (ret == p3 + 5)
cout << "검색실패" << endl;
}
3. 뒤집기, 정렬
int main()
{
vector<int> v = {1,2,3,4,5,6,7,8,9,10};
// 뒤집기
reverse(v.begin(), v.end));
// 정렬
sort(v.begin(), v.end());
sort(v.begin(), v.begin+6); // 5 6 7 8 9 10 4 3 2 1
for (auto n : v)
cout << n << endl;
}