Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

match_results::operator= trong C++

std::match_results::operator= (header <regex>) gán nội dung từ một match_results object khác (copy assignment hoặc move assignment).

Cú pháp

match_results& operator=(const match_results& other); // Copy
match_results& operator=(match_results&& other) noexcept; // Move (C++11)

Đặc điểm

  • Sao chép/chuyển tất cả sub-match, prefix, suffix, trạng thái match.
  • Sau gán, hai object độc lập (copy) hoặc source rỗng (move).
  • Trả về reference đến *this.

Ví dụ 1: Copy assignment

#include <bits/stdc++.h>
using namespace std;

int main() {
    string str = "Tutorials Point";
    regex R("(Tutorials)(.*)");
    
    smatch Mat1, Mat2;
    regex_match(str, Mat1, R); // Mat1 có kết quả
    
    Mat2 = Mat1; // Copy assignment
    
    cout << "Mat2 size: " << Mat2.size() << '\n'; // 3
    for (size_t i = 0; i < Mat2.size(); ++i) {
        cout << "Mat2[" << i << "] = '" << Mat2[i] << "'\n";
    }
    return 0;
}

Đầu ra

Mat2 size: 3
Mat2[0] = 'Tutorials Point'
Mat2[1] = 'Tutorials'
Mat2[2] = ' Point'

Ví dụ 2: Chọn match_results lớn hơn

#include <bits/stdc++.h>
using namespace std;

int main() {
    string str = "Tutorials Point";
    regex R1("(Tutorials)(.*)");     // 2 groups
    regex R2("(Po)(int)(.*)");       // 3 groups
    
    smatch Mat1, Mat2;
    regex_match(str, Mat1, R1);
    regex_match(str, Mat2, R2);
    
    smatch Best;
    if (Mat1.size() > Mat2.size())
        Best = Mat1; // Copy
    else
        Best = Mat2; // Copy
    
    cout << "Best match size: " << Best.size() << '\n';
    for (size_t i = 0; i < Best.size(); ++i)
        cout << Best[i] << '\n';
    return 0;
}

Đầu ra

Best match size: 4
Tutorials Point
Po
int

Ví dụ 3: Move assignment (C++11)

#include <bits/stdc++.h>
using namespace std;

smatch find_match(const string& s, const regex& r) {
    smatch m;
    regex_search(s, m, r);
    return m; // NRVO hoặc move
}

int main() {
    string s = "abc123def";
    regex r("(\\d+)");
    
    smatch result = find_match(s, r); // Move assignment
    
    if (!result.empty())
        cout << "Số tìm thấy: " << result[1] << '\n'; // 123
    
    return 0;
}

Lưu ý

  • match_results không thể gán từ kiểu khác (chỉ cùng template parameters).
  • Move assignment hiệu quả hơn cho object lớn (tránh copy allocator, sub_match vector).
  • Sau move, source object ở trạng thái valid nhưng unspecified (thường empty).