Difference Between courseGrades[i] and courseGrades.at(i)

  • Context:
  • Thread starter Thread starter ineedhelpnow
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
8 replies · 2K views
ineedhelpnow
Messages
649
Reaction score
0
i may have asked this before but what is the difference between and at(i)?

ex. courseGrades and courseGrades.at(i)
 
Physics news on Phys.org
ineedhelpnow said:
i may have asked this before but what is the difference between and at(i)?

ex. courseGrades and courseGrades.at(i)


courseGrades is element number i of the array courseGrades kindly remember that element number starts at 0

where as courseGrades.at(i) is call to the function courseGrades.at with parameter i
 
so you can't call a function using courseGrades?
 
im confused. do you use to check through all the items in the list??
 
ineedhelpnow said:
im confused. do you use to check through all the items in the list??


The only difference is in general at(i) throws an exception if you attempt to access the vector at an out of bounds index, while does not (and just triggers undefined behaviour instead, but as a result cannot be slower than at(i)). Operators are just functions with a bit of syntactic sugar thrown on top of them, don't worry too much about operators looking different.
 
can someone please show me an example of that when to use and when to use at(i)? :o like a single line of code or something. it would make it a lot more clear...
 
ineedhelpnow said:
can someone please show me an example of that when to use and when to use at(i)? :o like a single line of code or something. it would make it a lot more clear...


You can use either whenever you want.
It's merely a matter of personal preference.
The one distinction there is, that relates to exceptions, is in practice not particularly relevant.

So you can do either:
Code:
#include <vector>
std::vector<int> v;

for (int i = 0; i < v.size(); ++i) {
  cout << v[i] << ", ";
}

or:
Code:
for (int i = 0; i < v.size(); ++i) {
  cout << v.at(i) << ", ";
}
(Wasntme)