Viết trình lặp của riêng bạn và sử dụng STD: sắp xếp. Nó dễ dàng được mã hóa trong ít hơn 50 dòng mà không có thư viện của bên thứ ba. Chức năng hoán đổi rất quan trọng ở đây.
#include <iostream>
#include <iterator> // std::iterator, std::input_iterator_tag
#include <algorithm>
using namespace std;
struct Tuple;
struct RefTuple;
#define TUPLE_COMMON_FUNC(C, D, E, F) \
C##::C## (Tuple& t) ##D \
C##::C## (RefTuple& t) ##D \
void C##::operator = (Tuple& t) ##E \
void C##::operator = (RefTuple& t) ##E \
bool C##::operator < (const Tuple& t) const ##F \
bool C##::operator < (const RefTuple& t) const ##F
#define ASSIGN_1 : i(t.i), j(t.j), s(t.s) {}
#define ASSIGN_2 { i = t.i; j = t.j; s = t.s; }
#define SORT_CRITERIA \
return (j < t.j) || (j == t.j && (i < t.i));
struct Tuple {
int i, j, s;
TUPLE_COMMON_FUNC(Tuple, ; , ; , ;)
};
struct RefTuple {
int &i, &j, &s;
RefTuple(int &x, int &y, int &z): i(x), j(y), s(z) {}
TUPLE_COMMON_FUNC(RefTuple, ; , ; , ;)
};
TUPLE_COMMON_FUNC(Tuple, ASSIGN_1, ASSIGN_2, {SORT_CRITERIA})
TUPLE_COMMON_FUNC(RefTuple, ASSIGN_1, ASSIGN_2, {SORT_CRITERIA})
void swap(RefTuple& t1, RefTuple& t2) {
t1.i ^= t2.i; t2.i ^= t1.i; t1.i ^= t2.i;
t1.j ^= t2.j; t2.j ^= t1.j; t1.j ^= t2.j;
t1.s ^= t2.s; t2.s ^= t1.s; t1.s ^= t2.s;
}
class IterTuple : public iterator<random_access_iterator_tag, Tuple> {
int *i, *j, *s, idx;
public:
IterTuple(int* x, int*y, int* z, int l) : i(x), j(y), s(z), idx(l) {}
IterTuple(const IterTuple& e) : i(e.i), j(e.j), s(e.s), idx(e.idx) {}
RefTuple operator*() { return RefTuple(i[idx], j[idx], s[idx]); }
IterTuple& operator ++() { idx++; return *this; }
IterTuple& operator --() { idx--; return *this; }
IterTuple operator ++ (int) { IterTuple tmp(*this); idx++; return tmp; }
IterTuple operator -- (int) { IterTuple tmp(*this); idx--; return tmp; }
int operator - (IterTuple& rhs) { return idx - rhs.idx; }
IterTuple operator + (int n) { IterTuple tmp(*this); tmp.idx += n; return tmp; }
IterTuple operator - (int n) { IterTuple tmp(*this); tmp.idx -= n; return tmp; }
bool operator==(const IterTuple& rhs) { return idx == rhs.idx; }
bool operator!=(const IterTuple& rhs) { return idx != rhs.idx; }
bool operator<(IterTuple& rhs) { return idx < rhs.idx; }
};
int Ai[10] = {0, 0, 2, 3, 2, 4, 1, 1, 4, 2};
int Aj[10] = {0, 2, 3, 4, 4, 4, 0, 1, 0, 2};
int Ax[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int main() {
IterTuple from(Ai, Aj, Ax, 0);
IterTuple until(Ai, Aj, Ax, 10);
sort(from, until);
for (IterTuple it = from; it != until; it++)
cout << (*it).i << ' ' << (*it).j << ' ' << (*it).s << '\n';
return 0;
}
khi bạn đã sắp xếp 'arr' thứ tự sắp xếp ban đầu không còn được biết. Bạn sẽ cần phải lưu trữ thứ tự ban đầu nếu bạn muốn sắp xếp các mảng khác bằng cách gán đơn giản. –
Nếu 'arr' và' arr1' có liên quan, tại sao chúng không được lưu trữ cùng nhau (ví dụ như cấu trúc) ở vị trí đầu tiên? – casablanca
trùng lặp: http://stackoverflow.com/questions/236172/how-do-i-sort-a-stdvector-by-the-values-of-a-different-stdvector –