【问题标题】:Is it possible to use list like array?是否可以使用类似数组的列表?
【发布时间】:2021-01-11 10:50:21
【问题描述】:

我想问一下,是否可以让列表像数组一样工作?

我的意思是如何重载 [] 运算符以使其像在数组中一样工作。

我读过一些代码。例如,当我们想要的时候 -打印记忆单元:cout

  • 变量的左手赋值:b = abc[0];

但不能右手使用:abc[0] = 5; 而且我不知道如何确定数组的大小

#include <iostream>
#include <list>
#include <iterator>


using namespace std;

template<class type>
class My_array
{
    public:
    list<type> List;
    

    void add(type element)
    {
        List.push_back(element);
    }
    
    void dele()
    {
        List.pop_back();
    }
    
    type operator [](int i)
    {
        typename list<type>::iterator iter; 
        int counter = 0;
        
        for(iter = this->List.begin(); iter != this->List.end(); iter++)
        {
            if(counter == i) break;
            
            counter++;
        }
        
        
        return *iter;
        
    }
   
   My_array &operator = (My_array &k)
    {
        
        if(this == &k) return *this;
        
        
        return *this;
    }
    


};




int main()
{
    My_array<int> abc;
    abc.add(5);
    
    int b = 7;
    
    
    cout<<abc[0]<<endl;
    b = abc[0];
    cout<<b<<endl;
 
    
   
   
    
    return 0;
}

【问题讨论】:

  • 就算可以,为什么要专门用list呢?为什么不是向量?
  • 仅供参考 std::next() 对推进迭代器很有用。
  • 它(显然,因为您的代码演示了它)是可能的。现在为什么没有为现有的标准列表做?因为它效率低下。如果你提供一些看起来很简单的随机访问,人们会使用它并认为它很简单。它不是,他们不应该。
  • 因为我了解模板和重载,这是一项很好的任务
  • @kaniaramiawest 是的,编写自己的容器是一个很好的练习

标签: c++ list


【解决方案1】:

您可以修改重载以返回对元素的引用。

    type& operator [](int i) // add & to make it return a reference

【讨论】:

    【解决方案2】:

    简单的改变

    type operator [](int i)
    

    type& operator [](int i)
    

    它适用于访问和分配!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 2017-09-14
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      相关资源
      最近更新 更多