development

C ++에서 두 std :: set의 교차점을 찾는 방법은 무엇입니까?

big-blog 2020. 10. 19. 08:17
반응형

C ++에서 두 std :: set의 교차점을 찾는 방법은 무엇입니까?


C ++에서 두 std :: set 사이의 교차점을 찾으려고했지만 계속 오류가 발생합니다.

이를 위해 작은 샘플 테스트를 만들었습니다.

#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;

int main() {
  set<int> s1;
  set<int> s2;

  s1.insert(1);
  s1.insert(2);
  s1.insert(3);
  s1.insert(4);

  s2.insert(1);
  s2.insert(6);
  s2.insert(3);
  s2.insert(0);

  set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end());
  return 0;
}

후자의 프로그램은 출력을 생성하지 않지만 s3다음 값을 가진 새 세트 (라고 부르겠습니다)를 가질 것으로 예상 합니다.

s3 = [ 1 , 3 ]

대신 오류가 발생합니다.

test.cpp: In function ‘int main()’:
test.cpp:19: error: no matching function for call to ‘set_intersection(std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>)’

이 오류에서 내가 이해하는 것은 매개 변수로 set_intersection받아들이는 정의가 없다는 것 Rb_tree_const_iterator<int>입니다.

또한 std::set.begin()메서드가 이러한 유형의 객체를 반환 한다고 가정합니다 .

std::setC ++에서 두 교차점을 찾는 더 좋은 방법이 있습니까? 가급적 내장 기능?

감사합니다!


set_intersection에 대한 출력 반복기를 제공하지 않았습니다.

template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator set_intersection ( InputIterator1 first1, InputIterator1 last1,
                                InputIterator2 first2, InputIterator2 last2,
                                OutputIterator result );

다음과 같이하여이 문제를 해결하십시오

...;
set<int> intersect;
set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(),
                  std::inserter(intersect,intersect.begin()));

std::insert세트가 현재 비어 있으므로 반복기 가 필요합니다 . set가 해당 작업을 지원하지 않으므로 back_ 또는 front_inserter를 사용할 수 없습니다.


링크의 샘플을 살펴보십시오 : http://en.cppreference.com/w/cpp/algorithm/set_intersection

교차 데이터를 저장하려면 다른 컨테이너가 필요합니다. 아래 코드는 작동한다고 가정합니다.

std::vector<int> common_data;
set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(), std::back_inserter(common_data));

std :: set_intersection을 참조하십시오 . 결과를 저장할 출력 반복기를 추가해야합니다.

#include <iterator>
std::vector<int> s3;
set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(), std::back_inserter(s3));

전체 목록 Ideone참조 하십시오.


여기에 댓글 만 달아주세요. 설정된 인터페이스에 유니온, 교차 연산을 추가 할 때라고 생각합니다. 이것을 향후 표준에서 제안합시다. 나는 오랫동안 std를 사용해 왔는데, set 작업을 사용할 때마다 std가 더 좋기를 바랐습니다. intersect와 같은 복잡한 집합 작업의 경우 다음 코드를 간단하게 (쉽게?) 수정할 수 있습니다.

template <class InputIterator1, class InputIterator2, class OutputIterator>
  OutputIterator set_intersection (InputIterator1 first1, InputIterator1 last1,
                                   InputIterator2 first2, InputIterator2 last2,
                                   OutputIterator result)
{
  while (first1!=last1 && first2!=last2)
  {
    if (*first1<*first2) ++first1;
    else if (*first2<*first1) ++first2;
    else {
      *result = *first1;
      ++result; ++first1; ++first2;
    }
  }
  return result;
}

http://www.cplusplus.com/reference/algorithm/set_intersection/ 에서 복사

예를 들어, 출력이 세트 인 경우 output.insert (* first1)을 사용할 수 있습니다. 또한 함수가 템플릿 화되지 않을 수 있습니다. 코드가 std set_intersection 함수를 사용하는 것보다 짧을 수 있다면 계속 진행하십시오.

두 세트의 합집합을 수행하려면 간단히 setA.insert (setB.begin (), setB.end ()); 이것은 set_union 메소드보다 훨씬 간단합니다. 그러나 이것은 벡터에서는 작동하지 않습니다.


수락 된 답변 의 첫 번째 (잘 투표 된) 의견은 기존 표준 집합 작업에 대한 누락 된 연산자에 대해 불평합니다.

한편으로는 표준 라이브러리에 그러한 연산자가 없다는 것을 이해합니다. 다른 한편으로, 원하는 경우 (개인의 기쁨을 위해) 쉽게 추가 할 수 있습니다. 나는 과부하

  • operator *() 세트의 교차
  • operator +() 세트의 결합을 위해.

샘플 test-set-ops.cc:

#include <algorithm>
#include <iterator>
#include <set>

template <class T, class CMP = std::less<T>, class ALLOC = std::allocator<T> >
std::set<T, CMP, ALLOC> operator * (
  const std::set<T, CMP, ALLOC> &s1, const std::set<T, CMP, ALLOC> &s2)
{
  std::set<T, CMP, ALLOC> s;
  std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(),
    std::inserter(s, s.begin()));
  return s;
}

template <class T, class CMP = std::less<T>, class ALLOC = std::allocator<T> >
std::set<T, CMP, ALLOC> operator + (
  const std::set<T, CMP, ALLOC> &s1, const std::set<T, CMP, ALLOC> &s2)
{
  std::set<T, CMP, ALLOC> s;
  std::set_union(s1.begin(), s1.end(), s2.begin(), s2.end(),
    std::inserter(s, s.begin()));
  return s;
}

// sample code to check them out:

#include <iostream>

using namespace std;

template <class T>
ostream& operator << (ostream &out, const set<T> &values)
{
  const char *sep = " ";
  for (const T &value : values) {
    out << sep << value; sep = ", ";
  }
  return out;
}

int main()
{
  set<int> s1 { 1, 2, 3, 4 };
  cout << "s1: {" << s1 << " }" << endl;
  set<int> s2 { 0, 1, 3, 6 };
  cout << "s2: {" << s2 << " }" << endl;
  cout << "I: {" << s1 * s2 << " }" << endl;
  cout << "U: {" << s1 + s2 << " }" << endl;
  return 0;
}

컴파일 및 테스트 :

$ g++ -std=c++11 -o test-set-ops test-set-ops.cc 

$ ./test-set-ops     
s1: { 1, 2, 3, 4 }
s2: { 0, 1, 3, 6 }
I: { 1, 3 }
U: { 0, 1, 2, 3, 4, 6 }

$ 

내가 싫어하는 것은 연산자의 반환 값 복사본입니다. 아마도 이것은 이동 할당을 사용하여 해결할 수 있지만 이것은 여전히 ​​내 기술을 벗어납니다.

Due to my limited knowledge about these "new fancy" move semantics, I was concerned about the operator returns which might cause copies of the returned sets. Olaf Dietsche pointed out that these concerns are unnecessary as std::set is already equipped with move constructor/assignment.

Although I believed him, I was thinking how to check this out (for something like "self-convincing"). Actually, it is quite easy. As templates has to be provided in source code, you can simply step through with the debugger. Thus, I placed a break point right at the return s; of the operator *() and proceeded with single-step which leaded me immediately into std::set::set(_myt&& _Right): et voilà – the move constructor. Thanks, Olaf, for the (my) enlightment.

For the sake of completeness, I implemented the corresponding assignment operators as well

  • operator *=() for "destructive" intersection of sets
  • operator +=() for "destructive" union of sets.

Sample test-set-assign-ops.cc:

#include <iterator>
#include <set>

template <class T, class CMP = std::less<T>, class ALLOC = std::allocator<T> >
std::set<T, CMP, ALLOC>& operator *= (
  std::set<T, CMP, ALLOC> &s1, const std::set<T, CMP, ALLOC> &s2)
{
  auto iter1 = s1.begin();
  for (auto iter2 = s2.begin(); iter1 != s1.end() && iter2 != s2.end();) {
    if (*iter1 < *iter2) iter1 = s1.erase(iter1);
    else {
      if (!(*iter2 < *iter1)) ++iter1;
      ++iter2;
    }
  }
  while (iter1 != s1.end()) iter1 = s1.erase(iter1);
  return s1;
}

template <class T, class CMP = std::less<T>, class ALLOC = std::allocator<T> >
std::set<T, CMP, ALLOC>& operator += (
  std::set<T, CMP, ALLOC> &s1, const std::set<T, CMP, ALLOC> &s2)
{
  s1.insert(s2.begin(), s2.end());
  return s1;
}

// sample code to check them out:

#include <iostream>

using namespace std;

template <class T>
ostream& operator << (ostream &out, const set<T> &values)
{
  const char *sep = " ";
  for (const T &value : values) {
    out << sep << value; sep = ", ";
  }
  return out;
}

int main()
{
  set<int> s1 { 1, 2, 3, 4 };
  cout << "s1: {" << s1 << " }" << endl;
  set<int> s2 { 0, 1, 3, 6 };
  cout << "s2: {" << s2 << " }" << endl;
  set<int> s1I = s1;
  s1I *= s2;
  cout << "s1I: {" << s1I << " }" << endl;
  set<int> s2I = s2;
  s2I *= s1;
  cout << "s2I: {" << s2I << " }" << endl;
  set<int> s1U = s1;
  s1U += s2;
  cout << "s1U: {" << s1U << " }" << endl;
  set<int> s2U = s2;
  s2U += s1;
  cout << "s2U: {" << s2U << " }" << endl;
  return 0;
}

Compiled and tested:

$ g++ -std=c++11 -o test-set-assign-ops test-set-assign-ops.cc 

$ ./test-set-assign-ops
s1: { 1, 2, 3, 4 }
s2: { 0, 1, 3, 6 }
s1I: { 1, 3 }
s2I: { 1, 3 }
s1U: { 0, 1, 2, 3, 4, 6 }
s2U: { 0, 1, 2, 3, 4, 6 }

$

참고URL : https://stackoverflow.com/questions/13448064/how-to-find-the-intersection-of-two-stdset-in-c

반응형