使用unique_copy算法重复消除c ++(练习16.9)

时间:2018-03-13 04:30:07

标签: c++ algorithm duplicates

我尝试使用unique_copy算法创建重复消除练习。我需要在空向量中输入20个整数。但是,输出表示向量中的全零(0 0 0 ... 0 0 0)。我该怎么做才能使用unique_copy算法在向量中找到唯一变量?练习16.9的教科书( C ++如何编写第9版)说:“使用back_inserter可以在添加新项目时使向量增长。使用复制算法显示唯一值。” (738) 这是代码:

#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;

typedef vector<int, allocator<int> > vec_t;
typedef insert_iterator<vec_t> vec_iter;
typedef ostream_iterator<int, char, char_traits<char> > os_iter;

int main()
{
   int SIZE = 20;
   int twenty[20] = {};
   vec_t v20(twenty, twenty + 20);
   int entry;
   int current_index = 0;
   bool duplicated = false;
   for(int i = 0; i <= SIZE; i++)
   {
      cout << "Enter number: " << endl;
      cin >> entry;
      if(entry > 10 && entry < 100)
      {
         for(int u = 0; u < current_index; u++)
         {
             if(twenty[i] == entry)
             {
                cout << "You already entered these numbers " << endl;
                duplicated = true;
                break;
             }
         }
         if(duplicated == false)
         {
             twenty[current_index] = entry;
             current_index++;
         }
      }
      else
      {
          cout << "Error: invalid number; you must enter between 10 and 100 " << endl;
          i--;
      }
   }
   for(int x = 0; x < current_index; x++)
   {
      cout << twenty[x] << endl;
      vec_t outcome;
      vec_iter ins (outcome, outcome.begin());
      cout << "Vector: " << endl << " ";
      copy(v20.cbegin(), v20.cend(), os_iter(cout, " "));
      cout << endl;
      unique_copy(v20.cbegin(), v20.cend(), ins);
      cout << endl << "After unique_copy, outcome contains ";
      copy(outcome.cbegin(), outcome.cend(), os_iter(cout, " "));
      cout << endl;
   }
   return 0;
}

我希望你能帮助我解决问题。 ChonglinXu

0 个答案:

没有答案