C++ Standard Library C++ STL Library

C++ <vector> - begin() Function



The C++ vector::begin function returns the iterator pointing to the first element of the vector. Please note that, Unlike the vector::front function, which returns a direct reference to the first element, it returns the iterator pointing to the same element of the vector.

C++ begin end

Syntax

iterator begin();
const_iterator begin() const;
iterator begin() noexcept;
const_iterator begin() const noexcept;

Parameters

No parameter is required.

Return Value

An iterator to the beginning of the sequence container. If the sequence object is constant qualified, the function returns a const_iterator, else returns an iterator.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the vector::begin function returns the iterator pointing to the first element of the vector called MyVector.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<string> MyVector{"Alpha","Coding","Skills"};
  vector<string>::iterator it;

  it = MyVector.begin();
  cout<<*it<<" ";
  it++;
  cout<<*it<<" ";
  it++;
  cout<<*it<<" ";
  return 0;
}

The output of the above code will be:

Alpha Coding Skills

Example:

Lets see another example where the vector called MyVector contains integer values and vector::begin function is used with vector::end function to specify a range including all elements of the vector container.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> MyVector{10, 20, 30, 40, 50};
  vector<int>::iterator it;

  for(it = MyVector.begin(); it != MyVector.end(); ++it)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

10 20 30 40 50 

❮ C++ <vector> Library

5