迭代 c++ 时无法访问 list<Object*> 中的元素

Not able to access to element in list<Object*> when iterating c++

本文关键字:Object gt 元素 c++ lt 访问 list 迭代      更新时间:2023-10-16

我想了解为什么这段代码不能完成这项工作。我想显示包含在 Table 中的列元素,但是当我运行它时,它卡住了,然后它什么也不显示。

#ifndef TABLE_H
#define TABLE_H
#include "Column.h"
using namespace std;
class Table : public BaseObject{
private:
    string address;
    string name;
    list<Column*> columns;
public:
    Table(string,string);
    Table(string,string,list<Column*>);
    virtual ~Table();
    void save(ostream&) const;
    static Table* read(ifstream&);
    string toString() const;
    list<Column*> getColumns() const;
    string getName() const;
    string getAddress() const;
};
#endif  /* TABLE_H */

.cpp文件

#include"Table.h"
Table::Table(string address, string name){
    this->address = address;
    this->name = name;
}
Table::Table(string address, string name, list<Column*> cols){
    this->address = address;
    this->name = name;
    this->columns = cols;
}
Table::~Table(){
}
string Table::toString() const{
    stringstream ss;
    ss << "nAddress: " << address
            << "nName: " << name 
            << "nColumns: ";
    list<Column*>::const_iterator i;
    for(i=columns.begin(); i != columns.end(); i++){
        ss << (*i)->toString();
    }
    return ss.str();
}

toString 函数只显示地址和名称,然后它停止显示任何内容,直到我打破它 Ctrl + C.提前感谢。总体上任何建议都会很棒。

这可能是重新分配问题。每次调用运算符<<都会强制字符串流调用 realloc(),后者调用系统以获取更多内存(连续区域)并从当前位置复制数据。虽然列数以直线形式增长(N 列),但字符串流存储呈指数级增长(它每次复制所有 N-1 列的内容)。大多数程序在类似情况下会变慢(或非常慢)。请尝试以下操作:1. 将 ss <<(*i)->更改为字符串();to cerr <<(*i)->toString();看看发生了什么以及你实际有多少列。2.如果您发现上述工作正确且快速(假设您没有在代码中罚款其他根本原因),请尝试更改为String接口和实现以避免字符串和字符串流。对于 exampe,Table 可以定义自己的迭代器。使用 Table::itrator 你可能不需要 toString(),这取决于代码如何使用 Table:: toString

相关文章: