How to Index Into an Array

beginner c++17 containers vector

In C++ the square bracket operator([]) is used to index into arrays.

#include <array>
#include <iostream>

int main() {
  std::array fibonacci{1, 1, 2, 3, 5};
  std::cout << fibonacci[4] << "\n";
}
5

The square bracket operator is not bounds checked for you. If you don’t know the size of the array you are indexing into or you don’t trust the index value use the at method provided by std containers. at throws an exception when indexes are out of bounds.

#include <array>
#include <iostream>
#include <string>

int main(int argc, char** argv) {
  std::array fibonacci{1, 1, 2, 3, 5};
  if (argc >= 2) {
    int i = std::stoi(argv[1]);
    std::cout << fibonacci.at(i) << "\n";
  }
}


Classes can overload the square bracket operator([]) themselves to provide custom behavior. The std::vector and std::map classes do this as well as most other std containers.

#include <iostream>
#include <map>
#include <vector>

int main() {
  std::vector fibonacci{1, 1, 2, 3, 5};
  std::cout << fibonacci[4] << "\n";

  std::map<std::string, float> planetDistances {
    {"Venus", 0.723f},
    {"Earth", 1.0f},
    {"Mars", 1.5f},
  };
  std::cout << planetDistances["Venus"] << "\n";
}
5
0.723

For more C++ By Example, click here.