Namespaces
Variants

std::map<Key,T,Compare,Allocator>:: begin, std::map<Key,T,Compare,Allocator>:: cbegin

From cppreference.net

iterator begin ( ) ;
(1) (C++11以降 noexcept)
(C++26以降 constexpr)
const_iterator begin ( ) const ;
(2) (C++11以降 noexcept)
(C++26以降 constexpr)
const_iterator cbegin ( ) const noexcept ;
(3) (C++11以降)
(C++26以降 constexpr)

* this の最初の要素へのイテレータを返します。

* this が空の場合、返されるイテレータは end() と等しくなります。

range-begin-end.svg

目次

戻り値

最初の要素へのイテレータ。

計算量

定数。

注記

libc++は cbegin() をC++98モードにバックポートします。

#include <iostream>
#include <map>
int main()
{
    std::map<int, float> num_map;
    num_map[4] = 4.13;
    num_map[9] = 9.24;
    num_map[1] = 1.09;
    // num_map.begin() と num_map.end() を呼び出す
    for (auto it = num_map.begin(); it != num_map.end(); ++it)
        std::cout << it->first << ", " << it->second << '\n';
}

出力:

1, 1.09
4, 4.13
9, 9.24

カスタム比較関数を使用した例

#include <cmath>
#include <iostream>
#include <map>
struct Point { double x, y; };
// 2つのPointポインタのx座標を比較
struct PointCmp
{
    bool operator()(const Point* lhs, const Point* rhs) const
    {
        return lhs->x < rhs->x; 
    }
};
int main()
{
    // x座標は順不同だが、マップはx座標の昇順で反復処理される
    Point points[3] = {{2, 0}, {1, 0}, {3, 0}};
    // magはノードのアドレスをxy平面での大きさにマッピングするマップ
    // キーはPointへのポインタだが、Pointのアドレスではなくx座標で
    // マップを順序付けたい。これはPointCmpクラスの比較メソッドを使用して行う
    std::map<Point*, double, PointCmp> mag(
        {{points, 2}, {points + 1, 1}, {points + 2, 3}}
    );
    // 各y座標を0から大きさに変更
    for (auto iter = mag.begin(); iter != mag.end(); ++iter)
    {
        auto cur = iter->first; // ノードへのポインタ
        cur->y = mag[cur]; // cur->y = iter->second; も使用可能
    }
    // 各ノードの大きさを更新して出力
    for (auto iter = mag.begin(); iter != mag.end(); ++iter)
    {
        auto cur = iter->first;
        mag[cur] = std::hypot(cur->x, cur->y);
        std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is ";
        std::cout << iter->second << '\n';
    }
    // 範囲ベースのforループで上記を繰り返し
    for (auto i : mag)
    {
        auto cur = i.first;
        cur->y = i.second;
        mag[cur] = std::hypot(cur->x, cur->y);
        std::cout << "The magnitude of (" << cur->x << ", " << cur->y << ") is ";
        std::cout << mag[cur] << '\n';
        // 上記のstd::cout << iter->second << '\n';とは対照的に、
        // std::cout << i.second << '\n'; は更新された大きさを出力しない
        // 代わりに auto &i : mag を使用した場合は、更新された大きさを出力する
    }
}

出力:

The magnitude of (1, 1) is 1.41421
The magnitude of (2, 2) is 2.82843
The magnitude of (3, 3) is 4.24264
The magnitude of (1, 1.41421) is 1.73205
The magnitude of (2, 2.82843) is 3.4641
The magnitude of (3, 4.24264) is 5.19615

関連項目

(C++11)
終端を指すイテレータを返す
(public member function)
(C++11) (C++14)
コンテナまたは配列の先頭を指すイテレータを返す
(function template)