begin

C/C++ Reference

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

The function begin() returns an iterator to the first element of the map. 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: