C ++中n个排序数组的有效联合(集合与向量)?

时间:2018-10-03 19:35:29

标签: c++ algorithm performance

我需要实现一种有效的算法,以便从多个排序的数组中查找一个排序的联合。由于我的程序会执行许多此类操作,因此我使用C ++进行了模拟。我的第一种方法(method1)是简单地创建一个空向量,并将其他向量中的每个元素附加到该空向量上,然后使用std :: sort和std :: unique获得所有元素的想要排序的并集。但是,我认为将所有矢量元素转储到集合(方法2)中可能会更有效,因为集合已经使它们变得唯一并可以一次性排序。令我惊讶的是method1比method2快5倍!我在这里做错什么了吗? method2是否应该更快,因为它执行较少的计算?预先感谢

//// method1带有向量:

std::vector<long> arr1{5,12,32,33,34,50};
std::vector<long> arr2{1,2,3,4,5};
std::vector<long> arr3{1,8,9,11};

std::vector<long> arr;

int main(int argc, const char * argv[]) {

double sec;
clock_t t;
t=clock();
for(long j=0; j<1000000; j++){ // repeating for benchmark
    arr.clear();
    for(long i=0; i<arr1.size(); i++){
        arr.push_back(arr1[i]);
    }
    for(long i=0; i<arr2.size(); i++){
        arr.push_back(arr2[i]);
    }
    for(long i=0; i<arr3.size(); i++){
        arr.push_back(arr3[i]);
    }
    std::sort(arr.begin(), arr.end());
    auto last = std::unique(arr.begin(), arr.end());
    arr.erase(last, arr.end());
}
t=clock() - t;
sec = (double)t/CLOCKS_PER_SEC;
std::cout<<"seconds = "<< sec <<" clicks = " << t << std::endl;

return 0;
}

//// method2带有设置:

std::vector<long> arr1{5,12,32,33,34,50};
std::vector<long> arr2{1,2,3,4,5};
std::vector<long> arr3{1,8,9,11};

std::set<long> arr;

int main(int argc, const char * argv[]) {

double sec;
clock_t t;
t=clock();
for(long j=0; j<1000000; j++){ //repeating for benchmark
    arr.clear();
    arr.insert(arr1.begin(), arr1.end());
    arr.insert(arr2.begin(), arr2.end());
    arr.insert(arr3.begin(), arr3.end());
}
t=clock() - t;
sec = (double)t/CLOCKS_PER_SEC;
std::cout<<"seconds = "<< sec <<" clicks = " << t << std::endl;

return 0;
}

2 个答案:

答案 0 :(得分:3)

这是使用2个向量完成的方法。您可以轻松地将过程概括为N个向量。

vector<int> v1{ 4, 8, 12, 16 };
vector<int> v2{ 2, 6, 10, 14 };

vector<int> merged;
merged.reserve(v1.size() + v2.size());

// An iterator on each vector
auto it1 = v1.begin();
auto it2 = v2.begin();

while (it1 != v1.end() && it2 != v2.end())
    {
    // Find the iterator that points to the smallest number.
    // Grab the value.
    // Advance the iterator, and repeat.

    if (*it1 < *it2)
        {
        if (merged.empty() || merged.back() < *it1)
            merged.push_back(*it1);
        ++it1;
        }
    else
        {
        if (merged.empty() || merged.back() < *it2)
            merged.push_back(*it2);
        ++it2;
        }
    }

while(it1 != v1.end())
    {
    merged.push_back(*it1);
    ++it1;
    }

while (it2 != v2.end())
    {
    merged.push_back(*it2);
    ++it2;
    }

// if you print out the values in 'merged', it gives the expected result
[2, 4, 6, 8, 10, 12, 14, 16]

...并且您可以概括以下内容。请注意,同时包含“当前”迭代器和最终迭代器的帮助程序结构会更清洁,但思路仍然相同。

vector<int> v1{ 4, 8, 12, 16 };
vector<int> v2{ 2, 6, 10, 14 };
vector<int> v3{ 3, 7, 11, 15 };
vector<int> v4{ 0, 21};

vector<int> merged;
// reserve space accordingly...

using vectorIt = vector<int>::const_iterator;

vector<vectorIt> fwdIterators;
fwdIterators.push_back(v1.begin());
fwdIterators.push_back(v2.begin());
fwdIterators.push_back(v3.begin());
fwdIterators.push_back(v4.begin());
vector<vectorIt> endIterators;
endIterators.push_back(v1.end());
endIterators.push_back(v2.end());
endIterators.push_back(v3.end());
endIterators.push_back(v4.end());

while (!fwdIterators.empty())
    {
    // Find out which iterator carries the smallest value
    size_t index = 0;
    for (size_t i = 1; i < fwdIterators.size(); ++i)
        {
        if (*fwdIterators[i] < *fwdIterators[index])
            index = i;
        }

    if (merged.empty() || merged.back() < *fwdIterators[index])
        merged.push_back(*fwdIterators[index]);

    ++fwdIterators[index];
    if (fwdIterators[index] == endIterators[index])
        {
        fwdIterators.erase(fwdIterators.begin() + index);
        endIterators.erase(endIterators.begin() + index);
        }
    }

// again, merged contains the expected result
[0, 2, 3, 4, 6, 7, 8, 10, 11, 12, 14, 15, 16, 21]

...正如一些人指出的那样,使用堆甚至会更快

// Helper struct to make it more convenient
struct Entry
{
vector<int>::const_iterator fwdIt;
vector<int>::const_iterator endIt;

Entry(vector<int> const& v) : fwdIt(v.begin()), endIt(v.end()) {}
bool IsAlive() const { return fwdIt != endIt; }
bool operator< (Entry const& rhs) const { return *fwdIt > *rhs.fwdIt; }
};


int main()
{
vector<int> v1{ 4, 8, 12, 16 };
vector<int> v2{ 2, 6, 10, 14 };
vector<int> v3{ 3, 7, 11, 15 };
vector<int> v4{ 0, 21};

vector<int> merged;
merged.reserve(v1.size() + v2.size() + v3.size() + v4.size());

std::priority_queue<Entry> queue;
queue.push(Entry(v1));
queue.push(Entry(v2));
queue.push(Entry(v3));
queue.push(Entry(v4));

while (!queue.empty())
    {
    Entry tmp = queue.top();
    queue.pop();

    if (merged.empty() || merged.back() < *tmp.fwdIt)
        merged.push_back(*tmp.fwdIt);

    tmp.fwdIt++;

    if (tmp.IsAlive())
        queue.push(tmp);
    }

不过,似乎确实复制了很多“ Entry”对象,对于 std :: priority_queue 来说,具有适当比较功能的条目指针可能会更好。 >

答案 1 :(得分:3)

合并多个队列的通常方法是根据队列中第一个元素的值将其放入最小堆中。您反复从堆顶部的队列中拉出一个项目,然后将其向下推以恢复堆属性。

这将在O(N log K)时间内合并总共N个项目K个队列。

由于要合并vector<int>,因此队列可以是tuple<int, vector *>(当前位置和向量)或tuple<vector::const_iterator, vector::const_iterator>(当前位置和结束)