1

My inputs are pairs of ints. 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?

mbang
  • 855
  • 2
  • 9
  • 1
    why don't you use `std::vector>` ? – justANewb stands with Ukraine Feb 03 '23 at 13:53
  • @justANewbstandswithUkraine because the input is from LeetCode. I agree that interview questions often don't give sensible input formats. – mbang Feb 03 '23 at 13:55
  • 1
    so use the two vectors to merge it into a `std::vector>` ? – justANewb stands with Ukraine Feb 03 '23 at 13:56
  • 1
    *To continue, I may need to overload swap and move in namespace std*. Do not that you are not allowed to add overloads into `std` – NathanOliver Feb 03 '23 at 13:59
  • @NathanOliver I meant specialize. I believe you are allowed to specialize as of C++20. I'll correct in OP. **Edit:** Nathan is right. This is undefined behavior. – mbang Feb 03 '23 at 14:00
  • 1
    @mbang You are not allowed to specialize functions in `std` since C++20 as well so that will also be a no-go for you. – NathanOliver Feb 03 '23 at 14:00
  • Agree with @justANewbstandswithUkraine. I assume (perhaps incorrectly but I am feeling confident on it) anyone with experience in C++ would use `std::vector>`. It is going to be hard for you to get an answer on something nobody would attempt... – Atmo Feb 03 '23 at 14:01

0 Answers0