C++ <list> begin / end 関数

C++ 容器类 <list>C++ コンテナクラス <list>


beginとendlist の中でもっとも重要なイテレータ関数であり、使用されるのはリンクリストの先頭と末尾のイテレータを取得することです。

beginとendコンテナクラスのメンバ関数です:

  • beginリンクリストの最初の要素を指すイテレータを返します
  • endリンクリストの最後の要素の次の位置を指すイテレータを返します(番兵イテレータ)

この2つの関数は、C++ 標準ライブラリのアルゴリズムと範囲 for ループの基礎です。

単語の意味: begin「開始」を表し、end「終了」を表します。


基本構文とパラメータ

構文形式

iterator begin();
const_iterator begin() const;

iterator end();
const_iterator end() const;

関数の説明

  • 戻り値: begin()最初の要素を指すイテレータを返し、end()番兵イテレータを返します。

例

例1:リンクリストの走査

例

#include <iostream>
#include <list>

int main() {
    std::list<int> numbers = {10, 20, 30, 40, 50};

    // イテレータを使用して走査する
    std::cout << "イテレータを使用した走査: ";
    for(auto it = numbers.begin(); it != numbers.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

期待される実行結果:

使用迭代器遍历: 10 20 30 40 50

例2:範囲 for ループ

例

#include <iostream>
#include <list>

int main() {
    std::list<std::string> names = {"Alice", "Bob", "Charlie"};

    std::cout << "範囲 for ループ: ";
    for(const auto& name : names) {
        std::cout << name << " ";
    }
    std::cout << std::endl;

    return 0;
}

期待される実行結果:

范围 for 循环: Alice Bob Charlie

例3:STL アルゴリズムの使用

例

#include <iostream>
#include <list>
#include <algorithm>

int main() {
    std::list<int> numbers = {5, 2, 8, 1, 9, 3};

    // ソート
    numbers.sort();
    std::cout << "ソート後: ";
    for(int n : numbers) std::cout << n << " ";
    std::cout << std::endl;

    // 検索
    auto it = std::find(numbers.begin(), numbers.end(), 8);
    if(it != numbers.end()) {
        std::cout << "見つかりました: " << *it << std::endl;
    }

    return 0;
}

期待される実行結果:

排序后: 1 2 3 5 8 9
找到: 8

例4:逆イテレータ

例

#include <iostream>
#include <list>

int main() {
    std::list<int> numbers = {1, 2, 3, 4, 5};

    std::cout << "順方向: ";
    for(auto it = numbers.begin(); it != numbers.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    std::cout << "逆方向: ";
    for(auto it = numbers.rbegin(); it != numbers.rend(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

期待される実行結果:

正向: 1 2 3 4 5
反向: 5 4 3 2 1

C++ 容器类 <list>C++ コンテナクラス <list>

その他の拡張