Reputation: 79
I have a functionality where I want to compare every element of a set with previous elements. I want to do something like this:
std::set<int> sSet;
std::set<int>::iterator it;
std::set<int>::iterator itR;
sSet.insert(1);
sSet.insert(2);
sSet.insert(3);
sSet.insert(4);
sSet.insert(5);
sSet.insert(6);
for (it=sSet.begin(); it!=sSet.end(); ++it) //simple forward loop
{
itR = it;
if(it != sSet.begin())
itR--;
for(;itR!=sSet.begin();itR--)
{
//Reverse iteration
//for comparing every element to all the previous elements
//Problem here is it goes up to the second element only and not first
//because of the condition itR!=sSet.begin()
}
}
I was thinking of using reverse iterators here but again I couldn't find a way to set a reverse iterator from a specific position (or a forward iterator).
Is there any correct way to do this?
Update: Set used above is just for demonstration. Actual implementation as a set of a class and is defined like below:
std::set<TBigClass, TBigClassComparer> sSet;
class TBigClassComparer
{
public:
bool operator()(const TBigClass s1, const TBigClass s2) const
{
//comparison logic goes here
}
};
Upvotes: 0
Views: 896
Reputation: 4025
Want reverse?! Use reverse iterator:
std::set<int> sSet;
std::set<int>::iterator it;
std::reverse_iterator<std::set<int>::iterator> itR;
sSet.insert(1);
sSet.insert(2);
sSet.insert(3);
sSet.insert(4);
sSet.insert(5);
sSet.insert(6);
for (it=sSet.begin(); it!=sSet.rend(); ++it) //simple forward loop
{
itR = std::reverse_iterator<std::set<int>::iterator>(it);
for(;itR!=sSet.rbegin();++itR)
{
//Reverse iteration
//for comparing every element to all the previous elements
//Problem here is it goes up to the second element only and not first
//because of the condition itR!=sSet.begin()
}
}
Notice however that when an iterator is reversed, the reversed version does not point to the same element in the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a range: An iterator pointing to a past-the-end element in a range, when reversed, is changed to point to the last element (not past it) of the range (this would be the first element of the range if reversed). And if an iterator to the first element in a range is reversed, the reversed iterator points to the element before the first element (this would be the past-the-end element of the range if reversed).
Upvotes: 1
Reputation: 3658
You can use an internal while loop:
while (true)
{
// do your comparison here
if (itR == sSet.begin())
break;
--itR;
}
Upvotes: 0