C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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)循环……

大佬总结

以上是大佬教程为你收集整理的c – 扩展std :: list全部内容,希望文章能够帮你解决c – 扩展std :: list所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。