Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ QList与QVector行为_C++_Qt_Memory Management_Qlist_Qvector - Fatal编程技术网

C++ QList与QVector行为

C++ QList与QVector行为,c++,qt,memory-management,qlist,qvector,C++,Qt,Memory Management,Qlist,Qvector,我有一个QTreeView由一个qabstractemmodel子类提供服务,该子类是在自定义树数据模型上构建的。数据模型的定义如下: struct InventoryNode { // ctors, operator definitions // ... InventoryItem inventoryItem; // node data QList<InventoryNode> children; // child no

我有一个
QTreeView
由一个
qabstractemmodel
子类提供服务,该子类是在自定义树数据模型上构建的。数据模型的定义如下:

struct InventoryNode
{
    // ctors, operator definitions
    // ...

    InventoryItem inventoryItem;         // node data
    QList<InventoryNode> children;       // child nodes
    InventoryNode *parent = nullptr;     // parent pointer
};

class InventoryModel : public QAbstractItemModel
{
    Q_OBJECT

public:
    struct InventoryNode;
    QList<InventoryNode> _nodes;             // root nodes

    // required model methods
    // ...
}
当我尝试展开\折叠节点时,
searchList.indexOf(*targetNode)在没有任何反馈的情况下使程序崩溃。我想更深入地挖掘并重写搜索,以获得更多关于发生了什么的信息,显然
Q_ASSERT(position!=searchList.end())此条件失败

现在,我已经阅读了一些关于QVector和QList之间差异的信息,包括非常有用的讨论。我确实理解两者之间的主要区别,并且感觉主要原因是内存管理中的一些怪癖,但我仍然很难弄清楚为什么会发生这种情况


有人能解释一下吗?

应该没有什么区别,因为在代码中,您没有显示内存分配或删除。对于向量和列表接口以及迭代器,使用相同的方法。对我来说,只有一件奇怪的事
QList\u节点不是指针列表,而是在
findRow()
中使用
std::find(searchList.begin()、searchList.end()、*targetNode)
如果
short if
语句返回您的
\u节点
,该怎么办?嗯)这正是我感到困扰的原因,应该没有任何区别,因为两者的行为和API都是相同的,但只要我使用
QVector
而不是
QList
,程序就会崩溃。至于指针,我需要使用一个指向节点的指针,以便能够从
索引
void*
内部指针
对其进行强制转换<代码>\u节点
如果
分支将处理树根=)
QModelIndex InventoryModel::parent(const QModelIndex &index) const
{
    if (!index.isValid()) {
        return QModelIndex();
    }

    InventoryNode *currentNode = static_cast<InventoryNode *>(index.internalPointer());

    InventoryNode* parentNode = currentNode->parent;
    if (parentNode != nullptr) {
        return createIndex(findRow(parentNode), BranchColumn, parentNode);
    }
    else {
        return QModelIndex();
    }
}

int InventoryModel::findRow(const InventoryNode *targetNode) const
{
    const InventoryNodeList searchList = targetNode->parent != nullptr ? targetNode->siblings() : _nodes;
//    return searchList.indexOf(*targetNode);
    InventoryNodeList::const_iterator position = std::find(searchList.begin(), searchList.end(), *targetNode);
//    Q_ASSERT(position != searchList.end());
    return std::distance(searchList.begin(), position);
}