简体   繁体   English

如何根据另一个预先排序的字符串向量排序包含字符串的向量?

[英]How do i order vector containing strings in accordance with another pre sorted vector of strings?

So the program will take in a user's name then ID and store them in vectors vName and vID. 因此,程序将输入用户名和ID,并将其存储在向量vName和vID中。 For example i have a code like this that takes a string name 例如我有一个这样的代码,它带有一个字符串名称

cout << "what is your name?";
getline(cin sName)
vName.push_back(sName)

 cout << "what is your name?";
 getline(cin sName)
 vName.push_back(sName)

If a user inputs the names Paul and Leto and the IDs 123 and 456 and if i cout the elements inside the vectors i'll get them back exactly as i put them in. But if i decide to sort vName like this 如果用户输入了Paul和Leto的名称以及ID 123和456,并且如果我对向量中的元素进行了标注,我将把它们放回原先的位置。但是如果我决定像这样对vName进行排序

(vName.begin(), vName.end());  

and i cout the elements Leto will be matched with 123 and Paul will be matched with 456. How do i prevent that from happening? 并且我将Leto的元素与123匹配,而Paul的元素与456匹配。如何防止这种情况发生? How do i make it so that no matter how vName is sorted vID will change so that the IDs will match with the names? 我如何做到这一点,无论vName如何排序,vID都会改变,以便ID与名称匹配?

You should use a struct: 您应该使用一个结构:

struct Person {
  string name;
  int id;
};
vector<Person> people;

If you don't like that, you could do "proxy sorting" by sorting your ID vector first using the names as the proxy for ordering. 如果您不喜欢这样做,可以通过使用名称作为排序的代理首先对ID向量进行排序来进行“代理排序”。 In either of these solutions you will need to implement your own predicate for sorting by the name field. 在这两种解决方案中,您都需要实现自己的谓词以按名称字段进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM