How to add negative index functionality for std::vector? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to add negative index functionality for std::vector?

Python can do negative indexes to start indexing from the last element. How can it be implemented in c++?

22nd Apr 2017, 3:30 PM
Bebida Roja
Bebida Roja - avatar
2 Answers
23rd Apr 2017, 11:45 AM
Bebida Roja
Bebida Roja - avatar
+ 1
You cannot use negative indexes in c++. However, if you wish to read a vector from the last element, you can use a reversed for loop like this: int size = 5; std::vector<int> myvector = {1,2,3,4,5}; for(int i = myvector.size() - 1; i >= 0; --i) cout << myarr[i] << endl; output: 5 4 3 2 1
23rd Apr 2017, 2:53 AM
Bill Fosam
Bill Fosam - avatar