Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- 매터
- 홈네트워크
- 배당
- 애플
- 해외주식
- 국내주식
- matter
- esp32
- Python
- ConnectedHomeIP
- homebridge
- Espressif
- 나스닥
- 엔비디아
- 월패드
- Bestin
- 티스토리챌린지
- 공모주
- 오블완
- 미국주식
- MQTT
- RS-485
- raspberry pi
- Home Assistant
- 현대통신
- 라즈베리파이
- 힐스테이트 광교산
- 코스피
- Apple
- 파이썬
Archives
- Today
- Total
YOGYUI
std::vector 내부 요소에서 시퀀스 찾기 (find sub-sequence) 본문
반응형
<algorithm>에 정의되어 있는 std::search 함수를 사용하면 쉽게 구현할 수 있다
template <class ForwardIterator1, class ForwardIterator2>
ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, ForwardIterator2 last2);
Search range for subsequence
Searches the range [first1,last1) for the first occurrence of the sequence defined by [first2,last2), and returns an iterator to its first element, or last1 if no occurrences are found.
The elements in both ranges are compared sequentially using operator == (or pred, in version (2)): A subsequence of [first1,last1) is considered a match only when this is true for all the elements of [first2,last2).
This function returns the first of such occurrences. For an algorithm that returns the last instead, see find_end.
예를 위해 "Hello,World!" 문자들로 이루어진 바이트형 벡터에서 'lo' 문자열 시퀀스의 인덱스를 가져와보자
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<uint8_t> origin = { 'H', 'e', 'l', 'l', 'o', ',', 'W', 'o','r' ,'l' ,'d', '!'};
std::vector<uint8_t> find = { 'l', 'o' };
std::vector<size_t> indexes{};
auto it{ origin.begin() };
while ((it = std::search(it, origin.end(), find.begin(), find.end())) != origin.end()) {
indexes.push_back(std::distance(origin.begin(), it++));
}
for (auto const element : origin) {
std::cout << element;
}
std::cout << std::endl;
for (auto const element : indexes) {
std::cout << element << std::endl;
}
}
출력 결과
Hello,World!
3
시퀀스가 여러개 존재할 경우
std::vector<int> origin = { 1, 2, 3, 4, 5, 2, 3, 6, 7, 2, 3, 1, 2, 3, 2, 4 };
std::vector<int> find = { 2, 3 };
출력결과
1234523672312324
1
5
9
12
[참고]
https://www.cplusplus.com/reference/algorithm/search/
https://codereview.stackexchange.com/questions/179214/finding-subsequences-of-vector-from-a-vector
반응형
'Software > C, C++' 카테고리의 다른 글
C++::chrono - 현재 날짜/시간 가져오기 (밀리초 포함) (0) | 2022.07.24 |
---|---|
MFC::프로그램으로 PC 전원 끄기 (Windows OS) (0) | 2022.02.23 |
C/C++::CRC8, CRC16, CRC32 계산 라이브러리 깃허브 등록 (DLL) (0) | 2021.10.22 |
C++::CRC-16 계산 알고리즘 구현 (소스코드) (2) | 2021.10.13 |
MFC::SetupAPI - 장치관리자(Device Manager) 정보 얻기 (0) | 2021.06.24 |