begin [C++ Reference]
Keywords: stl,map,begin
Date: 2008-10-14T15:42:06-0700

[[begin]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- cz
- de
- es
- fr
- it
- jp
- nl
- pl
- ro
- ru
- sk
- tr
- tw

## begin

Syntax:

        #include <map>
        iterator begin();
        const_iterator begin() const;

The begin() function returns an iterator to the first element of the map. If the map doesn't contain any element, then begin() returns the same as end().

begin() should run in constant time.

For example, the following code uses begin() to initialize an iterator that is used to traverse a list:

        map<string,int> stringCounts;
        string str;

        while( cin >> str ) ++stringCounts[str];

        map<string,int>::iterator iter;
        for( iter = stringCounts.begin(); iter != stringCounts.end(); ++iter ) {
          cout << "word: " << iter->first << ", count: " << iter->second << endl;
        }

When given this input:

        here are some words and here are some more words

…the above code generates this output:

        word: and, count: 1
        word: are, count: 2
        word: here, count: 2
        word: more, count: 1
        word: some, count: 2
        word: words, count: 2

Related Topics: end, rbegin, rend

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •