0

我需要将 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:\projects\c++\wolvesisland\consoleapplication6\consoleapplication6\myvector.h(24): 错误 C2664: 'std::_Vector_iterator<_Myvec> std::vector<_Ty>::erase(std::_Vector_const_iterator<_Myvec >)' : 无法将参数 1 从 'obiekt **' 转换为 'std::_Vector_const_iterator<_Myvec>'

我试图擦除的方式:data.Remove(2); 其中数据是 myVector <对象> 数据;应用程序代码很好(我只使用 std::vector 对其进行了测试,而没有将其放入模板)。我会感谢你的帮助。

4

2 回答 2

3

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

可能的更正可能是

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

虽然我没有直接测试它。

于 2013-06-07T18:08:27.170 回答
2

矢量擦除函数只接受迭代器。

vec.erase(vec.begin()+ItemKey);
于 2013-06-07T18:12:39.433 回答