首页 > 解决方案 > 无重复运行功能

问题描述

我想知道是否有可能使函数运行而没有重复?

如果它通过带有数字的数组循环,1,2,2,3,4 我希望 2 只运行一次而不是两次。喜欢1,2,3,4。如何检查是否tab[i]已经插入?我需要在 c++ 98 中执行此操作。

     std::vector<int> noDup(n);

 for(int k=0; k < n; k++) {
    bool exists = false;

    for(int c= 0; c < noDup.size(); c++) {
      if(tab[k] == tab[c]) {
        exists = true;
        break;
      }
      if(exists == false) {
        noDup.push_back(tab[k]);
      }
    }
  }

  for(auto c : noDup) {
    cout << c << " ";
  }

当我在选项卡数组 4 中插入元素数量时,我输入2,2,3,4我得到了输出0 0 0 0 3 3 4 4 4

标签: c++c++98

解决方案


你做了

      if(exists == false) {
        noDup.push_back(tab[k]);
      }

在错误的地方。它必须在检查所有元素之后。

此外,向量std::vector<int> noDup(n);已经有n元素,push_back()并将在初始元素之后添加n元素。似乎您想预先分配而不通过添加元素reserve()

条件tab[k] == tab[c]也是错误的。应该是tab[k] == noDup[c]

另一个错误是for(auto c : noDup)(range-based for and auto) 的使用,它在 C++11 中可用,在 C++98 中不可用。

固定代码:

std::vector<int> noDup;
noDup.reserve(n);

for(int k=0; k < n; k++) {
  bool exists = false;

  for(int c= 0; c < noDup.size(); c++) {
    if(tab[k] == noDup[c]) {
      exists = true;
      break;
    }
  }
  if(exists == false) {
    noDup.push_back(tab[k]);
  }
}

for(std::vector<int>::iterator it = noDup.begin(); it != noDup.end(); it++) {
  cout << *it << " ";
}

更好的选择是使用std::set.

std::set<int> seen;
std::vector<int> noDup;
noDup.reserve(n);

for(int k=0; k < n; k++) {
  if (seen.find(tab[k]) == seen.end()) {
    seen.insert(tab[k]);
    noDup.push_back(tab[k]);
  }
}

for(std::vector<int>::iterator it = noDup.begin(); it != noDup.end(); it++) {
  cout << *it << " ";
}

推荐阅读