Invalid Dog
Invalid Dog

Reputation: 43

I don't understand how to use set_difference correctly

In the task it was said that it is necessary to get the "value" of the largest elements from the array. Then it should be compared with the second array, and duplicates should be excluded.

In the task it is necessary to use partial_sort_copy in vector, and set_difference.

The problem is that when you start the program crashes at all, even without showing what exactly the error is, that's why I am writing here

I looked at several sites with examples of using this function, but I used everything as there, and do not quite understand why it does not work and crashes.

#include<iostream>
#include<vector>
#include <algorithm>

using namespace std;

int main() 
{
    int value = 5;
    int A_ints[] { 1, 4, 12, 5, 1, 4, 6, 9, 0, 3 };
    vector<int> A_vec(value);
    vector<int> B_vec { 13, 12, 11, 10 };
    vector<int> C_vec;
    vector<int> D_vec {9, 6, 5, 4};


    partial_sort_copy(A_ints, A_ints + 9, A_vec.begin(), A_vec.end(), greater<int>());

    set_difference(A_vec.begin(), A_vec.end(), B_vec.begin(), B_vec.end(), C_vec.begin(), greater<int>());


    if (С_vec == D_vec)
         cout << "Success \n";
    else
         cout << "Failure \n";

    system("pause");
    return 0;
}

As a result, if set_difference will works correctly, then the last condition should return "Success".

Upvotes: 0

Views: 696

Answers (1)

Jonathan Mee
Jonathan Mee

Reputation: 38939

The 5th argument to set_difference is the parameter that the results of the algorithm will be written to.

You've passed in C_vec.begin() which is an iterator pointing to an empty vector. It's undefined behavior to write to an empty vector's iterator.

You have several issues here, but one solution for this particular problem would be to replace C_vec.begin() with an insert_iterator:

inserter(C_vec, begin(C_vec))

Upvotes: 6

Related Questions