#include<iostream> #include<vector> #include<numeric> using namespace std; int main(){ vector<int> v; int i; for(int i = 0;i < 10;i++){ //尾部元素擴張方式賦值 v.push_back(i); } //使用iterator迭代器順序遍歷全部元素 for(vector<int>::iterator it = v.begin();it!=v.end();it++){ cout << *it << " "; } cout << endl; cout << accumulate(v.begin(),v.end(),0) << endl; return 0; }
#include<iostream> #include<vector> #include<numeric> using namespace std; int main(){ vector<int> v(3); v[0] = 1; v[1] = 2; v[2] = 3; cout << v[0] << " " << v[1]<< endl; }
#include<iostream> #include<vector> #include<numeric> using namespace std; int main(){ vector<int> v(3); v[0] = 1; v[1] = 2; v[2] = 3; vector<int>::iterator it; for(it = v.begin();it != v.end();it++){ //輸出迭代器上的元素值 cout << *it << " "; } return 0; }
#include<iostream> #include<vector> #include<numeric> using namespace std; int main(){ vector<int> v(3); v[0] = 1; v[1] = 2; v[2] = 3; //在前面插入新元素,元素值爲8; v.insert(v.begin(),8); //在第二個元素前插入新元素1 v.insert(v.begin()+2,1); //在向量尾追加新元素3 v.insert(v.end(),3); //定義迭代器變量 vector<int>::iterator it; for(it = v.begin();it != v.end();it ++) { //輸出迭代器的元素值 cout << *it << " "; } //換行 cout << endl; return 0; } //8 1 1 2 3 3
#include<iostream> #include<vector> #include<numeric> using namespace std; int main(){ vector<int> v(3); v[0] = 1; v[1] = 2; v[2] = 3; //在前面插入新元素,元素值爲8; v.insert(v.begin(),8); //在第二個元素前插入新元素1 v.insert(v.begin()+2,1); //在向量尾追加新元素3 v.insert(v.end(),3); //定義迭代器變量 vector<int>::iterator it; for(it = v.begin();it != v.end();it ++) { //輸出迭代器的元素值 cout << *it << " "; } //換行 cout << endl; return 0; }