从不使用的 2 个向量(或列表)<algorithm>中删除相似元素

Remove similar elements from 2 vectors (or list) not using <algorithm>

本文关键字:algorithm lt gt 元素 相似 删除 列表 向量      更新时间:2023-10-16

我想从2个向量(或列表)中删除类似的元素。我在这里发现了一个类似的问题,他用<algorimth>来解决这个问题。我的问题是有没有其他不使用<algorimth>的方法?

我的是我创建一个向量来保存公共元素的索引,然后删除具有"标记"索引的元素。疯狂的想法,但这不是工作。

示例:

Vector A={1,2,3,4,5};
Vector B={2,3,4,6};
Vector result={1,5};  

这是一个已经注意排序和唯一输入的列表的解决方案。

//
#include "stdafx.h"
#include <list>
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int A_arrey[] = { 1, 2, 4, 5, 7, 8 };
    int B_arrey[] = { 1, 2, 3, 5, 6, 8, 9 };
    list<int> A_list(A_arrey, A_arrey + 6);
    list<int> B_list(B_arrey, B_arrey + 7);
    A_list.sort();
    A_list.unique();
    B_list.sort();
    B_list.unique();
    for (int i = 0; i < sizeof(A_arrey) / sizeof(A_arrey[0]); i++)
        B_list.remove(A_arrey[i]);
    for (int i = 0; i < sizeof(B_arrey) / sizeof(B_arrey[0]); i++)
        A_list.remove(B_arrey[i]);
    A_list.merge(B_list);
    cout << "My list contains:";
    for (list<int>::iterator it = A_list.begin(); it != A_list.end(); it++)
        std::cout << ' ' << *it;
    cout << 'n';
}

在所有值都是唯一且已排序的情况下,可以使用以下操作:

#include <iostream>
#include <vector>
using namespace std;
vector<int> A={1,2,3,4,5};
vector<int> B={2,3,4,6};
vector<int> result;

int main()
{
    int a = 0;
    int b = 0;
    while(a < A.size() && b < B.size())
    {
        /* Same value - skip to next on both sides */
        if (A[a] == B[b])
        {
            a++;
            b++;
        }
        else 
            /* Smaller value is unique, so push back that */
            if (A[a] < B[b])
            {
                result.push_back(A[a]);
                a++;
            }
            else
            {
                result.push_back(B[b]);
                b++;
            }
    } 
    while (a < A.size())
    { 
        result.push_back(A[a]);
        a++;
    }
    while (b < B.size())
    { 
        result.push_back(B[b]);
        b++;
    }
    for(auto r : result)
    {
        cout << r << ", ";
    }
    cout << endl;
    return 0;
}

还有许多其他方法。如果值不是很大,可以使用数组在遇到A中的值时向上计数,然后在遇到B时向下计数,然后在完成时遍历计数器数组以给出唯一值列表。

编辑:更新了完整的"工作"代码。

我想你需要这样的东西:

vector<T> v(SIZE);
T tmp=v[0];
// ... Fill your vector here
for(int i=0;i<SIZE;++i)
    v[i]==tmp?v.erase(i):tmp=v[i];