C++學習筆記(2)
阿新 • • 發佈:2022-05-14
C++學習筆記(2)
vector的四種遍歷方法測試
//迭代器測試iterator void myPrint(int a) { cout <<&a<<" = " << a << endl; } void test6() { vector<int> v; v.push_back(11); v.push_back(22); v.push_back(33); v.push_back(44); v.push_back(55); //方法一 cout << "---------方法一----------------" << endl; vector<int>::iterator begin = v.begin(); vector<int>::iterator end = v.end(); while (begin!=end) { cout <<"begin._Ptr="<<begin._Ptr<<" *begin=" << *begin << endl; begin++; } cout << "---------方法二----------------" << endl; //方法二 for (vector<int>::iterator it = v.begin(); it != v.end(); it++) { cout << "it._Ptr=" << it._Ptr << " *it=" << *it << endl; } cout << "-----------方法三--------------" << endl; //方法三 for (size_t i = 0; i < v.size(); i++) { cout << "&v[i]=" << &v[i] << " v[i]=" << v[i] << endl; } cout << "---------方法四----------------" << endl; //方法四 for_each(v.begin(), v.end(), myPrint); }
執行結果
vector測試
//vector測試
void test7()
{
vector<int>v;
for (size_t i = 0; i < 100; i++)
{
cout << "v.size()=" << v.size() << " v.capacity()=" << v.capacity() << " sizeof(v)=" << sizeof(v) << endl;
v.push_back(1);
}
}
執行結果
迭代器
void test6() { vector<int> v; v.push_back(11); v.push_back(22); v.push_back(33); v.push_back(44); v.push_back(55); vector<int>::iterator begin = v.begin(); vector<int>::iterator end = v.end(); while (begin!=end) { cout <<"begin._Ptr="<<begin._Ptr<<" *begin=" << *begin << endl; begin++; } }
執行結果