微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 扩展std :: list

我需要为我的程序使用列表,并需要决定是否使用std :: vector或std :: list.
向量的问题在于没有删除方法,并且列表中没有运算符[].所以我决定编写自己的类来扩展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;
}

我可以编译它,但如果我尝试使用它,我会收到链接错误.有任何想法吗?

解决方法

所有模板代码都应放在头文件中.这个填充修复链接问题(这是最简单的方法).
它发生的原因是因为编译器将每个源(.cc)文件与其他文件分开编译.另一方面,它需要知道它需要创建什么样的代码(即模板中的T被替换为什么),除非程序员明确地告诉它或者包含模板中的所有代码,否则没有其他方法可以知道它.实例化发生了.即当编译mylist.cc时,它对mylist用户一无所知,需要创建什么代码.另一方面,如果编译了listuser.cc,并且存在所有的mylist代码,则编译器会创建所需的mylist代码.您可以在 here或Stroustrup中阅读更多相关信息.

您的代码有问题,如果用户请求负数或太大(超过列表中的元素数量)会怎样.而且我看起来并不太多.

此外,我不知道你打算如何使用它,但你的运算符[]是O(N)时间,这可能很容易导致O(N * N)循环……

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐