1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
#include <iostream>
#include <iterator>
#include <algorithm>
class step_iterator
: public std::iterator<
std::forward_iterator_tag,
int
>
{
public:
step_iterator():
here(nullptr),
step(0)
{}
step_iterator(pointer here, difference_type step=0):
here(here),
step(step)
{}
reference operator*(){
return *here;
}
step_iterator operator++(){
here += step;
return *this;
}
step_iterator operator++(int){
step_iterator it(*this);
++it;
return it;
}
//iterators from different containers are not comparable
bool operator==(const step_iterator &that){
if(this->is_end() and that.is_end())
return true;
if(this->is_end())
return this->here <= that.here;
if(that.is_end())
return that.here <= this->here;
return this->here == that.here;
}
bool operator not_eq(const step_iterator &that){
return not (*this == that);
}
pointer operator->(){
return here;
}
private:
pointer here;
difference_type step;
bool is_end() const{
return step==0;
}
};
template<class Iter>
void print(Iter beg, Iter end, std::ostream &out = std::cout){
std::copy(
beg,
end,
std::ostream_iterator<
typename std::iterator_traits<Iter>::value_type
> (out, " ")
);
out << '\n';
}
int main(){
const int n = 3;
int m[3][3];
for(int K=0; K<n; ++K)
for(int L=0; L<n; ++L)
m[K][L] = K*n+L;
//show all
for(int K=0; K<n; ++K){
for(int L=0; L<n; ++L)
std::cout << m[K][L] << ' ';
std::cout << '\n';
}
std::cout << "one row\n";
print(&m[2][0], &m[3][0]);
std::cout << "one column\n";
print(
step_iterator(&m[0][1], n),
step_iterator(&m[n][0])
);
std::cout << "diagonal\n";
print(
step_iterator(&m[0][0], n+1),
step_iterator(&m[n][0])
);
std::cout << "another diagonal\n";
print(
step_iterator(&m[0][1], n-1),
step_iterator(&m[n][0]-1)
);
}
|
0 1 2
3 4 5
6 7 8
one row
6 7 8
one column
1 4 7
diagonal
0 4 8
another diagonal
1 3 5 7 |