My inputs are pairs of int
s. They are stored in std::vector<int>
s vec1
and vec2
. (vec1[i]
, vec2[i]
) corresponds to a single data-point. I want to sort this data.
Example:
Input:
- vec1 = [ 6, -3, 18, 0]
- vec2 = [100, 2, 3, 4]
Output:
- vec1 = [-3, 0, 6, 18]
- vec2 = [2, 4, 100, 3]
In the above example, vec1
was sorted using the order of integers. vec2
was modified to keep vec1[i]
and vec2[i]
aligned.
An Idea
I would like std::sort
to handle the sorting algorithm for me. To do this, I would define a new iterator type
class IteratorType {
private:
int i;
std::vector<int>& vec1;
std::vector<int>& vec2;
public:
DereferenceType& operator* ()
{
return DereferenceType{i, vec1, vec2}; // error: temporary returned as reference
}
};
When std::sort
swaps two elements, the iterators are dereferenced and the swap is made. It does not appear that this swap is guaranteed to be made with std::swap
or std::move
. For my example, I'll create a new DereferenceType
with an overloaded move operator.
class DereferenceType {
private:
int i;
std::vector<int>& vec1;
std::vector<int>& vec2;
public:
DereferenceType& DereferenceType::operator= (DereferenceType&&){
// overload std::move
}
};
Making std::move
not behave like a move may violate an assumption of std::sort
. I also don't like that I have to store std::vector<int>& vec1;
and std::vector<int>& vec2;
in each DereferenceType
.
The Question
Are there simpler (or more canonical) ways of getting the behavior I want?