Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

C++ STL match_results::cbegin()과 cend() 함수 완벽 가이드

이 글에서는 C++ STL에서 제공하는 match_results::cbegin()match_results::cend() 함수의 동작 방식, 구문, 그리고 실제 예제를 자세히 살펴보겠습니다.

C++ STL에서 match_results란 무엇인가?

std::match_results는 정규식(regex) 매칭 작업의 결과로 일치한 문자 시퀀스들의 집합을 저장하는 데 사용되는 특수한 컨테이너 유형의 클래스입니다. 이 컨테이너 클래스 내에서 정규식 매치 연산은 대상 시퀀스와 일치하는 항목들을 찾아 저장합니다.

match_results::cbegin()이란?

match_results::cbegin() 함수는 C++ STL에 내장된 함수로, <regex> 헤더 파일에 정의되어 있습니다. 이 함수는 match_results 컨테이너의 첫 번째 요소를 가리키는 상수 반복자(const_iterator)를 반환합니다. 상수 반복자는 컨테이너의 요소를 수정하는 데 사용할 수 없으며, 오직 컨테이너를 읽기 전용으로 순회하는 용도로만 사용됩니다.

구문

smatch_name.cbegin();

매개변수

이 함수는 매개변수를 받지 않습니다.

반환 값

이 함수는 match_results 컨테이너의 첫 번째 요소를 가리키는 상수 반복자를 반환합니다.

예제

입력:
std::string str("TutorialsPoint");
std::smatch Mat;
std::regex re("(Tutorials)(.*)");
std::regex_match(str, Mat, re);
Mat.cbegin();

출력: T

전체 예제 코드

#include <iostream>
#include <string>
#include <regex>

int main () {
    std::string str("Tutorials");
    std::smatch Mat;
    std::regex re("(Tuto)(.*)");
    std::regex_match(str, Mat, re);
    std::cout << "Match Found: " << std::endl;
    for (auto i = Mat.cbegin(); i != Mat.cend(); ++i) {
        std::cout << *i << std::endl;
    }
    return 0;
}

실행 결과

위 코드를 실행하면 다음과 같은 출력이 생성됩니다.

Match Found
Tutorials
Tuto
rials

match_results::cend()란?

match_results::cend() 함수 역시 C++ STL에 내장된 함수로, <regex> 헤더 파일에 정의되어 있습니다. 이 함수는 match_results 컨테이너의 마지막 요소 다음 위치를 가리키는 상수 반복자를 반환합니다. 동작 방식은 match_results::end() 함수와 동일하지만, 반환되는 반복자가 상수라는 점이 다릅니다.

구문

smatch_name.cend();

매개변수

이 함수는 매개변수를 받지 않습니다.

반환 값

이 함수는 match_results 컨테이너의 마지막 요소 바로 다음(past-the-end) 위치를 가리키는 상수 반복자를 반환합니다.

예제

입력:
std::string str("TutorialsPoint");
std::smatch Mat;
std::regex re("(Tutorials)(.*)");
std::regex_match(str, Mat, re);
Mat.cend();

출력: m (마지막 요소 다음 위치의 임의 값)

전체 예제 코드

#include <iostream>
#include <string>
#include <regex>

int main () {
    std::string str("Tutorials");
    std::smatch Mat;
    std::regex re("(Tuto)(.*)");
    std::regex_match(str, Mat, re);
    std::cout << "Match Found: " << std::endl;
    for (auto i = Mat.cbegin(); i != Mat.cend(); ++i) {
        std::cout << *i << std::endl;
    }
    return 0;
}

실행 결과

위 코드를 실행하면 다음과 같은 출력이 생성됩니다.

Match Found
Tutorials
Tuto
rials

정리

cbegin()cend()는 각각 컨테이너의 시작과 끝(마지막 요소 다음)을 가리키는 상수 반복자를 반환합니다. 따라서 정규식 매칭으로 얻은 캡처 그룹들을 읽기 전용으로 안전하게 순회해야 할 때 이 두 함수를 함께 사용하면 깔끔하고 효율적인 코드를 작성할 수 있습니다.