迭代 c++ 时无法访问 list<Object*> 中的元素
Not able to access to element in list<Object*> when iterating c++
我想了解为什么这段代码不能完成这项工作。我想显示包含在 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
相关文章:
- EASTL矢量<向量<int>>连续的
- 当覆盖存在时调用基本虚拟"binded to object"函数
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- C++将派生类转换为基类时'object slicing'期间发生的情况
- 如何理解 C++17 标准参考中的 [intro.object]/3? N4659 的
- "Cannot convert Python object argument to type '<typename>'" - 使用 Cython 包装 C++ 类时出错
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- "Called Object Type is Not a Function or Pointer" 与 typedef 和类
- C++线程"Call to non-static member function without an object argument"
- dopen():不以 root 身份运行时"failed to map segment from shared object"
- 当两个成员位于同一类中时出错"a nonstatic member reference must be relative to a specific object"
- Nan::ObjectWrap to Napi::Object Wrap 无法访问 JavaScript 中的属性
- 现代C++会支持 C# "Object Initalizer"语法吗?
- 指向对象生存期之外的已分配内存的指针是"invalid pointer[s]"还是"pointer[s] to an object"?
- C++ Equivalent of Java Map<String, Object>
- WebKit2GTK+ "window-object-cleared"未清除
- 返回 *&object 时是否允许复制/移动省略?
- QPointer::clear() 是删除其引用的指针,还是"Clears this QPointer object."其他含义?
- 解决方法:'can not be used when making a shared object; recompile with -fPIC'使用Cmake。使用普通的 g++ 工作
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型