在C ++中保持数组的唯一元素

时间:2015-11-22 12:24:48

标签: c++ arrays unique

我在C ++中有两个长度相同的数组。我想得到两个新的数组:第一个新数组将具有第一个原始数组的唯一元素,而第二个数组将具有第二个原始数组的相应值。例如:

原件:

1st:1 7 2 3 5 4 4 8 9 9 4 6 7

第二名:1 1 1 2 2 2 3 3 3 4 4 5 5

我希望得到:

1st:1 7 2 3 5 4 8 9 6

第二名:1 1 1 1 2 2 3 3 5

也许我可以使用哈希表,但不太确定如何做到这一点。任何解决方案都可以。在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

以下两种方法代表了相当普遍的解决方案类型:

  1. 制作单个数组,并排序+统一:

    int a[N], b[N];  // ... your data
    
    std::vector<std::pair<int, int>> v({{a[0], b[0]}, /*...*/, {a[N-1], b[N-1]}});
    
    std::sort(
        v.begin(), v.end(),
        [](const auto & lhs, const auto & rhs) { return lhs.first < rhs.first; });
    auto it = std::unique(
        v.begin(), v.end(),
        [](const auto & lhs, const auto & rhs) { return lhs.first == rhs.first;});
    v.erase(it, v.end());
    

    现在av[i].first的{​​{1}}的唯一值为i,而[0, v.size())的相应条目b分别为v[i].second

  2. 通过间接排序和统一索引数组:

    std::vector<std::size_t> idx({0, 1, 2, /* ... */, N - 1});
    
    std::sort(
        idx.begin(), idx.end(),
        [&a](std::size_t i, std::size_t j) { return a[i] < a[j]; });
    auto it = std::unique(
        v.begin(), v.end(),
        [&a](std::size_t i, std::size_t j) { return a[i] == a[j]; });
    v.erase(it, v.end());
    

    现在,a中的a[idx[i]]的唯一值位于[0, v.size())中,而b中的b[idx[i]]的相应值位于Sub Filter_and_move_data() Dim LastRow As Long Sheets("Parsing").UsedRange.Offset(0).ClearContents With Worksheets("Incidents_data") .Range("$A:$G").AutoFilter .Range("$A:$G").AutoFilter field:=1, Criteria1:="=Status Changed", Operator:=xlOr LastRow = .Range("A" & .Rows.Count).End(xlUp).Row .Range("A1:G" & LastRow).SpecialCells(xlCellTypeVisible).Copy _ Destination:=Sheets("Parsing").Range("A1") End With End Sub

相关问题