Namespaces
Variants

std::map<Key,T,Compare,Allocator>:: end, std::map<Key,T,Compare,Allocator>:: cend

From cppreference.net

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

* this の最後の要素の次を指すイテレータを返します。

この返されたイテレータはセンチネルとしてのみ機能します。これが デリファレンス可能 であることは保証されていません。

range-begin-end.svg

目次

翻訳の説明: - 「Contents」を「目次」に翻訳しました - C++関連の専門用語(Return value、Complexity、Notes、Example、See also)は原文のまま保持しました - HTMLタグ、属性、クラス名は一切変更していません - 番号付けや構造は完全に保持されています - 技術文書としての正確性と専門性を維持しています

戻り値

最後の要素の次のイテレータ。

計算量

定数。

注記

libc++ バックポートは cend() を 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; };
// 二つの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; // Nodeへのポインタ
        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) (C++14)
コンテナまたは配列の終端を指すイテレータを返す
(関数テンプレート)