myVector class - erasing

myVector class - erasing

本文关键字:erasing class myVector      更新时间:2023-10-16

我需要把std::vector放到模板类中。除了擦除

之外,一切正常。
#include <vector>
using namespace std;
template <class TBase> 
class TCollection
{
protected:
  //The Vector container that will hold the collection of Items
  vector<TBase> m_items;
public:
  int Add(void) 
  {
    //Create a new base item
    TBase BaseItem; 
    //Add the item to the container
    m_items.push_back(BaseItem); 
    //Return the position of the item within the container. 
    //Zero Based
    return (m_items.size()-1); 
  }
  //Function to return the memory address of a specific Item
  TBase* GetAddress(int ItemKey) 
  {
    return &(m_items[ItemKey]);
 }
  //Remove a specific Item from the collection
  void Remove(int ItemKey) 
  {
    //Remove the Item using the vector’s erase function
    m_items.erase(GetAddress(ItemKey)); 
  }
  void Clear(void) //Clear the collection
  {
    m_items.clear();
  }
  //Return the number of items in collection
  int Count(void) 
  {
    return m_items.size(); //One Based
  }
  //Operator Returning a reference to TBase
  TBase& operator [](int ItemKey) 
  {
    return m_items[ItemKey];
  }
};

我得到错误:

1>b:projectsc++wolvesislandconsoleapplication6consoleapplication6myvector.h(24): error C2664: 'std::_Vector_iterator<_Myvec> std:: vector_iterator <_Myvec>::erase(std::_Vector_const_iterator<_Myvec>)':无法将参数1从'obiekt **'转换为'std::_Vector_const_iterator<_Myvec>'

我试图删除的方式:data.Remove(2);其中数据为myVector data;应用程序代码很好(我只使用std::vector进行测试,没有将其放入模板)。我将感激你的帮助。

erase方法只接受迭代器,不接受指针作为参数。看这里。

可能的修正是

std::vector<TBase>::const_iterator it = m_items.begin() + ItemKey;
m_items.erase(it);

虽然我没有亲自测试

vector erase函数只接受迭代器。

vec.erase(vec.begin()+ItemKey);