Home > Software design >  Get the last element from a std::vector
Get the last element from a std::vector

Time:01-25

In the following example, I would like to get an element from my vector. But I don't understand the error:

#include <vector>
#include <memory>


using namespace std;

class Foo{
    virtual int end() = 0;
};

class Bar : public Foo{
    int end(){
        return 0;
    }
};


int main(){
    vector<shared_ptr<Foo>> a;
    a.push_back(make_shared<Bar>());
    shared_ptr<Foo> b = a.pop_back();
}

Here the error:

 g   test.cpp
test.cpp: In function ‘int main()’:
test.cpp:21:35: error: conversion from ‘void’ to non-scalar type ‘std::shared_ptr<Foo>’ requested
   21 |     shared_ptr<Foo> b = a.pop_back();
      |                         ~~~~~~~~~~^~

CodePudding user response:

This is indeed confusing. As said kiner_shah in his comment. You don't want to use pop_back

int main(){
    vector<shared_ptr<Foo>> a;
    a.push_back(make_shared<Bar>());
    shared_ptr<Foo> b = a.back();
}

The pop_back method doesn't return anything.

CodePudding user response:

Find the last element from std::vector -
back() - access the last element

int main(){
vector<shared_ptr<Foo>> a;
a.push_back(make_shared<Bar>());
shared_ptr<Foo> b = a.back();}

don't be use a.pop_back() which is use for delete the last element in the std::vector.

  •  Tags:  
  • Related