对由两个数组组成的结构进行排序
Sort a structure which consists of two arrays
我有一个结构,看起来像这样:
struct MyStruct {
int a[9];
int index[9];
}
我希望根据数组'a'的值对这个结构进行排序,并使数组'index'的相应值自动调整为相同的值。
请指导我如何为这样的结构编写比较函数。
EDIT:我想通过传递此结构并使用自定义比较函数根据数组'a'的值对结构进行排序,使用内置排序函数(如qsort
或sort
)对这样的结构进行排序。这将帮助我学习如何使用这样的比较函数,因此具体的要求。
问题是sort
使用swap
重新排列顺序和交换地址以交换指向用于排序的数据。a
of type int&
.
所以这是一个解决方案:
#include <iostream>
#include <iterator>
#include <algorithm>
static_assert(__cplusplus >= 201103L, "not C++11");
using std::cout;
using std::endl;
class OhMy {
public:
int a[9];
int index[9];
OhMy() {
int i = 9;
for (int& b : a)
b = i--;
i = 19;
for (int& b : index)
b = i--;
}
template <class T>
void swap(T& i,T& j) {
std::swap(i,j);
// dirty pointer arithmetic
std::swap(index[std::distance(&a[0],&i)],index[std::distance(&a[0],&j)]);
}
void sort() {
std::sort(std::begin(a),std::end(a));
}
void dump() {
copy(std::begin(a),std::end(a), std::ostream_iterator<int>(std::cout, " "));
cout << endl;
copy(std::begin(index),std::end(index), std::ostream_iterator<int>(std::cout, " "));
cout << endl;
}
};
int main() {
OhMy ohMy;
cout << "Before:";
ohMy.dump();
cout << "swap:";
ohMy.swap(ohMy.a[0],ohMy.a[1]);
ohMy.dump();
cout << "After sort:";
ohMy.sort();
ohMy.dump();
return 0;
}
它有效!不! !
Before:9 8 7 6 5 4 3 2 1
19 18 17 16 15 14 13 12 11
交换:8 9 7 6 5 4 3 2 1
18 19 17 16 15 14 13 12 11
后排序:1 2 3 4 5 6 7 8 9
18 19 17 16 15 14 13 12 11
因此sort
使用std::swap
或std::swap_iter
而不是本地可见的swap
。
你必须自己排序,因为我所知道的所有排序都只接受cmp
而不是swap
作为参数。
相关文章:
- 将结构向量排序为子组
- 带有枚举方向/类型的气泡排序结构数组
- C++对结构向量进行排序
- 在C++中对结构向量进行排序时出现问题
- 按字母顺序对结构内数组变量中的名称进行排序
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 使用选择排序对数组数据结构进行排序,但它不起作用
- 对结构向量进行两次排序
- C++使用QuickSort对数组结构进行排序
- 如何选择排序一些结构
- 对结构int成员进行排序
- 在排序链表中插入结构并将其写入二进制文件
- 对坐标结构的向量进行排序
- C++ 中优先级队列的结构排序条件
- C++ MDC final-在字符类型的数组结构中按字母顺序对记录中的名称进行排序
- 按字母顺序对结构数组进行排序
- C++结构排序性能
- 自定义结构排序不起作用
- std::向量使结构排序变慢?C++
- 数据结构-排序队列链表c++