1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| #include <iostream> #include <utility> #include <vector> #include <map> #include <algorithm> using namespace std;
pair<int, int> findMinMax(vector<int>& nums) { if (nums.empty()) { return make_pair(0, 0); } int minVal = *min_element(nums.begin(), nums.end()); int maxVal = *max_element(nums.begin(), nums.end()); return make_pair(minVal, maxVal); }
void coordinatePoints() { vector<pair<int, int>> points; points.push_back({1, 2}); points.push_back({3, 4}); points.push_back({5, 6}); cout << "坐标点: "; for (const auto& p : points) { cout << "(" << p.first << "," << p.second << ") "; } cout << endl; }
void intervals() { vector<pair<int, int>> intervals{{1, 3}, {2, 6}, {8, 10}, {15, 18}}; sort(intervals.begin(), intervals.end()); cout << "区间: "; for (const auto& interval : intervals) { cout << "[" << interval.first << "," << interval.second << "] "; } cout << endl; }
void mapWithPair() { map<string, pair<int, int>> studentScores; studentScores["Alice"] = {95, 88}; studentScores["Bob"] = {87, 92}; studentScores["Charlie"] = {92, 85}; for (const auto& [name, scores] : studentScores) { cout << name << ": 数学=" << scores.first << ", 英语=" << scores.second << endl; } }
void vectorOfPairs() { vector<pair<string, int>> fruits; fruits.push_back({"apple", 5}); fruits.push_back({"banana", 3}); fruits.push_back({"orange", 2}); sort(fruits.begin(), fruits.end(), [](const pair<string, int>& a, const pair<string, int>& b) { return a.second < b.second; }); cout << "按数量排序: "; for (const auto& [name, count] : fruits) { cout << name << ":" << count << " "; } cout << endl; }
int main() { pair<int, string> p{1, "apple"}; cout << "pair: (" << p.first << ", " << p.second << ")" << endl; auto p2 = make_pair(2, "banana"); cout << "make_pair: (" << p2.first << ", " << p2.second << ")" << endl; vector<int> nums{3, 1, 4, 1, 5, 9, 2, 6}; auto [minVal, maxVal] = findMinMax(nums); cout << "最小值: " << minVal << ", 最大值: " << maxVal << endl; coordinatePoints(); intervals(); mapWithPair(); vectorOfPairs(); return 0; }
|