728x90
#include <algorithm> 필요
자료구조 : 데이터를 저장하는 구조
알고르짐 : 데이터를 어떻게 사용 할 것인가?
find
find_if
count
count_if
all_of
any_of
none_of
for_each
remove
remove_if
find
Q1)number 라는 숫자가 벡터에 체크하는 기능(bool, 첫등장 iterator)
{
int number = 50;
vector<int>::iterator itFind = find(v.begin(), v.end(), number);
if (itFind == v.end())
{
cout << "못찾았음" << endl;
}
else
{
cout << "찾았음" << endl;
}
}
vector<int>::iterator 이 부분도 auto 로 변경가능
find_if
Q2)11로 나뉘는 숫자가 벡터에 있는지 체크하는 기능
{
struct CanDivideBy11
{
bool operator()(int n)
{
return (n % 11) == 0;
}
};
vector<int>::iterator itFind = find_if(v.begin(), v.end(), CanDivideBy11());
if (itFind == v.end())
{
cout << "못찾았음" << endl;
}
else
{
cout << "찾았음" << endl;
}
}
count_if
Q3)홀수인 숫자의 갯수는(count)
{
int count = 0;
struct IsOdd
{
bool operator()(int n)
{
return (n % 2) != 0;
}
};
count = count_if(v.begin(), v.end(), IsOdd());
}
추가로
//모든 데이터가 홀수입니까?
bool b1 = all_of(v.begin(), v.end(), IsOdd());
//홀수인 데이터가 하나라도 있습니까?
bool b2 = any_of(v.begin(), v.end(), IsOdd());
//모든 데이터가 홀수가 아닙니까?
bool b3 = none_of(v.begin(), v.end(), IsOdd());
for_each
//Q4) 벡터에 들어가있는 모든 숫자들에 3을 곱해주세요
{
struct MultiPlyBy3
{
void operator()(int& n)
{
n = n * 3;
}
};
for_each(v.begin(),v.end(), MultiPlyBy3());
}
remove, remove_if // 사용시 주의! 필요한 데이터를 남겨주고 뒤 데이터를 남겨주지 않음
//홀수인 데이터를 일괄 삭제
{
v.clear();
v.push_back(1);
v.push_back(4);
v.push_back(3);
v.push_back(5);
v.push_back(8);
v.push_back(2);
v.push_back(7);
v.push_back(9);
remove(v.begin(), v.end(), 4);
struct IsOdd
{
bool operator()(int n)
{
return (n % 2) != 0;
}
};
v.erase(remove_if(v.begin(), v.end(), IsOdd()), v.end());
}
728x90
'프로그래밍 > c++' 카테고리의 다른 글
weak_ptr(스마트 포인터) (0) | 2024.01.22 |
---|---|
shared_ptr(스마트포인터) (0) | 2024.01.22 |
set, multimap, multiset (0) | 2023.03.04 |
map (0) | 2023.03.04 |
deque (0) | 2023.03.04 |
댓글