Reputation: 1169
I'm building a stack and queue class that are based on my Vector class. Each one, I need to call a function that will allow me to modify the value at that index.
For stack, that function is:
T &top()
However, I can't seem to modify this value, which is what my end goal is. Currently, I have removed the ampersands from the stack function, so the value can be displayed, but not modified.
When I include the ampersand on stack, or queue, the error is the same. So I assume the problem is the same, and I believe that it's syntax related
for ex.:
error C2440: 'return' : cannot convert from 'float' to 'float &'
Here is my Stack.h
template <class T>
class Stack{
private:
Vector<T> stack;
public:
void push(const T &x) {stack.push_back(x);}
void pop(){stack.pop_back();}
bool empty(){return stack.empty();}
int currentCapacity() const {return stack.currentCapacity();}
int size(){return stack.size();}
T &top() {return stack.back();}
};
Here is my Vector header file, and the function I'm calling in Stack:
#include<iostream>
using namespace std;
const int SIZEFACTOR = 4;
template <class T>
class Vector{
private:
unsigned int size_Of_Vector; // # of Items in list
unsigned int total_Vector_Capacity;//Total Capacity
T * vector_array;//Items themselves
public:
Vector();
~Vector();
void push_back(const T &e);
void pop_back();
void pop_front();
bool empty();
int size() const;
void growVector();
void shrinkVector();
void shrinkToSize();
int currentCapacity() const;
T back();
T front();
//Operator
const T & operator [] (int index){
if((index >= size_Of_Vector) || index < 0){
cout << "ERROR! Index not used: " << index
<< " (max = " << size_Of_Vector << ")" << endl;
return EXIT_FAILURE;
}
return vector_array[index];
};//End Operator
};//End Header Definition
template <class T>
T Vector<T>::back(){
if(size_Of_Vector == 0){
cout << "Vector is EMPTY" << endl;
return 0;
}
return vector_array[size_Of_Vector-1];//returns top
}
Anyone able to help point me in the right direction? The end goal I'm trying to reach is to be able to call something like: (Assuming that the template is int)
x.top() += 5;
And then have a modified value stored on the stack.
Upvotes: 2
Views: 279
Reputation: 16419
It is because you are passing back a copy of the object inside your vectors back
and front
methods, and not a reference.
void shrinkToSize();
int currentCapacity() const;
T back(); // < Copy returned from this method, should be T&
T front(); // < Same here!
Change the T
in the lines above to T&
and you should be good to go.
Upvotes: 5