getting vector index?
Ok lets say I have just inserted a element into my vector with push_back(). let say there was already 3 elements in there so that mean this new one is at index 3 and accessing it would me vector[3]. How can i find that out through the code?
#include <iostream>#include <vector>int main(){ std::vector<int> data; data.push_back(10); data.push_back(20); if(data.size() > 0) { std::cout << data[data.size()-1] << std::endl; } return 0;}
Since you're adding things to the end of the vector, the index of the most recently added item is just the last item in the vector - vector.size() - 1.
I should ask: why do you need the index of the last element? If you just want to access it you can using the member function back() like this:
#include <iostream>#include <vector>int main(){ std::vector<int> data; data.push_back(10); data.push_back(20); std::cout << data.back() << std::endl; return 0;}
int main() {
using namespace std;
vector <int> v1;
v1.push_back( 10 );
v1.push_back( 11 );
int& i = v1.back( );
const int& ii = v1.front( );
cout << "The last integer of v1 is " << i << endl;
i--;
cout << "The next-to-last integer of v1 is "<< ii << endl;
}
using namespace std;
vector <int> v1;
v1.push_back( 10 );
v1.push_back( 11 );
int& i = v1.back( );
const int& ii = v1.front( );
cout << "The last integer of v1 is " << i << endl;
i--;
cout << "The next-to-last integer of v1 is "<< ii << endl;
}
Quote:Original post by nobodynews
I should ask: why do you need the index of the last element? If you just want to access it you can using the member function back() like this:
Becuase if i add 5 things and then what the 3 element, I need to keep track of that I totally forgot about size() function. Thanks.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement