dear experts,
This question is an extension of this question I asked.
I have a std::vector vec_B
.which stores instances of class Foo
. The order of elements in this vector changes in the code.
Now, I want to access the value of the current "last element" or current 'nth' element of the vector. If I use the code below to get the last element using getLastFoo()
method, it doesn't return the correct value.
For example, to begin with the last element of the vector has Foo.getNumber() = 9
. After sorting it in descending order of num
, for the last element, Foo.getNumber() = 0
.
But with the code below, it still returns 9.. that means it is still pointing to the original element that was the last element.
What change should I make to the code below so that "lastFoo
" points to the correct last element?
class Foo {
public:
Foo(int i);
~Foo(){};
int getNum();
private:
int num;
};
Foo:Foo(int i){
num = i;
}
int Foo::getNum(){
return num;
}
class B {
public:
Foo* getLastFoo();
B();
~B(){};
private:
vector<Foo> vec_B;
};
B::B(){
int i;
for (i = 0; i< 10; i++){
vec_B.push_back(Foo(i));
}
// Do some random changes to the vector vec_B so that elements are reordered. For
// example rearrange elements in decreasing order of 'num'
//...
}
Foo* B::getLastFoo(){
return &vec_B.back();
};
int main(){
B b;
Foo* lastFoo;
lastFoo = b.getLastFoo()
cout<<lastFoo->getNumber();
return 0;
}