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

Hàm multiset::begin() và multiset::end() trong C++ STL

begin() và end() cung cấp iterator để duyệt qua các phần tử của multiset theo thứ tự đã sắp xếp (mặc định tăng dần).

multiset::begin()

  • Trả về iterator trỏ đến phần tử đầu tiên (nhỏ nhất).
  • Nếu multiset rỗng, begin() == end().
  • Cú pháp: iterator begin() noexcept; / const_iterator begin() const noexcept;

multiset::end()

  • Trả về iterator trỏ đến vị trí sau phần tử cuối cùng (past-the-end).
  • Không trỏ đến phần tử hợp lệ, chỉ dùng làm sentinel cho vòng lặp.
  • Cú pháp: iterator end() noexcept; / const_iterator end() const noexcept;

Ví dụ 1: Duyệt cơ bản

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

int main() {
    int arr[] = {2, 4, 1, 3, 8, 5, 6};
    multiset<int> ms(arr, arr + 7); // {1,2,3,4,5,6,8}
    
    cout << "Phần tử đầu (begin): " << *ms.begin() << '\n'; // 1
    
    cout << "Tất cả phần tử: ";
    for (auto it = ms.begin(); it != ms.end(); ++it)
        cout << *it << ' ';
    cout << '\n';
    
    // Range-based for (C++11) - tự động dùng begin/end
    cout << "Range-based for: ";
    for (int x : ms) cout << x << ' ';
    cout << '\n';
    
    return 0;
}

Đầu ra

Phần tử đầu (begin): 1
Tất cả phần tử: 1 2 3 4 5 6 8
Range-based for: 1 2 3 4 5 6 8

Ví dụ 2: Iterator const (cbegin/cend)

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

void print_ms(const multiset<int>& ms) {
    // Phải dùng cbegin/cend hoặc const_iterator
    for (auto it = ms.cbegin(); it != ms.cend(); ++it)
        cout << *it << ' ';
    cout << '\n';
}

int main() {
    multiset<int> ms = {5, 1, 3};
    print_ms(ms); // 1 3 5
    return 0;
}

Các biến thể iterator

HàmTrả vềDùng cho
begin()iteratorDuyệt & sửa đổi (non-const)
end()iteratorSentinel non-const
cbegin()const_iteratorDuyệt read-only (const-safe)
cend()const_iteratorSentinel const
rbegin()reverse_iteratorDuyệt ngược (lớn → nhỏ)
rend()reverse_iteratorSentinel reverse
crbegin()const_reverse_iteratorDuyệt ngược const
crend()const_reverse_iteratorSentinel reverse const

Ví dụ 3: Duyệt ngược

multiset<int> ms = {1, 2, 3, 4, 5};
cout << "Ngược: ";
for (auto it = ms.rbegin(); it != ms.rend(); ++it)
    cout << *it << ' '; // 5 4 3 2 1
cout << '\n';

Độ phức tạp

  • begin(), end(), cbegin(), cend(): O(1).
  • Iterator của multiset là BidirectionalIterator (++, --), không phải RandomAccessIterator (không hỗ trợ it + n, it[n]).