老九学堂的网课中,列举出C++迭代的多种写法:
第一种正常写法:
void LandOwner::ShowCards(const vector<int>& cards) {
for (int i = 0; i < cards.size(); i++) {
cout << cards[i] << ",";
}
cout << endl;
}
第二种c语言的习惯,使用迭代器:
void LandOwner::ShowCards(const vector<int>& cards) {
for (vector<int>::const_iterator iter = cards.begin(); iter != cards.end(); iter++) {
cout << *iter << ",";
}
cout << endl;
}
第三种c++11的类型推断:
void LandOwner::ShowCards(const vector<int>& cards) {
for (auto iter = cards.begin(); iter != cards.end(); iter++) {
cout << *iter << ",";
}
cout << endl;
}
第四种c++11的区间遍历:
void LandOwner::ShowCards(const vector<int>& cards) {
for (auto card : cards) {
cout << card << ",";
}
cout << endl;
}
第五种使用算法的方式,将容器中的内容复制发哦cout绑定的迭代器中
(需要添加 #include<iterator> #include<algorithm>:
#include<iterator>
#include<algorithm>
void LandOwner::ShowCards(const vector<int>& cards) {
copy(cards.cbegin(), cards.cend(), ostream_iterator<int>(cout, ","));
cout << endl;
}