这段代码为什么会报语法错误:int miceAndCheese(vector<int>& reward1, vector<int>& reward2, int k) { vector<pair<int, int>>v; for(int i = 0; i < reward1.size(); i++) { v.push_back(make_pair(reward1[i], reward2[i])); } sort(v.begin(), v.end(), greater<int>()); int ans = 0; for(int i = 0; i < v.size(); i++) cout << v[i].first << " " << v[i].second << endl; return ans; } };
时间: 2024-03-17 18:47:15 浏览: 60
这段代码会报语法错误是因为有一个多余的 "}; "在代码的末尾,应该将它删除。代码的正确形式如下:
```
int miceAndCheese(vector<int>& reward1, vector<int>& reward2, int k) {
vector<pair<int, int>>v;
for(int i = 0; i < reward1.size(); i++) {
v.push_back(make_pair(reward1[i], reward2[i]));
}
sort(v.begin(), v.end(), greater<int>());
int ans = 0;
for(int i = 0; i < v.size(); i++) cout << v[i].first << " " << v[i].second << endl;
return ans;
}
```
相关问题
这段代码为什么会报语法错误:int miceAndCheese(vector<int>& reward1, vector<int>& reward2, int k) { vector<pair<int, int>>v; for(int i = 0; i < reward1.size(); i++) { v.push_back(make_pair(reward1[i], reward2[i])); } sort(v.begin(), v.end(), greater<int>()); int ans = 0; for(int i = 0; i < v.size(); i++) cout << v[i].first << " " << v[i].second << endl; return ans; }
这段代码没有语法错误。它定义了一个名为 `miceAndCheese` 的函数,该函数接受三个参数:类型为 `vector<int>&` 的 `reward1`、类型为 `vector<int>&` 的 `reward2`和类型为 `int` 的 `k`。该函数使用一个 `vector<pair<int, int>>` 类型的变量 `v` 存储 `reward1` 和 `reward2` 中的值。然后,该函数对 `v` 进行降序排序,并将排序后的结果输出到控制台。最后,该函数返回值为0。
对于这段代码,如何实现v按照pair的第一个元素降序排序:vector<pair<int, int>>v; for(int i = 0; i < reward1.size(); i++) { v.push_back(make_pair(reward1[i], reward2[i])); }
你可以使用 `sort()` 函数对 `vector<pair<int, int>>` 类型的变量 `v` 进行排序,排序时需要指定排序规则。因为想要按照 `pair` 的第一个元素降序排序,所以排序规则应该使用 `greater<pair<int, int>>()`。具体实现如下:
```
vector<pair<int, int>>v;
for(int i = 0; i < reward1.size(); i++) {
v.push_back(make_pair(reward1[i], reward2[i]));
}
sort(v.begin(), v.end(), greater<pair<int, int>>()); // 使用 greater<pair<int, int>>() 降序排序
```
这样,`v` 就按照 `pair` 的第一个元素降序排序了。
阅读全文
相关推荐
















