sorry, I meant if elements have the same value, for example integers in vector: 1, 2, 2, 3, 4, 5, 5
how can I erase or remove the ones that have duplicates, to get an output like: 1,2,3,4, 5
you actually erase place holders (instead of values).
find which values are duplicate and erase corresponding places.
use a loop.
erase from end such as vec[6], vec[2]
EDIT: or copy all unique members to a new vector, and delete the whole old vector by vect.clear();
yes, but what if have populated that vector with inputs from user, and I don't know how many elements or what values those elements have, how would I erase then the elements that have the same value?
I need to iterate vector and somehow loop it to remove those elements, but I don't know how.
do I need to determine the size of the vector first in order to loop this?
I am sorry, I am total begginer and I don't know how to implement this in to the code above.
I just have one more question, I noticed that if user enters character instead of number, when he is asked to, program goes through endlees loop, and I need to exit it. How can this be avoided?
First, that for (int x: vect) cout << x << " "; is a range-based for syntax, which requires C++11 support from the compiler. Furthermore, the keyword auto has different meaning in C++11 than what it had before. Which compiler do you use?
Lets assume that you already have a vector<Foo> vect with some values in it. First approach:
auto pbegin = vect.begin();
auto pend = vect.end();
while ( pbegin != pend ) {
constauto value { *pbegin };
pend = std::remove( pbegin+1, pend, value );
++pbegin;
}
vect.erase( pend, vect.end() );
A no-sort version 2:
1 2 3 4 5 6 7 8 9 10
std::vector<Foo> temp;
tem.reserve( vect.size() );
std::set<Foo> known;
for ( auto x : vect ) {
if ( 0 == known.count( x ) ) {
known.insert( x );
temp.push_back( x );
}
}
vect.swap( temp );
I noticed that if user enters character instead of number
The formatted input for number does not find any number-like charaters and sets the fail-bit for the stream. As long as the bit is there, all future input will fail automatically. You have to tell the stream that it is ok, and then remove from the stream all offending characters before next input.
Code Block is not a compiler, it is an IDE. The compiler included in it is most likely GCC. GCC defaults to older standard, but has option -std=c++11 to enable new standard. Hopefully the IDE has means to pass that easily.