在C++中,遍歷數據結構(如數組、向量、列表、映射等)時,有多種技巧可以使用,以下是一些常用的技巧:
int arr[] = {1, 2, 3, 4, 5};
for(int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
vector<int> vec = {1, 2, 3, 4, 5};
for(auto it = vec.begin(); it != vec.end(); it++) {
cout << *it << " ";
}
vector<int> vec = {1, 2, 3, 4, 5};
for(int x : vec) {
cout << x << " ";
}
vector<int> vec = {1, 2, 3, 4, 5};
for_each(vec.begin(), vec.end(), [](int x) {
cout << x << " ";
});
vector<int> vec = {1, 2, 3, 4, 5};
for(auto it = vec.rbegin(); it != vec.rend(); it++) {
cout << *it << " ";
}
map<string, int> myMap = {{"a", 1}, {"b", 2}, {"c", 3}};
for(auto it = myMap.begin(); it != myMap.end(); it++) {
cout << it->first << " : " << it->second << endl;
}
這些是一些常用的C++遍歷技巧,根據具體情況選擇合適的遍歷方法。