仅保留给定列表中不重复的元素.例如:(a b a a a c c) 给我们 (a b)

Leave only the elements that are not repeated in a given list. Ex: (a b a a a c c) gives us (a b)

本文关键字:例如 我们 元素 列表 保留      更新时间:2023-10-16

所以我需要能够在 c++ 中做到这一点。 我能够做的是使用"abaaacc"作为字符串,我得到了正确的答案,但是当"a b a a a c c"在链表中时,我不知道如何解决它。 有人可以帮我一个代码:

这是我的代码

#include <iostream>
using namespace std;
const int SIZE=20;
int main ()
{
    int numbs[SIZE], value, idx,n;
    cout<<"PLease enter size of an array"<<endl;
    cin>>n;
    cout << "Please enter in a series of numbers "<<endl;
    for(idx = 0; idx < n; idx++)
       cin >>numbs[idx];

    cout<< numbs[0] << " ";
for (int i = 1; i < n; i++)
{
    bool matching = false;
    for (int j = 0; (j < i) && (matching == false); j++)if (numbs[i] == numbs[j]) matching = true;
    if (!matching) cout<< numbs[i] << " ";
}   
}

现在我希望它删除相邻的重复项并给我 1 份副本

像前任一样,但使用数字,所以我如何能够编辑我的代码来做到这一点。

我有一些时间,所以我试图解决这个问题。

这确实是一件棘手的事情。您需要处理边缘情况的第一个和最后一个项目,以及 1-2 个项目列表。在这两者之间,您需要同时迭代三个迭代器,以在这些子集的中间找到唯一项。在处理列表时,您需要解决缺少的随机访问迭代器。

如今,我更习惯于Python,复杂的迭代很舒服,在这种情况下,您可以很好地摆脱zip和切片。也许新的范围可以用来完善这段代码。也许我会尝试一下。

#include <list>
#include <iostream>
std::list<char> remove_adjacent_duplicates(std::list<char> input) {
    std::list<char> output;
    std::list<char>::iterator first = input.begin();
    if (first == input.end()) {
        // no first, item, exit
        return output;
    }
    // let second point to second element
    std::list<char>::iterator second = input.begin();
    ++second;
    if (second == input.end()) {
        // no second item, insert first, then exit
        output.push_back(*first);
        return output;
    }
    // check first item
    if (*first != *second) {
        // first and second are different, insert first
        output.push_back(*first);
    }
    // let third point to third item
    std::list<char>::iterator third = input.begin();
    ++third; ++third;
    // check items up until the last
    while (third != input.end()) {
        if (*first != *second && *second != *third) {
            // the second item neither equals the first, nor the third
            // insert second
            output.push_back(*second);
        }
        // increment iterators
        ++first; ++second; ++third;
    }
    // finally, check the last item
    if (*first != *second) {
        // the last two items differ, insert the latter
        output.push_back(*second);
    }
    // done
    return output;  
}
void test_case(std::list<char> l) {
    std::list<char> output = remove_adjacent_duplicates(l);
    for (char i : l) {
        std::cout << i << ' ';
    }
    std::cout << " -> ";
    for (char i : output) {
        std::cout << i << ' ';
    }
    std::cout << 'n';
}
int main() {
    test_case({'a'});
    test_case({'a', 'b'});
    test_case({'a', 'b', 'a', 'a', 'a', 'c', 'c'});
}

输出为:

$ g++ test.cc -std=c++11 && ./a.out
a  -> a 
a b  -> a b 
a b a a a c c  -> a b 

很简单。首先,对容器进行 std::sort 处理,然后使用 std::unique(与 erase 结合使用(删除每个值的所有实例,但只有一个实例除外。

相关文章: