主要运用了map自动排序的性质
class Solution {
public:
vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
map<int , string> ans; //map容器是有序的,只允许key与value一一对应
vector <string> name; //用于存放names
int n = names.size();
for(int i = 0; i < n ; i++)
{
ans[heights[i]] = names[i]; //建立身高与名字的映射关系
}
for(auto it = ans.begin() ; it != ans.end() ; it++) //map的遍历方式
{
name.push_back(it->second); //以指针形式访问第二个
}
reverse(name.begin() , name.end()); //逆序输出
return name;
}
};
方法二:各种排序方法,例如选择排序、冒泡排序等
class Solution {
public:
vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
int n = names.size();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (heights[i] < heights[j]) {
swap(heights[i], heights[j]);
swap(names[i], names[j]);
}
}
}
return names;
}
};
#include <iostream> //1.1 反转Vector容器
#include <vector>
using namespace std;
int main()
{
vector<int> a;
for (int i = 0; i < 10; i++)
{
a.push_back(i);
}
cout << "翻转前: " << "\n";
for (int i = 0; i < 10; i++)
{
cout << a[i];
}
reverse(a.begin(), a.end());
cout << "\n" << "翻转后: " << "\n";
for (int i = 0; i < 10; i++)
{
cout << a[i];
}
}
#include <iostream> //1.2 反转string
#include <vector>
using namespace std;
int main()
{
string s = "abcdefg";
cout << "翻转前: " << "\n";
cout << s;
reverse(s.begin(), s.end());
cout << "\n" << "翻转后: " << "\n";
cout << s;
}
#include <iostream> //1.3 翻转字符数组
#include <vector>
using namespace std;
int main()
{
char s[] = "abcdefg";
int N = sizeof(s) / sizeof(s[0]);
cout << "翻转前: " << "\n";
cout << s;
reverse(s, s + N - 1);
cout << "\n" << "翻转后: " << "\n";
cout << s;
}
#include <iostream> //1.4 反转数组
#include <vector>
using namespace std;
int main()
{
int s[] = { 1,2,3,4,5,6,7,8,9 };
cout << "翻转前: " << "\n";
for (int i = 0; i < sizeof(s) / sizeof(s[0]); i++)
cout << s[i] << " ";//输出9 8 7 6 5 4 3 2 1
reverse(s, s + 9);
cout << "\n" << "翻转后: " << "\n";
for (int i = 0; i < sizeof(s) / sizeof(s[0]); i++)
cout << s[i] << " ";//输出9 8 7 6 5 4 3 2 1
}
// Testing for palindromes using reverse_copy()
#include <iostream> // For standard streams
#include <iterator> // For stream iterators and begin() and end()
#include <algorithm> // For reverse_copy() and copy_if()
#include <cctype> // For toupper() and isalpha()
#include <string>
using namespace std;
using std::string;
int main()
{
string first, second;
first = "123456789";
second.resize(first.size());
reverse_copy(first.begin(), first.end(), second.begin());
cout << second << endl;
}