myVector类 - 擦除

时间:2013-06-07 18:03:26

标签: c++

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

我试图擦除的方式:data.Remove(2);数据是myVector&lt;对象&gt;数据; 应用程序代码很好(我只使用std :: vector测试它而不将其放到模板中)。我很感谢你的帮助。

2 个答案:

答案 0 :(得分:3)

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

可能的修正可能是

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

虽然我没有亲自测试。

答案 1 :(得分:2)

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

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