
C++ 값 변경하기 replace
Notepad96
·2020. 11. 16. 05:54

1. replace
replace 함수는 algorithm 라이브러리의 포함되어 있다.
replace는 지정한 구간 사이를 검사하여 바꾸고자 하는 값이 존재할 경우 지정한 값으로 변경한다.
해당 작업은 for문과 if문을 사용하여 간단하게 구현 가능하지만 해당 함수를 쓰면 단 한줄로도 똑같은 기능을 할 수 있다.
2. 코 드
환경 : Visual studio 2019
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = { 10, 35, 45, 27, 10 };
for (int i : v) cout << i << " ";
cout << "\n";
replace(v.begin(), v.end(), 10, 90); // 모든 10을 90으로
for (int i : v) cout << i << " ";
cout << "\n==================================\n";
// 홀수인 원소를 -7으로 변환
replace_if(v.begin(), v.end(), [](int a) {return a % 2 == 1; }, -7 );
for (int i : v) cout << i << " ";
cout << "\n==================================\n";
}

- replace 함수는 (시작 반복자, 종료 반복자, 바꾸기 전 값, 바꾼 후 값) 으로 인자를 받는다.
- replace_if 함수는 replace에서 바꾸기 전 값, 즉 바꾸고자 하는 값 대신 조건이 들어간다.
3. 참 조
replace_if - C++ Reference
123456789 template < class ForwardIterator, class UnaryPredicate, class T > void replace_if (ForwardIterator first, ForwardIterator last, UnaryPredicate pred, const T& new_value) { while (first!=last) { if (pred(*first)) *first=new_value; ++first; } }
www.cplusplus.com
'C++ > STL' 카테고리의 다른 글
C++ map value sort - 맵 값 정렬 (0) | 2020.11.17 |
---|---|
C++ 제곱 수, 제곱근 구하기 pow, sqrt, hypot (0) | 2020.11.16 |
C++ 인접하는 중복되는 원소 지우기 unique (0) | 2020.11.15 |
C++ 문자열 소문자, 대문자 변환 transform (0) | 2020.11.15 |
C++ 값 교환하기 Swap (0) | 2020.11.14 |