0
Best way to access vector element
Hi I know that [] on vector is fastest to access element like i did in trial1 function. But in my actual case of code, i dont have gurantee that index will be in range and i would not have issues. So, best way is to use .at() method we have in trial2 method of code. Nut i heard that it is 3 to 4 times slow than direct access through [] I cant afford that much performance hit and obviously cant always go with [] operator. Is it always best to check size first and then access element using [] like we have in trial3 method ? Whats the performance analysis of it compared to [] and .at() ? https://code.sololearn.com/cC0iDQjb6iN9/?ref=app
2 ответов
+ 1
I think the use of vector.at() is less to be able to throw and catch error when index is OOB, but more in that it makes it easier to catch bugs in your code. With [] operator you'll get UB when index is OOB, but with vector.at(), you'll get an error.
With vector.at() you would using a conditional to check if index is in bounds anyways, because most of the times, a try-catch block is not viable. So it's best to to always make sure that the index is in bounds when it's not obvious, even when using vector.at()
IMO it's better to use the [] operator and turn on bounds checking through compiler-specific options/macros in Debug mode. In Release mode, you can just turn those options off.
0
Thanks XXX