简体   繁体   English

将std :: sets合并到std :: vector中

[英]Merging std::sets into std::vector

Consider the following. 考虑以下。

I have two std::set s and want to merge them in the std::vector in sorted order. 我有两个std::set s并希望按排序顺序将它们合并到std::vector中。

Which is the most effective way to do that? 哪种方法最有效?

I did something like this, but I think that there must be a better way of doing it. 我做了类似的事情,但我认为必须有更好的方法。

std::set<int> S1;
std::set<int> S2;
// ....
// Initialization of sets
// ....

std::vector V;

std::set<int>::iterator iter;

for(iter = S1.begin(); iter!=S1.end(); ++iter)
{
    V.push_back(*iter);
}

for(iter = S2.begin(); iter!=S2.end(); ++iter)
{
    V.push_back(*iter);
}

std::sort(V.begin(), V.end());

Here is my code, is there more effective way? 这是我的代码,有更有效的方法吗? Thanks in advance. 提前致谢。

std::merge should do the trick, since S1 and S2 are sorted: std :: merge应该可以解决问题,因为S1和S2是排序的:

// Initialization of sets
// ....
std::vector V;

std::merge(S1.begin(), S1.end(), S2.begin(), S2.end(), std::back_inserter(V));

// instead of V.begin() -- thanks for the correction. //而不是V.begin() - 感谢您的纠正。

I believe you can simplify your code by using std::copy() : 我相信你可以使用std::copy()来简化你的代码:

std::copy(S1.begin(), S1.end(), std::back_inserter(V));
std::copy(S2.begin(), S2.end(), std::back_inserter(V));
std::sort(V.begin(), V.end());

The sets are already sorted, so it does seem wasteful to re-sort it all again at the end. 这些集已经排序,因此最后再次对它进行重新排序似乎很浪费。

How about something like this (left a couple of TODOs as an excercise for the reader!): 这样的事情怎么样(留下几个TODO作为读者的练习!):

  std::set<int>iterator S1iter = S1.begin();
  std::set<int>iterator S1iter = S2.begin();

  while( S1iter != S1.end() && S2iter != S2.end() ) {

    if( S1iter == S1.end() ) {
       //TODO:  S1 is finished, so push back range S2iter->S2.end()
       //       onto the vector
       break;
    }
    else if( S2iter == S2.end() ) {
       //TODO:  S2 is finished, so push back range S1iter->S1.end()
       //       onto the vector
       break;
    }
    else if( *S1iter < *S2iter ) {
      V.push_back( *S1iter );
      ++S1iter;
    }
    else {
      V.push_back( *S2iter );
      ++S2iter;
    }

  }

You can use std::merge(): http://en.cppreference.com/w/cpp/algorithm/merge 您可以使用std :: merge(): http//en.cppreference.com/w/cpp/algorithm/merge

Its implementation is similar to yours. 它的实现类似于你的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM