c – 使用两个向量进行排序
发布时间:2020-12-16 10:26:22 所属栏目:百科 来源:网络整理
导读:我想知道你是否有可能,例如,一个矢量 string和矢量 double使用相应的对,对矢量 string进行排序字母顺序,同时保持对匹配. 我知道这可以通过创建一个包含两个值并只对其进行排序的类来完成,但我宁愿保留两个单独的向量. 有任何想法吗? 最终守则: #include "s
我想知道你是否有可能,例如,一个矢量< string>和矢量< double>使用相应的对,对矢量< 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 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,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,int bottom) // top is subscript of beginning of vector { int middle; if(top < bottom) { middle = divide(num,num2,top,bottom); quicksort(num,middle); quicksort(num,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,(np.names.size()-2)); np.print(); keep_window_open();} 解决方法
如果您打算使用std :: sort,则需要使用像对一样的数据结构.
当然,您可以手动对向量进行排序,并基本上重新实现std :: sort. 这个问题实际上取决于许多其他问题,例如: >向量中有多少项? 实现快速排序应该相当轻松,并且可以避免移动数据. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |