I'm not sure how to cast a value obtained from the pop_back()
function of vector
. The following is a simple code to illustrate the problem.
#include<vector>
#include<iostream>
using namespace std;
int main()
{
vector<int> a,b;
int val;
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
for(int i=0; i<4; i++)
{
val = a.pop_back();
b.push_back(val);
}
vector<int>::iterator v = b.begin();
while( v != b.end())
{
cout << *v << " ";
v++;
}
return 0;
}
This is the error I get.
pushback.cpp:18:9: error: assigning to 'int' from incompatible type 'void'
val = a.pop_back();
^ ~~~~~~~~~~~~
1 error generated.
I tried casting as well; (int)a.pop_back()
, but it throws an error stating C-style cast from 'void' to 'int' is not allowed
.
May I know if there is a standard way to store the value from the pop_back()
function?
It may sound as pop as in returning a value. But it actually doesn't. The standard says that vector::pop_back
should erase the last value, with no return value.
You can do:
auto val = a.back();
a.pop_back();
As stated in documentation std::vector::pop_back()
does not return any value, you just need to call std::vector::back()
right before:
val = a.back();
a.pop_back();
In case you have a vector
of objects and not just primitive types, moving out from the vector can be done with std::move
:
auto val = std::move(a.back()); // allow call of move ctor if available
a.pop_back();
Note that wrapping the call to back()
with std::move
is done only because we know that we are about to erase this element from the vector on the next line.
According to http://www.cplusplus.com/reference/vector/vector/pop_back/
The pop_back is void function, it is nonvalue-returning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With