Sign in to follow this  
3dmodelerguy

getting vector index?

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites
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;
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this