람다 함수는 익명 함수(anonymous function)로, 간결하게 정의하여 코드의 가독성을 높이고, 함수 객체(functor) 없이도 간편하게 사용할 수 있다.
✅ 람다 함수 기본 문법
Copy code
[capture](parameter_list) -> return_type { function_body };
✅ 예제
#include <iostream>
int main() {
auto add = [](int a, int b) { return a + b; };
std::cout << add(3, 5) << std::endl; // 8
}
[] : 캡처 리스트 (외부 변수를 사용할 수 있게 함)
-> 클래스처럼 객체에 대한 변수를 사용할 경우엔 [this]를 통해 인스턴스에 대한 변수임을 알려야 함.
[&] -> 모든 외부 변수를 레퍼런스로
[=] -> 모든 외부 변수를 복사본으로
[&a ,b] -> 반반
(int a, int b) : 매개변수 리스트
{ return a + b; } : 함수 본문
std::remove는 특정 값을 배열 또는 컨테이너에서 삭제하는 것처럼 보이게 한다. 실제로 원소를 삭제하는 것이 아니라, 제거된 요소들을 컨테이너의 끝으로 이동시키고, 새로운 끝을 가리키는 반복자를 반환한다.
✅ 사용법
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5, 3, 6};
vec.erase(std::remove(vec.begin(), vec.end(), 3), vec.end());
for (int v : vec) std::cout << v << " "; // 1 2 4 5 6
}
💡 주의: std::remove는 원소를 삭제하는 것이 아니라, 새로운 위치로 이동시키므로 erase와 함께 사용해야 한다.
std::remove_if는 조건을 만족하는 요소들을 제거하는 버전이다.
✅ 사용법
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5, 6};
vec.erase(std::remove_if(vec.begin(), vec.end(), [](int x) { return x % 2 == 0; }), vec.end());
for (int v : vec) std::cout << v << " "; // 1 3 5
}
💡 람다 함수 사용 가능하여 더욱 유연하게 조건을 설정할 수 있다.
std::sort는 빠른 정렬(QuickSort, HeapSort, IntroSort를 혼합한 최적화된 정렬 알고리즘)을 사용하여 컨테이너를 정렬한다.
✅ 기본 사용법 (오름차순 정렬)
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {5, 2, 9, 1, 5, 6};
std::sort(vec.begin(), vec.end());
for (int v : vec) std::cout << v << " "; // 1 2 5 5 6 9
}
✅ 내림차순 정렬 (람다 사용)
std::sort(vec.begin(), vec.end(), [](int a, int b) { return a > b; });
std::stable_sort는 안정적인 정렬 알고리즘으로, 같은 값에 대한 상대적인 순서를 유지한다.
✅ 예제
#include <iostream>
#include <vector>
#include <algorithm>
struct Person {
std::string name;
int age;
};
int main() {
std::vector<Person> people = {{"Alice", 30}, {"Bob", 25}, {"Charlie", 30}};
std::stable_sort(people.begin(), people.end(), [](const Person &a, const Person &b) {
return a.age < b.age;
});
for (const auto &p : people) std::cout << p.name << " "; // Bob Alice Charlie
}
💡 정렬 후에도 Alice와 Charlie의 순서가 유지됨 (stable)
std::partial_sort는 컨테이너의 일부만 정렬하는 알고리즘으로, 상위 N개의 요소만 정렬할 때 유용하다.
✅ 예제
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {10, 5, 8, 1, 7, 9};
std::partial_sort(vec.begin(), vec.begin() + 3, vec.end());
for (int v : vec) std::cout << v << " "; // 1 5 7 10 8 9
}
💡 처음 3개의 요소만 정렬됨, 나머지는 정렬되지 않음.
std::transform은 컨테이너의 각 요소를 변환하여 새로운 컨테이너에 저장할 때 사용한다.
✅ 예제 (각 요소를 2배로 변환)
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::vector<int> result(vec.size());
std::transform(vec.begin(), vec.end(), result.begin(), [](int x) { return x * 2; });
for (int v : result) std::cout << v << " "; // 2 4 6 8 10
}
💡 원본 컨테이너는 유지하면서 변환된 결과를 다른 컨테이너에 저장할 수 있음.
std::find는 컨테이너에서 특정 값을 찾아 첫 번째 위치를 반환하는 알고리즘이다.
✅ 사용법
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
auto it = std::find(vec.begin(), vec.end(), 30);
if (it != vec.end()) {
std::cout << "Found: " << *it << std::endl; // Found: 30
} else {
std::cout << "Not Found" << std::endl;
}
}
첫 번째 30을 찾으면 반복자를 반환하며, 없으면 vec.end()를 반환한다.
std::find_if는 특정 조건을 만족하는 첫 번째 요소를 찾는 알고리즘이다.
✅ 사용법
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {10, 21, 33, 40, 50};
auto it = std::find_if(vec.begin(), vec.end(), [](int x) { return x % 2 == 1; });
if (it != vec.end()) {
std::cout << "First odd number: " << *it << std::endl; // First odd number: 21
} else {
std::cout << "No odd numbers found" << std::endl;
}
}
람다 함수를 사용해 홀수(x % 2 == 1)인 첫 번째 요소를 찾는다.
set,map과 같은 컨테이너는 이미 내부 구조를 알고 있어 해당 컨테이너의 find함수를 쓰는 것이 더 빠르(효율적)이다. 내부적으로 find함수가 없을 경우 사용하면 유용하다.
std::all_of는 컨테이너의 모든 요소가 특정 조건을 만족하는지 확인하는 알고리즘이다.
✅ 사용법
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {2, 4, 6, 8, 10};
bool allEven = std::all_of(vec.begin(), vec.end(), [](int x) { return x % 2 == 0; });
if (allEven) {
std::cout << "All elements are even." << std::endl; // 출력됨
} else {
std::cout << "Not all elements are even." << std::endl;
}
}
✔️ 모든 요소가 짝수(x % 2 == 0)인지 검사
✔️ 모든 요소가 조건을 만족하면 true, 그렇지 않으면 false 반환
std::any_of는 컨테이너의 하나 이상의 요소가 특정 조건을 만족하는지 확인하는 알고리즘이다.
✅ 사용법
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {2, 4, 6, 9, 10};
bool hasOdd = std::any_of(vec.begin(), vec.end(), [](int x) { return x % 2 == 1; });
if (hasOdd) {
std::cout << "There is at least one odd number." << std::endl; // 출력됨
} else {
std::cout << "No odd numbers found." << std::endl;
}
}
✔️ 하나라도 홀수(x % 2 == 1)인 요소가 있으면 true 반환
✔️ 모든 요소가 조건을 만족하지 않으면 false 반환