c++ - 使用集合对 vector 进行排序

标签 c++ vector stl set

vector <int> v1(6);
//some procedure to fill the vector v1 with ints.
set <int> s(v1);
vector <int> v2(s)

此处“v2”将包含与“v1”相同的元素,但按升序排序。此排序过程的时间复杂度是多少。 set s 以排序的形式存储整数。

最佳答案

将数据从 vector 复制到 set 会比较慢,因为这将涉及在堆上创建数据结构(通常是红黑树),而排序可以就地完成(有效地使用堆栈作为临时数据存储)。

#include <iostream>
#include <vector>
#include <set>

size_t gAllocs;
size_t gDeallocs;

void * operator new ( size_t sz )   { ++gAllocs; return std::malloc ( sz ); }
void   operator delete ( void *pt ) { ++gDeallocs; return std::free ( pt ); }

int main () {
    gAllocs = gDeallocs = 0;
    std::vector<int> v { 8, 6, 7, 5, 3, 0, 9 };
    std::cout << "Allocations = " << gAllocs << "; Deallocations = " << gDeallocs << std::endl;
    std::set<int> s(v.begin(), v.end());
    std::cout << "Allocations = " << gAllocs << "; Deallocations = " << gDeallocs << std::endl;
    std::sort ( v.begin(), v.end ());
    std::cout << "Allocations = " << gAllocs << "; Deallocations = " << gDeallocs << std::endl;

    return 0;
    }

在我的系统(clang、libc++、Mac OS 10.8)上,打印:

$ ./a.out 
Allocations = 1; Deallocations = 0
Allocations = 8; Deallocations = 0
Allocations = 8; Deallocations = 0

构建集合需要 7 次内存分配(每个条目一次)。对 vector 进行排序不需要花费任何时间。

关于c++ - 使用集合对 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17900651/

相关文章:

c++ - 看不懂这段代码?这是关于在 C++ 中读取文件

c++ - 如何从当前可执行文件中获取函数地址?

c++ - 如何使用 C++ 以二进制模式将 vector 写入文件?

c++ - 如何解决模板问题以将不同的数据类型保存到文件中?

c++ - 保留存储在 STL 容器中的指针指向的值 (unordered_map)

C++ 处理队列溢出

c++ - 为什么cin.get()卡在换行符上?

c++ - 将 vector < vector <Point>> x 变换为 vector <Point> y

java - 同一个对象的两个不同的同步方法?

c++ - C++ STL vector 保留太多容量会消耗大量内存吗?