简体   繁体   中英

Difference between two std::vectors with no natural sorting order

I am looking for an efficient way to obtain the difference between two std::vectors . The objects they contain don't have any natural ordering; the best I can do is test for equality. This seems to rule out the std::set_difference option.

Is there a better solution than to compare the objects inside two nested iterators?

The goal is to reduce the number of equality test, by grouping possible positive matches together.

The best I can think of is to build a hashmap with the first vector, and then substract all the elements of the second vector from the hashmap. This means that you need to come up with a decent hash function for your elements.

Trivially, if you are storing pointers, and that your equality predicate is based on it, you could also base your hash on that pointer integral value.

See What is a good hash function? .

As mentioned in the comments, an alternate possibility is to establish an ordering on certain attributes of the elements, and use that to reduce the possibilities of equality. You may have to sort both vectors first.

You can take advantage of a property of vectors, they have contiguous memory allocation, that means, vector have a one big memory space reserved (bigger then used, normally), and without fancy optimizations, you can compare directly memory spaces.

In C++0x, you have data() method, that give you direct access of the beginning of that memory space. And you can use memcmp to compare all data inside vectors.

std::vector<char> vector_1;
std::vector<char> vector_2;

// data in to vector_1
// data in to vector_2

if(!memcmp(vector1.data(),vector_2.data(),SIZE_OF_BUFFER_TO_COMPARE))
{
    std::cout <<< "equal vectors" << std::endl;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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