💡 퀵 접속: cpp.kr/search_n
C++ 표준 라이브러리의 알고리즘으로, 주어진 범위에서 특정 값이 연속으로 n번 나타나는 첫 번째 위치를 찾습니다. search_n은 원본 범위를 수정하지 않고, 패턴이 발견되면 해당 위치의 반복자를 반환하고, 발견되지 않으면 last 반복자를 반환합니다.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 2, 2, 3, 4, 5, 2, 2, 6};
std::cout << "원본 벡터: ";
for (int n : numbers) std::cout << n << " ";
std::cout << std::endl;
// 값이 2인 요소가 연속으로 3번 나타나는 위치 찾기
auto it = std::search_n(numbers.begin(), numbers.end(), 3, 2);
if (it != numbers.end()) {
std::cout << "연속된 3개의 2가 발견된 위치: ";
for (auto i = it; i != it + 3; ++i) {
std::cout << *i << " ";
}
std::cout << std::endl;
} else {
std::cout << "연속된 3개의 2를 찾을 수 없습니다." << std::endl;
}
return 0;
}
실행 결과:
원본 벡터: 1 2 2 2 3 4 5 2 2 6 연속된 3개의 2가 발견된 위치: 2 2 2
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string text = "Hello...World!!!";
std::cout << "원본 문자열: " << text << std::endl;
// 연속된 3개의 '.' 찾기
auto it = std::search_n(text.begin(), text.end(), 3, '.');
if (it != text.end()) {
std::cout << "연속된 3개의 '.'이 발견된 위치: ";
for (auto i = it; i != it + 3; ++i) {
std::cout << *i;
}
std::cout << std::endl;
} else {
std::cout << "연속된 3개의 '.'을 찾을 수 없습니다." << std::endl;
}
return 0;
}
실행 결과:
원본 문자열: Hello...World!!! 연속된 3개의 '.'이 발견된 위치: ...
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
class Person {
std::string name;
int age;
public:
Person(const std::string& n, int a) : name(n), age(a) {}
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
void print() const {
std::cout << name << " (" << age << "세)" << std::endl;
}
};
int main() {
std::vector<Person> people = {
Person("Alice", 20),
Person("Bob", 30),
Person("Bob", 30),
Person("Bob", 30),
Person("Charlie", 25),
Person("David", 35)
};
std::cout << "원본 목록:" << std::endl;
for (const auto& person : people) {
person.print();
}
// Bob(30세)가 연속으로 3번 나타나는 위치 찾기
Person target("Bob", 30);
auto it = std::search_n(people.begin(), people.end(), 3, target);
if (it != people.end()) {
std::cout << "\n연속된 3개의 Bob(30세)가 발견된 위치:" << std::endl;
for (auto i = it; i != it + 3; ++i) {
i->print();
}
} else {
std::cout << "\n연속된 3개의 Bob(30세)를 찾을 수 없습니다." << std::endl;
}
return 0;
}
실행 결과:
원본 목록: Alice (20세) Bob (30세) Bob (30세) Bob (30세) Charlie (25세) David (35세) 연속된 3개의 Bob(30세)가 발견된 위치: Bob (30세) Bob (30세) Bob (30세)
| 함수 | 설명 |
|---|---|
| search_n(first, last, count, value) | 범위 [first, last)에서 value가 연속으로 count번 나타나는 첫 번째 위치를 찾음 |