使用集排序矢量

时间:2013-07-27 17:34:29

标签: 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'相同的元素,但按升序排序。这将是此排序过程的时间复杂度。以排序的形式设置商店。

1 个答案:

答案 0 :(得分:1)

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

#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个内存分配(每个条目一个)。对矢量进行排序不需要。