c++ - 扩展 std::list

标签 c++ templates list linker

我需要为我的程序使用列表,并且需要决定我是使用 std::vector 还是 std::list。 vector 的问题是没有 remove 方法,而 list 的问题是没有 operator []。所以我决定编写自己的类,扩展 std::list 并重载 [] 运算符。

我的代码是这样的:

#include <list>

template <class T >
class myList : public std::list<T>
{
public:
T operator[](int index);
T operator[](int & index);
myList(void);
~myList(void);
};

#include "myList.h"

template<class T>
myList<T>::myList(void): std::list<T>() {}

template<class T>
myList<T>::~myList(void)
{
std::list<T>::~list();
}

template<class T>
T myList<T>::operator[](int index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;    
}

template<class T>
T myList<T>::operator[](int & index) {
int count = 0;
std::list<T>::iterator itr = this->begin();
while(count != index)itr++;
return *itr;
}

我可以编译它,但如果我尝试使用它,我会收到链接器错误。有什么想法吗?

最佳答案

根据您的需要,您应该使用std::vector(如果您需要经常在末尾添加/删除,以及随机访问),或者std::deque(如果您需要经常在结尾或开头添加/删除,并且您的数据集很大,并且仍然希望随机访问)。这是一张很好的图片,向您展示了如何做出决定:

Container Choice
(来源:adrinael.net)

关于c++ - 扩展 std::list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/366432/

相关文章:

c++ - 如何访问 OpenCV 匹配器上的点位置?

c++模板问题

c++ - 非常简单的可变参数函数的问题

R 将 data.frame 转换为按列列出

list - Lisp 列表中的不完整输出,# 给出的列表深度超过 4

c++ - 如何在 C++ 中提取二维数组的列?

c++ - 自行卸载的 Linux 共享库

c++ - 将 std::future 和 std::promise 与非 std::thread 一起使用是否安全?

javascript - 带 Twig 的模板 Nordemailer

list - "Generating Numbers"拼图