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

时间:2018-10-19 15:00:34

标签: c++ vector

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

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

有什么想法吗?我不知道。

2 个答案:

答案 0 :(得分:1)

因为元素是有序的,所以只需要传递一次即可。

每个都有迭代器,如果两个范围都不在末尾则继续进行

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

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

查看std::set_intersection

的可能实现
delta = df.Close.diff()
window = 15
up_days = delta.copy()
up_days[delta<=0]=0.0
down_days = abs(delta.copy())
down_days[delta>0]=0.0
RS_up = up_days.rolling(window).mean()
RS_down = down_days.rolling(window).mean()
rsi= 100-100/(1+RS_up/RS_down)

让我们适应“ 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>

答案 1 :(得分:0)

尽管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算法,这是在您获得有关该语言的经验并了解代码中实际发生的事情后应该使用的算法。

相关问题