Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 228
Ébe Isaac Avatar asked Nov 09 '16 05:11

Ébe Isaac


4 Answers

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();
like image 113
themagicalyang Avatar answered Nov 19 '22 02:11

themagicalyang


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();
like image 33
Slava Avatar answered Nov 19 '22 01:11

Slava


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.

like image 36
Amir Kirsh Avatar answered Nov 19 '22 03:11

Amir Kirsh


According to http://www.cplusplus.com/reference/vector/vector/pop_back/

The pop_back is void function, it is nonvalue-returning.

like image 31
khôi nguyễn Avatar answered Nov 19 '22 01:11

khôi nguyễn