在 C++ 中,使用 pair.second 还是 pair->second 取决于 pair 的数据类型。
📌 pair.second vs pair->second
| 语法 | 适用对象 | 说明 |
|---|---|---|
pair.second | std::pair<K, V> | pair 是对象,使用 . 访问成员变量 |
pair->second | std::pair<K, V>*(指针) | pair 是指针,使用 -> 访问成员变量 |
✅ 1️⃣ 直接使用 pair.second(当 pair 是对象时)
#include <iostream>
#include <utility> // std::pair
using namespace std;
int main() {
pair<int, string> p = {1, "Alice"};
// 访问 second
cout << "ID: " << p.first << ", Name: " << p.second << endl;
return 0;
}
🔹 运行结果
ID: 1, Name: Alice
📌 解释
p是对象,使用p.second访问pair的第二个值。
✅ 2️⃣ 使用 pair->second(当 pair 是指针时)
#include <iostream>
#include <utility>
using namespace std;
int main() {
pair<int, string>* p = new pair<int, string>(1, "Alice");
// **指针访问成员变量**
cout << "ID: " << p->first << ", Name: " << p->second << endl;
delete p; // 释放内存
return 0;
}
🔹 运行结果
ID: 1, Name: Alice
📌 解释
p是pair<int, string>*指针,所以用p->second访问second成员。
🚀 3️⃣ 在 unordered_map 遍历时的用法
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<int, string> myMap = {{1, "Alice"}, {2, "Bob"}};
// 遍历 `unordered_map`
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
cout << "Key: " << it->first << ", Value: " << it->second << endl;
}
return 0;
}
🔹 运行结果
Key: 1, Value: Alice
Key: 2, Value: Bob
📌 解释
unordered_map<int, string>::iterator it指向pair<const int, string>it是指针,所以用it->second访问second。
🚀 总结
| 用法 | pair 类型 | 正确写法 |
|---|---|---|
当 pair 是对象 | std::pair<int, string> p; | ✅ p.second |
当 pair 是指针 | std::pair<int, string>* p; | ✅ p->second |
在 unordered_map 迭代器中 | unordered_map<int, string>::iterator it | ✅ it->second |
🚀 规则:
- 对象用
.(pair.second) - 指针用
->(pair->second) - 迭代器
it->second适用于unordered_map和map🎯
3534

被折叠的 条评论
为什么被折叠?



