分类: C/C++
2014-04-18 10:56:27
// constructing vectors #include#include using namespace std; int main () { unsigned int i; // constructors used in the same order as described above: vector<int> first; // empty vector of ints vector<int> second (4,100); // four ints with value 100 vector<int> third (second.begin(),second.end()); // iterating through second vector<int> fourth (third); // a copy of third // the iterator constructor can also be used to construct from arrays: int myints[] = {16,2,77,29}; vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) ); cout << "The contents of fifth are:"; for (i=0; i < fifth.size(); i++) cout << " " << fifth[i]; cout << endl; return 0; }
// vector::operator[] #include#include using namespace std; int main () { vector<int> myvector (10); // 10 zero-initialized elements unsigned int i; vector<int>::size_type sz = myvector.size(); // assign some values: for (i=0; i // reverse vector using operator[]: for (i=0; i 2; i++) { int temp; temp = myvector[sz-1-i]; myvector[sz-1-i]=myvector[i]; myvector[i]=temp; } cout << "myvector contains:"; for (i=0; i " " << myvector[i]; cout << endl; return 0; }
// vector::push_back #include#include using namespace std; int main () { vector<int> myvector; int myint; cout << "Please enter some integers (enter 0 to end):\n"; do { cin >> myint; myvector.push_back (myint); } while (myint); cout << "myvector stores " << (int) myvector.size() << " numbers.\n"; return 0; }
// inserting into a vector #include#include using namespace std; int main () { vector<int> myvector (3,100); vector<int>::iterator it; it = myvector.begin(); it = myvector.insert ( it , 200 ); myvector.insert (it,2,300); // "it" no longer valid, get a new one: it = myvector.begin(); vector<int> anothervector (2,400); myvector.insert (it+2,anothervector.begin(),anothervector.end()); int myarray [] = { 501,502,503 }; myvector.insert (myvector.begin(), myarray, myarray+3); cout << "myvector contains:"; for (it=myvector.begin(); it " " << *it; cout << endl; return 0; }
// erasing from vector #include#include using namespace std; int main () { unsigned int i; vector int> myvector; // set some values (from 1 to 10) for (i=1; i<=10; i++) myvector.push_back(i); // erase the 6th element myvector.erase (myvector.begin()+5); // erase the first 3 elements: myvector.erase (myvector.begin(),myvector.begin()+3); cout << "myvector contains:"; for (i=0; i " " << myvector[i]; cout << endl; return 0; }
// clearing vectors #include#include using namespace std; int main () { unsigned int i; vector<int> myvector; myvector.push_back (100); myvector.push_back (200); myvector.push_back (300); cout << "myvector contains:"; for (i=0; i " " << myvector[i]; myvector.clear(); myvector.push_back (1101); myvector.push_back (2202); cout << "\nmyvector contains:"; for (i=0; i " " << myvector[i]; cout << endl; return 0; }