If i have 2 array contains data
1 50
2 30
3 40
4 70
if I want to sort in descending order which take nombor and data together...
4 70
1 50
3 40
2 30
How???
If i have 2 array contains data
1 50
2 30
3 40
4 70
if I want to sort in descending order which take nombor and data together...
4 70
1 50
3 40
2 30
How???
Short answer: keep each id/value pair together, then sort by the value. As hinted, grouping related data is the right idea; two common ways are (A) combine into one container and sort that, or (B) sort an index list so the original containers are not moved.
Example: pair-container approach — build a vector of (id,value) pairs, then sort by the second element (descending). This is simple and easy to reconstruct the sorted arrays afterwards.
std::vector<std::pair<int,int>> v;
// fill v: (id, value)
std::sort(v.begin(), v.end(),
[](const auto &a, const auto &b){ return a.second > b.second; }); Index approach — useful when IDs are heavy (strings) or you want to avoid moving objects. Create an index array with iota, sort indices by the value array, then iterate in that order or copy into new arrays.
std::vector<int> idx(n);
std::iota(idx.begin(), idx.end(), 0);
std::sort(idx.begin(), idx.end(),
[&](int i, int j){ return values[i] > values[j]; });
for (int k : idx) std::cout << ids[k] << ' ' << values[k] << '\n'; Regarding your exam idea (): you can sort your exam objects by any key — a particular total element or an aggregate (sum/average). Always check bounds before accessing total[i]. Use std::stable_sort if you need to preserve original order on ties. For details on the algorithm guarantees and options, see std::sort. Common pitfalls: mismatched lengths in parallel arrays, unsound comparators, and needless copying of large objects — prefer indices when performance/memory matters.
Jump to Post— Ancient Dragon 5,243When you exchange one array during the sort you have to make similar exchanges in the second array. That's one reason that many (most?) programmers put suich things in an array of structures -- to make sorting a lot simpler.
struct data { int a; int b; …
When you exchange one array during the sort you have to make similar exchanges in the second array. That's one reason that many (most?) programmers put suich things in an array of structures -- to make sorting a lot simpler.
struct data
{
int a;
int b;
}; Now instead of sorting two arrays you only have to sort one array of structures.
If I put like this???
struct exam
{
string examid;
vector <int> total;
}; We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.