std::sort排序std::list类型std::vector的效率及相关疑问
问题1:代码中std::sort排序的是指向list的指针吗?
不是。
代码中定义的vector类型为vector<list<int>>,存储的是std::list<int>的实例对象,而非指针。std::sort执行过程中交换的是std::list对象本身,比较器直接接收两个std::list的const引用做字典序比较,全程没有涉及指针操作。
问题2:排序存储容器(智能)指针的std::vector的最优实现方式是什么?
核心优化思路是:排序仅交换指针(内存开销极小),比较时解指针对实际容器内容做对比,避免按指针地址排序的错误逻辑,同时用智能指针管理容器生命周期避免内存风险。
具体实现要点:
- 优先选用
std::shared_ptr或std::unique_ptr封装容器,不要用裸指针 - 自定义比较器中先解引用指针,再对容器内容做
lexicographical_compare字典序比较 - 排序过程仅交换指针值,相比直接排序容器实例性能提升极明显,尤其适合存储大体积容器的场景
代码示例
#include <vector> #include <list> #include <algorithm> #include <memory> #include <iostream> using namespace std; template<typename T> inline void INSERT_ELEMENT(T& coll, int first, int last){ for(int i=first; i<=last; ++i) coll.insert(coll.end(), i); } template<typename T> inline void PRINT_ELEMENTS(const T& coll, const std::string& optcstr=""){ std::cout << optcstr; for(auto elem:coll) std::cout << elem << " "; std::cout << std::endl; } int main(){ list<int> c1, c2, c3, c4; INSERT_ELEMENT(c1, 1, 5); c2 = c3 = c4 = c1; c1.push_back(7); c3.push_back(2); c3.push_back(0); c4.push_back(2); // 改为存储智能指针的vector vector<shared_ptr<list<int>>> cc{ make_shared<list<int>>(c1), make_shared<list<int>>(c2), make_shared<list<int>>(c3), make_shared<list<int>>(c4), make_shared<list<int>>(c3), make_shared<list<int>>(c1), make_shared<list<int>>(c4), make_shared<list<int>>(c2) }; // 排序逻辑:仅交换指针,比较时解引用 sort(cc.begin(), cc.end(), [](const shared_ptr<list<int>>& first, const shared_ptr<list<int>>& second){ return lexicographical_compare( first->cbegin(), first->cend(), second->cbegin(), second->cend() ); }); // 输出结果 for(auto& ptr : cc){ PRINT_ELEMENTS(*ptr); } }
内容的提问来源于stack exchange,提问作者bst0612
相关产品推荐
相关产品推荐

