【发布时间】:2021-02-07 04:58:30
【问题描述】:
我对向量和模板非常陌生。似乎还不能把我的头绕在他们身上。 代码如下:
template <class T>
class m_vector
{
int m_iNextIndex;
int m_iMaxSize;
T* m_pArray;
public:
m_vector()
{
m_pArray = 0;
init();
}
m_vector(const m_vector<T>& other)
{
m_pArray = 0;
m_iNextIndex = 0;
m_iMaxSize = 0;
*this = other;
}
~m_vector()
{
if (m_pArray != 0)
delete [] m_pArray;
}
void init()
{
m_iMaxSize = VECT_INC_SIZE;
m_pArray = new T[m_iMaxSize];
m_iNextIndex = 0;
}
inline void push_back(const T& item)
{
if (m_iNextIndex >= m_iMaxSize)
{
resize(m_iNextIndex + VECT_INC_SIZE);
m_iNextIndex -= VECT_INC_SIZE;
}
m_pArray[m_iNextIndex] = item;
++m_iNextIndex;
}
void resize(int iNewSize)
{
if (iNewSize >= m_iMaxSize)
{
T* temp = new T[iNewSize];
for (int i = 0; i < m_iNextIndex; ++i)
{
temp[i] = m_pArray[i];
}
delete [] m_pArray;
m_pArray = temp;
m_iMaxSize = iNewSize;
}
m_iNextIndex = iNewSize;
}
};
push_back 使用 (x, y) 向量和 (x, y, width, height) 矩形调用。 我认为由于代码具有“m_pArray [m_iNextIndex] = item”,因此我可以简单地添加一个新函数来检查该项目是否唯一,然后再将其添加到向量列表中。所以我编写了一个例程如下:
int inline exists(const &item)
{
for(int i = 0; i < m_iMaxSize; i++)
{
if(m_pArray[i] == item)
return 1;
}
return 0;
}
编译器不高兴。它在if语句上报告了以下错误: “左操作数必须是指针或指向类成员的指针,或算术”
我想我可能需要类似的东西:
if (type == vector)
if( (m_pArray[i].x == item.x) ....)
else
if( (m_pArray[i].x == item.x) && (m_pArray[i].width == item.width) )
我在正确的轨道上吗? 如果是这样,我如何检查项目的类型。
谢谢,比尔。
【问题讨论】:
-
exists(const &item) -
你能告诉我们你是如何使用你的班级的吗?
-
请复制完整的错误信息。
-
当我编译提供的代码时,我得到的第一个错误是
ISO C++ forbids declaration of 'item' with no type(参见 bipll 的评论)。一旦我解决了这个问题并且缺少VECT_INC_SIZE的定义,代码就会编译。虽然最好将minimal reproducible example 中的代码最小化,但该示例仍然需要重现问题。 -
该问题可能是由
Vector和Rectangle类没有相等比较运算符引起的。例如。friend bool operator==(Vector& lhs, Vector& rhs);.
标签: c++ templates vector unique