程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++ vector MSDN簡單入門解釋

C++ vector MSDN簡單入門解釋

編輯:C++入門知識

// VectorTest.cpp : 定義控制台應用程序的入口點。
//


#include "stdafx.h"


// Empty.cpp
// compile with: /EHsc
// Illustrates the vector::empty and vector::erase functions.
// Also demonstrates the vector::push_back function.
//
// Functions:
//
//    vector::empty - Returns true if vector has no elements.
//
//    vector::erase - Deletes elements from a vector (single & range).
//
//    vector::begin - Returns an iterator to start traversal of the
//                    vector.
//
//    vector::end - Returns an iterator for the last element of the
//                  vector.
//
//    vector::push_back - Appends (inserts) an element to the end of a
//                        vector, allocating memory for it if necessary.
//
//    vector::iterator - Traverses the vector.
//
//////////////////////////////////////////////////////////////////////


// The debugger can't handle symbols more than 255 characters long.
// STL often creates symbols longer than that.
// When symbols are longer than 255 characters, the warning is disabled.
#pragma warning(disable:4786)


#include <iostream>
#include <vector>


using namespace std ;


typedef vector<int> INTVECTOR;


const int ARRAY_SIZE = 10;


void ShowVector(INTVECTOR &theVector);


int _tmain(int argc, _TCHAR* argv[])
{


// Dynamically allocated vector begins with 0 elements.
INTVECTOR theVector;


// Intialize the vector to contain the numbers 0-9.
for (int cEachItem = 0; cEachItem < ARRAY_SIZE; cEachItem++)
theVector.push_back(cEachItem);


// Output the contents of the dynamic vector of integers.
ShowVector(theVector);


// Using void iterator erase(iterator Iterator) to
// delete the 6th element (Index starts with 0).
theVector.erase(theVector.begin() + 5);


// Output the contents of the dynamic vector of integers.
ShowVector(theVector);


// Using iterator erase(iterator First, iterator Last) to
// delete a range of elements all at once.
theVector.erase(theVector.begin(), theVector.end());


// Show what's left (actually, nothing).
ShowVector(theVector);
}


// Output the contents of the dynamic vector or display a
// message if the vector is empty.
void ShowVector(INTVECTOR &theVector)
{
// First see if there's anything in the vector. Quit if so.
if (theVector.empty())
{
cout << "theVector is empty." << endl;
return;
}


// Iterator is used to loop through the vector.
INTVECTOR::iterator theIterator;


// Output contents of theVector.
cout << "theVector [ " ;
for (theIterator = theVector.begin(); theIterator != theVector.end();
theIterator++)
{
cout << *theIterator;
if (theIterator != theVector.end()-1) cout << ", ";
// cosmetics for the output
}
cout << " ]" << endl ;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved