扩展std :: list [英] Extending std::list

查看:176
本文介绍了扩展std :: list的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to use lists for my program and needed to decide if I use std::vector or std::list. The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.

我的代码看起来像这样:

My code looks like this:

#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;
}



我可以编译它但是我得到一个链接器错误,如果我试图使用它。任何想法?

I can compile it but I get a linker error if I try to use it. Any ideas?

推荐答案

所有模板代码都应放在头文件中。这个填充修复链接问题(这是最简单的方法)。
发生的原因是因为编译器将每个源(.cc)文件与其他文件分开编译。另一方面,它需要知道什么代码正确地需要创建(即什么是模板中的T被替换),并且没有其他方式知道它,除非程序员明确地告诉它或包含所有的代码当模板实例化发生。也就是说当编译mylist.cc时,它不知道mylist用户和需要创建什么代码。另一方面,如果listuser.cc被编译,并且所有mylist代码存在,编译器创建所需的mylist代码。您可以在这里或Stroustrup中了解详情。

All template code should be put in header file. This fill fix linking problems (that's the simplest way). The reason it happens is because compilers compiles every source (.cc) file separately from other files. On the other hand it needs to know what code exactly it needs to create (i.e. what is the T in template is substituted with), and it has no other way to know it unless the programmer tells it explicitly or includes all the code when template instantiation happens. I.e. when mylist.cc is compiled, it knows nothing about mylist users and what code needs to be created. On the other hand if listuser.cc is compiled, and all the mylist code is present, the compiler creates needed mylist code. You can read more about it in here or in Stroustrup.

您的代码有问题,如果用户请求否定或太大(超过列表中的元素数量)。

Your code has problems, what if user requests negative or too large (more than amount of elements in the list). And i didn't look too much.

此外,我不知道u计划如何使用它,但是你的操作符[]是O(N)这可能很容易导致O(N * N)循环...

Besides, i don't know how u plan to use it, but your operator[] is O(N) time, which will probably easily lead to O(N*N) loops...

这篇关于扩展std :: list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆