getting vector index?

Started by
6 comments, last by 3dmodelerguy 15 years, 11 months ago
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?
Advertisement
std::size_t index = vec.size();vec.push_back(item);// vec[index] == item
#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;}

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

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

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

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;
}
use [ source][/source] tags pls
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