c++ - 对我的类(class)实现删除功能

标签 c++ visual-c++ boost c++11 stl

我正在尝试为我的方形列表函数实现删除函数,但是当我编写我的函数时,它给我这个编译器错误

Error 1 error C2664: 'square_list::erase' : cannot convert parameter 1 from 'std::_List_iterator<_Mylist>' to 'int *'

主要代码

#define nullptr NULL
template <typename T_>
class square_list
{



    void erase(iterator it)
    {
        data.erase(it);
    }


};

最佳答案

std::list<T>::erase将 list::iterator 作为参数,但您试图将其传递给 square_list<T>::iterator , a.k.a. T* .

我会质疑将迭代器定义为 T* 的逻辑对于 squared_list<T> ,同时暴露list<T>::iterator s 到公共(public)接口(interface)(begin() 和 `end()1) 中的基础列表,因为这会破坏封装。

不过,如果你想继续,你可以这样做:

void erase(typename std::list<T>::iterator it)
{
    data.erase(it);
}

或者,如果您想实际使用您在 squared_list 中定义的迭代器类:

void erase(iterator it)
{
    // look for the underlying list iterator pointing to this value
    auto underlyingIt = std::find_if(data.begin(), data.end(), [=](const T& node) {
       return (&node == it);  
    });
    if (underlyingIt != data.end()) {
         data.erase(underlyingIt);
    } else {
         // handle case where the "iterator" is not found here 
    }
}

关于c++ - 对我的类(class)实现删除功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21844829/

相关文章:

c++ - cv::remap segfaults with std::thread

c++ - 在服务器上处理来自 WebRTC 对等连接的音频流

c++ - 在 ifstream 中使用运算符 '>>' 的编译器错误

c++ - Boost 最新版本兼容 VC++6 是什么?

c++ - std::thread 是 boost::thread 的替代品吗?

c++ - 如何为显式重载构造函数启用复制初始化?

c++ - 如何在编译时检查类型

visual-c++ - 如何将clang-tidy与CMake(<LANG> _CLANG_TIDY)和MSVC集成?

c++ - 具有不同字符大小的 spirit::qi::grammar-name

c++ - 来自 boost::async() 的 boost::future<> 类型