查找两个排序向量中共有的元素
Finding the elements common among two sorted vectors
我需要编写一个函数,该函数接受对向量的常量引用,并返回数字的升序向量。
我有两个整数的排序向量作为参数,并且需要仅使用<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算法是您在获得语言经验并了解代码中实际发生的事情时应该使用的算法。
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- C++:如何循环通过向量中的整数元素
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 不允许在向量中添加更多元素
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 使用并行参数向量调用元素向量的成员函数
- C++ 查找字符串中存在的元素向量
- 包含 std::threads 的元素向量
- 避免从单一元素向量转换为基元类型
- 对自定义元素向量进行排序时出现意外(至少对我来说)行为
- 如何为对元素(向量和int)配对创建unique_ptr也是unique_ptr
- 元素向量乘法 C++(代码不起作用)
- 时间和空间复杂性在二叉树的每个级别创建元素向量(NON-BST)
- 遍历结构元素向量
- 犰狳C++中的元素向量或矩阵乘法
- 为什么'std::vector<int> b{2};'创建 1 元素向量,而不是 2 元素向量?
- 可移动元素向量的大小调整是否有效?
- 唯一元素向量的c++模板函数
- 获取索引和元素-向量问题
- 定义一个生成元素向量的函数时,正确的方法是什么?