简体   繁体   English

没有自然排序顺序的两个std :: vector之间的差异

[英]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 . 我正在寻找一种有效的方法来获取两个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. 这似乎排除了std::set_difference选项。

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. 您可以利用vector的属性,它们具有连续的内存分配,这意味着vector保留了一个大的内存空间(通常使用更大的内存,然后再使用),并且无需花哨的优化,就可以直接比较内存空间。

In C++0x, you have data() method, that give you direct access of the beginning of that memory space. 在C ++ 0x中,您具有data()方法,可以直接访问该内存空间的开始。 And you can use memcmp to compare all data inside vectors. 您可以使用memcmp比较向量中的所有数据。

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;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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