mardi 6 janvier 2015

C++: confused by type on computing distances between iterators

I need to rotate elements in a std::vector so that it holds at the beginning the first duplicate element. To be clearer, say if I have:



1 2 3 4 5 6 3 7 8


Then I want:



3 4 5 6 3 7 8 1 2


Ok, lets use std::rotate(), and build a function to get the first duplicate position:



int main() {
std::vector<int> v = { 1,2,3,4,5,6,3,7,8 };
auto it = FindFirstDuplicate(v);
cout << "first dupe is " << *it << " at " << it - v.begin() << endl;
std::rotate( v.begin(), it, v.end() );
}


The idea for that task is to store one by one the elements in a new vector, until I find that the one I am about to add is already in this new vector.


But I stumble on iterators issues, so it doesn't compile. I get confused with the type of the different iterators, and on const/non const iterator issues.


Here is my code at present, try it online here (skipped std:: for readability):



template<typename T>
typename vector<T>::iterator FindFirstDuplicate( const vector<T>& v )
{
vector<T> nv; // new temp vector
nv.reserve( v.size() );
for( auto it1 = v.cbegin(); it1 != v.cend(); it1++ )
{
auto it2 = find( nv.begin(), nv.end(), *it1 ); // search elem in new vector
if( it2 == nv.end() ) // if not present,
nv.push_back( *it1 ); // add in new vector
else // else, we found a dupe
return v.begin() + (it2-nv.begin());
}
return v.begin();
}


To save your eyes, I don't post the error message, but to me it seems that the compiler complains about the different types of the iterators on the last line. I also tried by using non const iterator for it1, but I still get that problem.


Any help appreciated, on this iterator issue, but also any advice on the algorithm by itself.


Aucun commentaire:

Enregistrer un commentaire