3

i tried to make custom iterator for 2D array to iterate it by column. what i want to achieve by this test is to manipulate 2d array values. for example this script with produce an out put:

0 1 2
3 4 5
6 7 8

by help of column iterator and std::reverse i can manipulate 2d array to get the out put like this

6 1 2
3 4 5
0 7 8

however. same result can be done by std::swap. so i repeated the test script by swap but it fails.

my question, is the swap for any iterator class is just dummy member function?

template<typename Container>
class Columniterator : public std::iterator<std::random_access_iterator_tag,
    typename std::decay<decltype(std::declval<Container>()[0][0])>::type>
{
    using iterator = typename Container::iterator;
    using  type = typename std::decay<decltype(std::declval<Container>()[0][0])>::type;
public:

    Columniterator(iterator _it, size_t _i)
        : it(_it), i(_i)
    {}

....

a lot of code bla bla

....

    void swap(Columniterator& other)
    {
        using std::swap;
        swap(it, other.it);
    }
private:
    iterator it;
    size_t i;
};

test code

    //std::reverse(Columniterator<Container>(container.begin(),0), Columniterator<Container>(container.end(), 0)); // passed
    std::swap(Columniterator<Container>(container.begin(),0), Columniterator<Container>(container.end(), 0)); // failed
MORTAL
  • 383
  • 2
  • 10

2 Answers2

3

You didn't implement swap at global scope, you implemented swap within the class.

If you implement a proper swap it can be made to work. See how to provide a swap function for my class?

Community
  • 1
  • 1
StilesCrisis
  • 15,972
  • 4
  • 39
  • 62
3

Your test try to swap temporaries; use variable instead:

auto begin0 = begin(matrix, 0);
auto end0 = end(matrix, 0);

begin0.swap(end0);

or provide swap overload with rvalue reference.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • its your code i just tried to add swap to it. but it seems won't be – MORTAL Dec 24 '14 at 00:44
  • 1
    @MORTAL: You may add info about what doesn't work: No info in the Question and in both answers. It would help us to help you. – Jarod42 Dec 24 '14 at 00:50