In the following function, impObj argument currently points to a particular index in myVec and after using std::unique I want to update impObj to point to the same MyClass instance in vector (or the instance which was sequentially equal to original)
void RemoveSequentialDuplicates(std::vector<MyClass>& myVec, int& impObj)
{
auto itrLast = std::unique(myVec.begin(), myVec.end(), [](const MyClass& first, const MyClass& second) -> bool {
return first == second;
});
myVec.erase(itrLast, myVec.end());
}
Basically what I want is -
Input1 - [A, A, B, B, D, A], impObj = 5
Output1 - [A, B, D, A] impObj = 3
Input2 - [A, B, B, B, A, A, C], impObj = 2
Output2 - [A, B, A, C] impObj = 1
Use of std::unique is not mandatory, we can use any other way also.
One way to do it is -
void RemoveSequentialDuplicates(std::vector<MyClass>& myVec, int& index)
{
int leftIndex = 0, rightIndex = 1;
auto itrLast = std::unique(myVec.begin(), myVec.end(), [&leftIndex, &rightIndex, &impObj](const MyClass& first, const MyClass& second) -> bool {
bool equals = false;
if (first == second)
equals = true;
else
leftIndex++;
if(impObj == rightIndex)
impObj = leftIndex;
rightIndex++;
return equals;
});
myVec.erase(itrLast, myVec.end());
}
Is there a better way to do it?
Note: I want to keep the order of the elements same