F
F
fjaerj122021-09-25 16:05:58
C++ / C#
fjaerj12, 2021-09-25 16:05:58

Why doesn't std::set_intersection work?

std::set_intersection doesn't work in this example.
Input:
5
1 2 3 4 5
3
1 2 8
Output:
Should output 1 2, but only the empty string is output. When debugging, it becomes clear that the result multiset is empty.

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

int main()
{
    int lengthFirst = 0, lengthSecond = 0;
    std::cout << "Input a length of the first multiset ";
    std::cin >> lengthFirst;

    int value = 0;
    std::multiset<int> firstMultiset;
    for (int i = 0; i < lengthFirst; i++)
    {
        std::cout << "Input a value ";
        std::cin >> value;
        firstMultiset.insert(value);
    }

    std::cout << "Input a length of the second multiset ";
    std::cin >> lengthSecond;

    std::multiset<int> secondMultiset;
    for (int i = 0; i < lengthSecond; i++)
    {
        std::cout << "Input a value ";
        std::cin >> value;
        secondMultiset.insert(value);
    }

    std::multiset<int>result;
    std::multiset<int>::iterator iter;
    
    std::set_intersection(firstMultiset.begin(), firstMultiset.begin(), 
                              secondMultiset.begin(), secondMultiset.end(), std::inserter(result, result.begin()));

    for (iter = result.begin(); iter != result.end(); iter++) std::cout << *iter << " ";
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-09-25
@fjaerj12

in your code: std::set_intersection(firstMultiset.begin(), firstMultiset.begin ( )
should be: std::set_intersection(firstMultiset.begin(), firstMultiset.end ( ))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question