想象一下:我有一个 JSON 文件,其中包含一个包含类型列表的Node
对象列表。Link
就像是:
node1:
links: node1,node2
node3,node1
node1,node6
node2:
links: node2,node1
node2,node9
node7,node2
我需要识别唯一的链接对 - 即一(node_a,node_b)
对。注意,(node_b,node_a)
代表的是同一个东西。
该类Link
具有返回指向 source/destination 的指针的 getter 方法Node
。在该文件中,有关链接的信息存储为具有source
节点名称和destination
节点名称的字符串,例如:(source,destination)
.
当我从文件构建结构时,我首先创建,Nodes
然后才创建Links
. 构造Link
函数如下:
Link::Link(Node *fromNode, Node *toNode)
还有我创建链接的代码:
QList<Link*> consumedLinks; // list where I was trying to place all the non-duplicate links
// for each node in the file
foreach(QVariant nodesMap, allNodesList){
QVariantMap node1 = nodesMap.toMap();
QList<QVariant> nodeDetails = node1["node"].toList();
QVariantMap allLinksMap = nodeDetails.at(9).toMap();
// extract all the links of the node to a list of QVariant
QList<QVariant> linksList = allLinksMap["links"].toList();
// for each Link in that list
foreach(QVariant linkMap, linksList){
QVariantMap details = linkMap.toMap();
Node *savedFromNode;
Node *savedToNode;
// get all the Items in the scene
QList<QGraphicsItem*> itemList = scene->items();
// cast each item to a Node
foreach(QGraphicsItem *item, itemList){
Node* tempNode = qgraphicsitem_cast<Node*>(item);
if(tempNode){
// check what the node name matches in the link list
if(tempNode->text()==details["fromNode"]){
savedFromNode = tempNode;
}
if(tempNode->text()==details["toNode"]){
savedToNode = tempNode;
}
}
}
// create the link
Link *linkToCheck = new Link(savedFromNode,savedToNode);
// add it to the links list (even if duplicate)
consumedLinks.append(linkToCheck);
}
}
// add all the links as graphics items in the scene
foreach(Link *linkToCheck, consumedLinks){
scene->addItem(linkToCheck);
}
所以现在这不会检查consumedLinks
列表中的重复项(显然)。关于如何实现这一目标的任何想法?
注意:我知道上面的伪 JSON 无效,只是为了让您了解结构。
NOTE2:我重新措辞并在问题中添加了细节和代码,以便更清楚地理解我需要什么。