我想知道是否有可能对于一个包含相应成对元素的vector<string>
和vector<double>
,按照字母顺序排序vector<string>
,同时保持这些成对元素的匹配关系。
我知道可以通过创建一个类来保存这两个值,并对其进行排序来实现此目的,但我更愿意保留两个单独的向量。
有什么好的想法吗?
最终代码:
#include "std_lib_facilities.h"
struct Name_pairs
{
vector<string>names;
vector<double>ages;
void quicksort(vector<string>& num, vector<double>& num2, int top, int bottom);
int divide(vector<string>& array, vector<double>& array2, int top, int bottom);
bool test();
string read_names();
double read_ages();
void print();
};
string Name_pairs::read_names()
{
string name;
cout << "Enter name: ";
cin >> name;
names.push_back(name);
return name;
}
double Name_pairs::read_ages()
{
double age;
cout << "Enter corresponding age: ";
cin >> age;
ages.push_back(age);
cout << endl;
return age;
}
int Name_pairs::divide(vector<string>& array, vector<double>& array2, int top, int bottom)
{
string x = array[top];
int i = top-1;
int j = bottom+1;
string temp;
double temp2;
do{
do
{
j--;
}while(x<array[j]);
do
{
i++;
}while(x>array[i]);
if(i<j)
{
temp = array[i];
temp2 = array2[i];
array[i] = array[j];
array2[i] = array2[j];
array[j] = temp;
array2[j] = temp2;
}
}while(i<j);
return j;
}
void Name_pairs::quicksort(vector<string>& num, vector<double>& num2, int top, int bottom) // top is subscript of beginning of vector
{
int middle;
if(top < bottom)
{
middle = divide(num, num2, top, bottom);
quicksort(num, num2, top, middle);
quicksort(num, num2, middle+1, bottom);
}
return;
}
void Name_pairs::print()
{
for(int i = 0; i < (names.size()-1) && i < (ages.size()-1); ++i)
cout << names[i] << " , " << ages[i] << endl;
}
int main(){
Name_pairs np;
cout << "Enter names and ages. Use 0 to cancel.\n";
bool finished = false;
while(!finished){
finished = "0" == np.read_names();
finished = 0 == np.read_ages();}
np.quicksort(np.names, np.ages, 0, (np.names.size()-2));
np.print();
keep_window_open();}