查找两个排序向量中共有的元素

Finding the elements common among two sorted vectors

本文关键字:元素 向量 排序 两个 查找      更新时间:2023-10-16

我需要编写一个函数,该函数接受对向量的常量引用,并返回数字的升序向量。

我有两个整数的排序向量作为参数,并且需要仅使用<vector>标头查找所有常见元素。

对此有什么想法吗?我想不通。

因为元素是有序的,所以你只需要跳过它们一次。

使用每个迭代器,如果两个范围都不在末尾,则继续

如果两个元素都不小于另一个元素,则它们相等,您可以将一个元素写入结果。

否则,您需要推进指向较小元素的迭代器。

查看 std::set_intersection 的可能实现

template<class InputIt1, class InputIt2, class OutputIt>
OutputIt set_intersection(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
OutputIt d_first)
{
while (first1 != last1 && first2 != last2) {
if (*first1 < *first2) {
++first1;
} else  {
if (!(*first2 < *first1)) {
*d_first++ = *first1++;
}
++first2;
}
}
return d_first;
}

让我们将其适应"只有<vector>"规则

#include <vector>
template <typename T>
std::vector<T> set_intersection(const std::vector<T> & one, const std::vector<T> & two)
{
std::vector<T> result;
std::vector<T> const_iterator first1 = one.begin(), last1 = one.end(), first2 = two.begin(), last2 = two.end();
while (first1 != last1 && first2 != last2) {
if (*first1 < *first2) {
++first1;
} else  {
if (!(*first2 < *first1)) {
result.push_back(*first1++);
}
++first2;
}
}
return result;
}

尽管Caleths的答案是绝对有效的,但您可能是初学者,并且可能想要一种更简单的方法(用于学习语言等(。

这将是:

std::vector<int> find_same_ints(const std::vector<int> &vec1, const std::vector<int> &vec2)
{
std::vector<int> results;
//Check if same number exists in the both vector arguments, if so, push the number to results
for(int x : vec1)
for(int y : vec2)
if(x == y)
results.push_back(x);
//Simple bubblesort algorithm
for(std::size_t x = 0; x < results.size(); x++)
{
int lowestValueIndex = x;
//Try to find the lowest value of the remaining not sorted values
for(std::size_t y = x + 1; y < results.size(); y++)
if(results[y] < results[lowestValueIndex])
lowestValueIndex = y;
//Swap the values
int temp = results[lowestValueIndex];
results[lowestValueIndex] = results[x];
results[x] = temp;
}
//Return sorted vector
return results;
}

请记住,Caleths算法是您在获得语言经验并了解代码中实际发生的事情时应该使用的算法。