Ébe Isaac Ébe Isaac - 25 days ago 11
C++ Question

How to store a value obtained from a vector `pop_back()` in C++?

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?

Answer

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();
Comments