jeudi 28 mars 2019

Should .at() be used over [] in std::vector or std::array?

This is related to this post that talked about .at() vs [] in std::vector. I just want to ask if .at() should be used over the bracket operators? Take the following code example:

#include <vector>
#include <iostream>

void print(const std::vector<int> &v)
{
  for(int i = 0; i < v.size(); ++i)
  {
    std::cout << v.at(i) << " ";
  }
  std::cout << std::endl;
}

int main()
{
  std::vector<int> test = {1,2,3,4};
  print(test);
}

I would not print a vector this way, I would used for(const auto &e : v) and print out every element as that is guaranteed to not go outside the bounds of the vector. However let's say for a minute we are teaching new students about for loops.

Say we change the second argument in our for loop to v.size() + 1. .at(i) will crash and give us a meaningful runtime error std::out_of_range. However if we change .at(i) to be v[i] the program runs fine and prints out an extra number for me. I'm running this on Ubuntu 18.04 on Window's, I thought the program would crash when I did that however it didn't.

So the question stands, should we be using .at() instead of [] when accessing our containers?

Aucun commentaire:

Enregistrer un commentaire