views:

490

answers:

1

I am trying to find the set difference of two vectors, so i do something like this:

std::vector<sha1_hash> first_vec, second_vec, difference_vec;

// populate first_vec and second_vec ...

std::sort(first_vec.begin(),first_vec.end());
std::sort(second_vec.begin(),second_vec.end());

std::set_difference(first_vec.begin(),first_vec.end(),
         second_vec.begin(),second_vec.end(),
         difference_vec.begin());

When i run this in debug, i get the following run-time assertion failure (in 'vector'):

_SCL_SECURE_VALIDATE_RANGE(_Myptr < ((_Myvec *)(this->_Getmycont()))->_Mylast);

I am using VS 2008. Any ideas on what can trigger this?

+6  A: 

Like most c++ algorithms, set_difference does not create new entries in the output vector where none existed before. You ned to create space in the output to hold the results.

Edit: Or use an an insert iterator (following untested):

 back_insert_iterator< std::vector<sha1_hash> > bi( difference_vec ); 

std::set_difference(first_vec.begin(),first_vec.end(),
            second_vec.begin(),second_vec.end(),
            bi);
anon
Less verbose use of the back_insert_iterator:std::set_difference(first_vec.begin(), first_vec.end(), second_vec.begin(), second_vec.end(), std::back_inserter(difference_vec));
Éric Malenfant