如何删除 std::vector 中的直接邻居

问题描述 投票:0回答:1

假设我有一个 std::vector。 MyStruct 定义如下:

     typedef struct
     {
         int nIndex; 
         float fValue;
     } MyStruct;

现在,当索引 (nIndex) 彼此相邻时,我想从向量中删除 MyStruct。该向量已按索引 (nIndex) 排序。

例如,如果我有以下 std::vector:

vector<MyStruct> v { { 2, 8.0 }, { 4, 9.0 }, { 7, 4.0 }, { 8, 7.0 }, { 10, 3.0 } }; 

我需要这个结果:

vector<MyStruct> v { { 2, 8.0 }, { 4, 9.0 }, { 7, 4.0 }, { 10, 3.0 } }; 

因此,由于两个索引彼此相邻,因此删除了第二个索引。

在更复杂的情况下,我有几个彼此相邻的索引。在这种情况下,除了中间的 MyStruct 之外的每个 MyStruct 都应该被删除:

vector<MyStruct> v { { 2, 8.0 }, { 4, 9.0 }, { 7, 4.0 }, { 8, 7.0 }, { 9, 6.0 }, { 10, 2.0 }, { 12, 7.0 }, { 14, 5.0 }, { 15, 8.0 }, { 18, 9.0 } };

想要的结果:

vector<MyStruct> v { { 2, 8.0 }, { 4, 9.0 }, { 8, 7.0 }, { 12, 7.0 }, { 14, 5.0 }, { 18, 9.0 } };

在本例中,索引为 7、9、10 和 15 的元素被删除。

我该如何解决这个问题。我尝试使用相邻差异并检查索引之差是否为一来解决此问题。但我失败了很多次。

c++ vector
1个回答
0
投票

不确定这是否正是您想要的,但下面的代码可能是一个解决方案。

#include <vector>

typedef struct {
  int nIndex;
  float fValue;
} MyStruct;


int main() {
  std::vector<MyStruct> v { { 2, 8.0 }, { 4, 9.0 }, { 7, 4.0 }, { 8, 7.0 }, { 9, 6.0 }, { 10, 2.0 }, { 12, 7.0 }, { 14, 5.0 }, { 15, 8.0 }, { 18, 9.0 } };

  for(auto it = v.begin(); it != v.end() - 1 && it != v.end();) {
    if((it + 1)->nIndex - it->nIndex == 1) {
      it = v.erase(it + 1);
    } else {
      it++;
    }
  }

  for(const auto& s : v) {
    printf("{ %d, %f }, ", s.nIndex, s.fValue);
  }
  printf("\n");
}

打印:

{ 2, 8.000000 }, { 4, 9.000000 }, { 7, 4.000000 }, { 9, 6.000000 }, { 12, 7.000000 }, { 14, 5.000000 }, { 18, 9.000000 }, 

© www.soinside.com 2019 - 2024. All rights reserved.