【发布时间】:2019-12-01 09:18:03
【问题描述】:
我最近在实施某些事情时遇到了这个问题。我有一个自定义的树状结构,其中包含一个值和一个子向量。插入子节点时,我希望它们以随机顺序出现,并且我需要跟踪插入的最后一个元素以供将来的某些操作使用。事实证明,如果我保存一个指向最后一个节点的向量的指针,在对向量进行排序后,指针仍然有效,但它现在指向一个完全不同的向量。这是一个最小的例子:
#include <iostream>
#include <vector>
#include <algorithm>
struct Node {
int value;
std::vector<Node> nxt;
bool operator<(const Node& other) {
return value < other.value;
}
/* Having this custom swap function doesn't make a difference
*friend void swap(Node& lhs, Node& rhs) {
* std::swap(lhs.value, rhs.value);
* lhs.nxt.swap(rhs.nxt);
*}
*/
};
int main() {
Node node1;
node1.value = 1;
Node node2;
node2.value = 2;
Node node3;
node3.value = 3;
Node node4;
node4.value = 4;
std::vector<Node> container;
container.push_back(node2);
container.push_back(node1);
container.push_back(node4);
container.push_back(node3);
std::vector<Node>* node3_vec = &container.back().nxt;
node3_vec->push_back(node1);
std::cout << "Address of the vector: " << node3_vec << std::endl;
std::cout << "Size of the vector: " << node3_vec->size() << std::endl;
std::sort(container.begin(), container.end());
std::cout << "Address of the vector post sort: " << node3_vec << std::endl;
std::cout << "Size of the vector post sort: " << node3_vec->size() << std::endl;
//Inside the container
std::cout << "Value of the node inside the container: " << container[2].value << std::endl;
std::cout << "Address of the vector: " << &container[2].nxt << std::endl;
std::cout << "Size of the vector: " << container[2].nxt.size() << std::endl;
return 0;
}
我尝试使用一些自定义的std::swap 实现,但我似乎无法改变这种行为。我怎样才能使它在排序后,指向向量的指针指向同一个向量?目前,我在排序后执行额外的搜索以找到所需的元素。
也有人可以向我指出一些解释这种行为的文档吗?
【问题讨论】:
-
@stark,插入所有元素后,我的向量将具有恒定长度。它永远不会扩大或缩小。
标签: c++ sorting swap stdvector