I'm trying to write an array wrapper class for a project. Everything is working ok, except I'm not able to assign values ( array[i] = value; ) that already exist in the array, I keep getting "expression must be a modifyable lvalue". I tried to overload the assignment operator but had no luck.
#include "stdafx.h"
#include <vector>
template <typename T>
inline bool operator==(const T left, const T right)
{
return &left == &right;
}
template <typename T>
class TArray {
std::vector<T> data;
public:
TArray() { }
void Reserve(unsigned int space)
{
if (space == 0)
{
return;
}
data.reserve(space);
}
/**
* Adds a value
*/
void Add(T value)
{
data.push_back(value);
}
/**
* Adds the value if it does not already exist
*/
void AddUnique(T value)
{
if (Contains(value))
{
return;
}
Add(value);
}
/**
* Removes the first value in the array matching the value
*/
void Remove(T value)
{
std::vector<T>::iterator itr = std::find(data.begin(), data.end(), value);
if (itr != data.end())
{
data.erase(itr);
}
}
/**
* Removes all matching the type
*/
void RemoveAllMatching(T value)
{
for (int i = data.size(); i >= 0; i--)
{
if (data[i] == value)
{
data.erase(i);
}
}
}
/**
* Removes value at index
*/
void RemoveAtIndex(int index)
{
if (index > data.size() - 1)
{
return;
}
data.erase(index);
}
/**
* Returns true if the array contains the object
*/
bool Contains(T value)
{
for (T v : data)
{
if (v == value)
{
return true;
}
}
return false;
}
/**
* Returns the number of the same value
*/
int ContainsQuantity(T value)
{
int quantity = 0;
for (T v : data)
{
if (v == value)
{
++quantity;
}
}
return quantity;
}
void Clear() { data.clear(); }
typename std::vector<T>::const_iterator begin() const { return data.begin(); }
typename std::vector<T>::const_iterator end() const { return data.end(); }
int Size() { return data.size(); }
T operator[](int index) { return data[index]; }
};
Any help would be much appreciated!
You apply the []
operator.
Then you attempt to assign to what that returns.
What it returns is a copy of T
, because of T operator[](int index) { return data[index]; }
T operator[](int index) { return data[index]; }
.
You'd have to return a reference.
As kindly pointed out by HolyBlack Cat, it would be almost needed to also have
a second
operator[]
that'sconst
and returnsconst T &
because
It just allows you to call
[]
on const objects/references to read the values.
Eg if you define a const version of what you are implementing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.