-3

If vector consists from these numbers 55 55 55 55 1 23 45, how I am possible to print the number who repeat itself for more then once, so basically it should print: 55, 1, 23, 45.

3 Answers3

0

Do this

int sample[]= {55,55,55,55,1,23,45};
std::set<int> myset(sample, sample + sizeof(myset));
for(set<int>::iterator iter=myset.begin(); iter!=myset.end();++iter) cout<<(*iter)<<endl;
return 0;
xxfast
  • 697
  • 5
  • 14
0

As the comments suggested, you can use a std::unordered_set or std::set:

#include <unordered_set>
#include <vector>
#include <iostream>

int main()
{
   std::unordered_set<int> tempSet;
   std::vector<int> vec { 55, 55, 55, 1, 23, 45 };
   for ( auto& val : vec )
   {
      if (!tempSet.count(val)) 
         std::cout << val << " "; 
      tempSet.insert(val); 
   }
}

Live Example

For each item in the vector, the set::count() is used to determine if the item is already in the set. If not in the set, then print the value.

Edit: I could have placed the insert() call within the if():

      if (!tempSet.count(val)) 
      {
         std::cout << val << " "; 
         tempSet.insert(val); 
      }

but I placed it outside the if() to demonstrate that the set will not store duplicates, even if you tried to store them.

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
0

basically,

vector <int> b;
b.push_back(55);
b.push_back(55);
b.push_back(55);
b.push_back(25);
b.push_back(23);
b.push_back(2);
set <int> a;
for (auto it : b) a.insert(it);
for (auto it : a)
cout << it;
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
0x9093717
  • 11
  • 6
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Mar 19 '17 at 11:04