Jump to content
  • Advertisement
Sign in to follow this  
3dmodelerguy

getting vector index?

This topic is 3724 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
#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;
}

Share this post


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

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!