Hello,
How do I remove the last entry of an int vector?
Thanks.
What have you tried? Did you at least find and read the documentation for std::vector?
I tried pop_back but I'm not quite sure what it did, and no, I didn't read the documentation.
Seriously man, read the documentation.
It clearly says:
vector::pop_back
Removes the last element in the vector, effectively reducing the container size by one.
The contents of my vector are:
0,3,1,0,3
but after pop_back I get:
0,3,0
It is not a problem with pop_back. This code works for me:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <iostream>
#include <vector>
template<typename T>
void PrintVector(std::vector<T> inVec)
{
for(std::vector<T>::iterator it = inVec.begin();
it != inVec.end();
++it)
{
std::cout << (*it) << "\n";
}
}
int main(int argc, char *argv[])
{
std::vector<int> intVec;
intVec.push_back(0);
intVec.push_back(3);
intVec.push_back(1);
intVec.push_back(0);
intVec.push_back(3);
PrintVector(intVec);
int lastEntry = intVec.back();
std::cout << "Getting ready to remove " << lastEntry << " from the vector.\n";
intVec.pop_back();
PrintVector(intVec);
return 0;
}
| |
Last edited on
booradley60, thanks, I'll look for the problem in my code.