Search code examples
c++c++98

Run function without duplicate


I want to know if it's possible, to make the function run without duplicates?

If it's looping through array with numbers 1,2,2,3,4 I would want the 2 to be run only once instead twice. Like 1,2,3,4. How can I check if tab[i] has been already inserted? I need to do this in 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 << " ";
  }

When I inserted number of elements in tab array 4, I input 2,2,3,4 I got output 0 0 0 0 3 3 4 4 4


Solution

  • You did

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

    in wrong place. It have to be after checking all elements.

    Also the vector std::vector<int> noDup(n); already has n elements and push_back() will add elements after the initial n elements. It seems you want to pre-allocate without adding elements via reserve().

    The condition tab[k] == tab[c] is also wrong. It should be tab[k] == noDup[c].

    Another error is usage of for(auto c : noDup) (range-based for and auto), which is available from C++11 and not in C++98.

    Fixed code:

    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 << " ";
    }
    

    Better option is using 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 << " ";
    }