Ok let me see if I understand you correctly.
You have two containers one for the letters 1-5 and one for the letters a-e.
Each of the letters is linked with a number like in your example
1 = C
2 = A
3 = D
4 = B
5 = E |
You then want to sort the letters alphabetically, and also change the numbers positions when that sort is run?
IE Output after sort() on the letters would be
.
Have you thought about creating a array of pairs http://www.cplusplus.com/reference/utility/pair/?kw=pair or a vector of pairs? That way each letter is linked to its respective number. And when you sort the letters you also sort the numbers the way you want it to be.
Here is a example of how it can be done.
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
|
#include <iostream>
#include <algorithm>
#include <utility>
#include <vector>
using namespace std;
// The sort uses this function to sort by the characters. The characters
// are second in the pair that is why we use lhs.second and rhs.second.
// You can make another function to sort by the numbers.
bool sortByChar(const pair<int,char> &lhs, const pair<int,char> &rhs)
{
return lhs.second < rhs.second;
}
int main()
{
// A vector of pairs.
vector<pair<int, char>> container;
// Just added the elements to the vector so it looks like
// Your example you posted.
container.push_back(pair<int, char>(1, 'C'));
container.push_back(pair<int, char>(2, 'A'));
container.push_back(pair<int, char>(3, 'D'));
container.push_back(pair<int, char>(4, 'B'));
container.push_back(pair<int, char>(5, 'E'));
// Sort the vector<pair<int, char>> using a special function
// that we defined aboved.
sort(container.begin(), container.end(), sortByChar);
// Ranged based loops requires C++11. It is just
// printing the vector out. You can use the default way if you want
cout << "The Letters are sorted like" << endl;
for (pair<int,char> &x : container)
cout << x.second << endl;
// Ranged base loop. Just is printing the vector out
cout << "The Numbers are sorted like" << endl;
for (pair<int,char> &x : container)
cout << x.first << endl;
return 0;
}
| |
This uses a single vector of pairs that way each number is attached to its respective character (You can change char to strings if you want and vise versa). So when you sort the characters by alphabetical order you also move around the numbers to.
I am not sure how far along you are so if you don't understand anything just let me know and I can try and explain it to you or maybe suggest a more simple solution.
Also here are some links that can help.
Pair Documentation : http://www.cplusplus.com/reference/utility/pair/pair/
My Non Finished Tutorial on sort() : http://www.cplusplus.com/forum/lounge/100051/