gpt4 book ai didi

c++ - 如何根据元素在原始 vector 中的位置对 C++ vector 的拷贝进行排序?

转载 作者:行者123 更新时间:2023-11-30 05:44:16 24 4
gpt4 key购买 nike

我类有这张 map :

map<string,vector<pair<string,int>>> assessedTest__name_result;

我已将该 vector 复制到另一个临时 vector ,我想按对中的第一个值对其进行排序。如果一对中有两个元素具有相同的第一个值,我想通过它们在原始 vector 中的位置来确定位置。但是如果我想查看原始 vector ,静态 vector 排序函数将不允许我这样做。你能告诉我怎么做吗?谢谢

代码:

//test is the key in the map shown above
vector<pair<int,int>> tmpVec = assessedTest__name_result.at(test);
sort (tmpVec.begin(),tmpVec.end(),vecIdSort);
...
bool myClass::vecNameSort(const pair<string,int>& firstElem, const pair<string,int>& secondElem, const string& test){
if (firstElem.first < secondElem.first)
return true;
if (firstElem.first > secondElem.first)
return false;
return AssSort(firstElem.first, secondElem.first,test); //in case the elements are the same
}

bool myClass::AssSort (const int firstId, const int secId,const string& test){
bool foundFirst,foundSecond;
vector<pair<string,int>>::iterator first,second;
for (auto it = assessedTest__name_result.at(test).begin();it != assessedTest__name_result.at(test).end(); it++){
if ((*it).first == firstId){
first = it;
foundFirst = true;
}
if ((*it).first == secId){
second = it;
foundSecond = true;
}
if (foundFirst && foundSecond) break;
}
return first < second;
}

最佳答案

std::stable_sort 就是答案

std::stable_sort(tmpVec.begin(),tmpVec.end())

如果你有自己的比较函数 vecIdSort 这样做

std::stable_sort (tmpVec.begin(),tmpVec.end(),vecIdSort);

关于c++ - 如何根据元素在原始 vector 中的位置对 C++ vector 的拷贝进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com