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
.
Asked
Active
Viewed 64 times
-3

Benjamin Kljuno
- 9
- 1
-
1Add everything to a `std::set` (which doesn't allow repeats), then print that. – Cory Kramer Mar 19 '17 at 00:08
-
@CoryKramer Haven't have any experience with std::set, may you explain it further. Many thanks! – Benjamin Kljuno Mar 19 '17 at 00:12
-
1[More information about `std::set`](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), be sure to read it. – Sam Varshavchik Mar 19 '17 at 00:15
-
member that repeat itself more than 1 = 55 only no ? – HDJEMAI Mar 19 '17 at 01:11
3 Answers
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);
}
}
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
-
Thanks, It worked! Not sure about few things how it worked... but thanks anyway. – Benjamin Kljuno Mar 19 '17 at 00:28
-
@BenjaminKljuno What are you not sure about? I will explain it, but the code is pretty straightforward. Output the value only if it isn't in the set. – PaulMcKenzie Mar 19 '17 at 00:29
-
Thanks. Not sure why my question got negative reputation, but thanks everyone for comments, I get it now. – Benjamin Kljuno Mar 19 '17 at 00:35
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