標准模板庫包含一個成為矢量(vector)的數據類型。它與一位數組類似,但與標准數組相比有一些優點。
標准模板庫(STL)是程序員定義的數據類型和算法的集合,可以供C++程序使用。這些數據類型和算法不是C++語言的一部分,但它們的創建是對內置數據類型的有益補充。如果打算繼續在計算機領域學習,那么就應該熟悉STL。現在介紹STL數據類型之一:矢量。
注意:要使用矢量,則程序的頭文件必須指明使用namespace std,因為矢量包含在該命名空間中。許多較早的編譯器不允許命名空間或不支持STL。
在STL中定義的數據類型通常稱為容器(Container)。它們之所以稱為容器,是因為他們存儲和組織數據。STL中有兩種類型的容器:順序容器和關聯容器。順序容器以序列方式組織數據,類似於數組。關聯容器使用關鍵字組織數據,它允許對存儲在容器中的元素進行快速隨機訪問。
vector數據類型是一個序列式容器,它很像一個一維數組,其表現和數組相似的地方如下:
1)矢量包括一系列值或者元素。
2)矢量將其元素存儲在連續的內存位置中。
3)可以使用數組下標運算符[]訪問矢量中的各個元素。
但是,矢量相對於數組還有幾個優點:
1)不必聲明矢量將具有的元素的數量。
2)如果向已滿的矢量添加值,則矢量將自動增加其大小以適應新值。
3)矢量可以報告它們包含的元素的數量。
1. 定義和初始化矢量
要在程序中使用矢量,則必須使用以下語句包含vector頭文件: #include <vector>
創建矢量對象的語法與定義一個常規變量或數組所用的語法有所不同。以下是一個例子:
vector<int> numbers;
這個語句將numbers定義為一個int的矢量。請注意,數據類型包含在尖括號內,緊跟在單詞vector之后。由於矢量的大小隨着添加值而擴大,因此不需要聲明大小。不過,如果願意的話,也可以聲明一個開始大小。示例如下:
vector<int> numbers(10);
這個語句將numbers定義為10個整數的矢量,但這只是一個起始大小。如果添加10以上的值,它的大小會擴大。
注意:如果為矢量指定開始的大小,則大小聲明符將被括在圓括號中,而不是方括號中。
為矢量指定開始大小時,還可以指定一個初始化值。初始化值被復制到每個元素。示例如下:
vector<int> numbers(10,2);
在這個語句中,numbers被定義為10個整數矢量,並且numbers中的每個元素都被初始化值2。
也可以用另一個矢量中的值初始化一個矢量。例如,如果set1是已經有值的int矢量,則以下語句將創建一個名為set2的新矢量,它是set1的精確副本。 vector<int> set2(set1);
在執行這個語句之后,矢量set2將具有相同數量的元素,並保持與set1相同的一組值。
如果使用的是C++11版本,則還可以使用一個值列表來初始化vector,示例如下:
vector<int> numbers {10, 20, 30, 40};
該語句定義了一個名為numbers的int矢量。該矢量有4個元素,其初始化值為10,20,30和40。注意,初始化列表被括在一組大括號中,但是在它前面不使用賦值運算符(=)。
矢量定義示例:
定義格式 描述
vector<string> names; 將names定義為string對象的空矢量。
vector<int> scores(15); 將scores定義為15個整數的矢量。
vector<char> letters(25, 'A'); 將letters定義為25個字符的矢量。每個元素都用'A'初始化。
vector<double> values2(values1); 將values2定義為double矢量。value1的所有元素(也是double矢量)將被復制到values2。
vector<int> length {12, 10, 6}; 在C++11中,該語句定義length為3個int值的矢量,保存值12, 10和6。
2. 存儲和檢索矢量中的值
要將值存儲到已存在的矢量元素中,或訪問矢量元素中存儲的數據,可以使用數組下標運算符[]。示例代碼如下:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
const int NUM_EMPS = 5;
vector <int> hours(NUM_EMPS);
vector <double> payRate(NUM_EMPS);
double grossPay;
cout<<"Enter the hours worked and hourly pay rates of "
<<NUM_EMPS<<" employees.\n";
for(int index = 0; index < NUM_EMPS; index++)
{
cout<<"\nHours worked by employee #" << (index + 1) << ": ";
cin>>hours[index];
cout<<"Hourly pay rate for employee #"<<(index + 1) << ": ";
cin>>payRate[index];
}
//Display each employee's gross pay
cout<<"\nHere is the gross pay for each employee:\n";
cout<<fixed<<showpoint<<setprecision(2);
for(int index = 0; index < NUM_EMPS; index++)
{
grossPay = hours[index] * payRate[index];
cout<<"Employee #"<<(index + 1);
cout<<": $"<<setw(7)<<grossPay<<endl;
}
return 0;
}
結果:
3. 使用push_back成員函數
不能使用[]運算符來訪問尚不存在的矢量元素。要將值存儲在沒有起始大小或已滿的矢量中,應使用push_back成員函數。該函數接受一個值作為參數,並將其存儲在位於矢量末尾的新元素中。
以下是一個使用push_back函數,將一個元素添加到一個名為numbers的int矢量的例子:
numbers.push_back(25);
該語句可以創建一個新的元素,其存儲的值為25,該元素被放在numbers矢量的末尾。如果numbers以前沒有元素,則新元素將成為其單一元素。
示例代碼:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
vector<int> hours;
vector<double> payRate;
double grossPay;
int numEmployees;
int index;
//get the number of employees
cout<<"How many employees do you have? ";
cin>>numEmployees;
cout<<"Enter the hours worked and hourly pay rates of the "
<<numEmployees << " employees.\n";
for(index = 0; index < numEmployees; index++)
{
int tempHours;
double tempRate;
cout<<"Hours worked by employee #"<<(index+1)<<":";
cin>>tempHours;
hours.push_back(tempHours);
cout<<"Hourly pay rate for employee #"<<(index+1)<<":";
cin>>tempRate;
payRate.push_back(tempRate);
}
//Display each employee's gross pay
cout<<"\nHere is the gross pay for each employee:\n";
cout<<fixed<<showpoint<<setprecision(2);
for(index =0; index < numEmployees; index++)
{
grossPay = hours[index] * payRate[index];
cout<<"Employee #"<<(index+1);
cout<<": $"<<setw(7)<<grossPay<<endl;
}
return 0;
}
結果:
4. 確定矢量的大小
與數組不同,矢量可以報告它們包含的元素的數量,這是通過size成員函數實現的。以下是一個使用size成員函數的示例:
numValues = set.size();
在該語句中,假定numValues是一個int, set是一個矢量。執行語句后,numValues將包含set中的元素數量。
在編寫接收矢量作為實參的函數時,size成員函數特別有用。例如,來看showValues函數的代碼:
void showValues(vector<int> vect)
{
for(int i = 0; i < vect.size(); i++)
cout<<vect[i]<<endl;
}
因為矢量可以報告其大小,所以該函數不需要第二個參數來表示矢量中元素的個數。示例程序如下:
#include <iostream>
#include <vector>
using namespace std;
void showValues(vector<int>);
int main()
{
vector <int> values;
//store a series of numbers int the vector
for(int count = 0; count < 7; count++)
values.push_back(count * 2);
//Display the numbers
showValues(values);
return 0;
}
void showValues(vector<int> vect)
{
for(int count = 0; count < vect.size(); count++)
cout<<vect[count]<<" ";
cout<<endl;
}
結果:
5. 從矢量中刪除元素
要從矢量中刪除最后一個元素,可以使用pop_bach成員函數。以下語句從名為collection的矢量中移除最后一個元素:
collection.pop_back();
程序示例:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> values;
//Store values in the vector
values.push_back(1);
values.push_back(2);
values.push_back(3);
cout<<"The size of values is "<<values.size()<<endl;
//Remove a value from the vector
cout<<"Popping a value from the vector...\n";
values.pop_back();
cout<<"The size of values is now "<<values.size()<<endl;
//Now remove another value from the vector
cout<<"Popping a value from the vector...\n";
values.pop_back();
cout<<"The size of values is now "<<values.size()<<endl;
//Remove the last value from the vector
cout<<"Popping a value from the vector ...\n";
values.pop_back();
cout<<"The size of values is now "<<values.size()<<endl;
return 0;
}
結果:
注意:pop_back函數是一個void函數,它不返回將從矢量中刪除的值。以下代碼行將不起作用:
cout<<"The value being removing from the vector is "
<<values.pop_back()<<endl; //Error!
6. 清理矢量
要完全清除矢量的內容,可以使用clear成員函數,如下所示:
numbers.clear();
在執行該語句后,numbers的所有元素將被清除。示例代碼:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector < int > values(100);
cout<<"The values vector has "
<<values.size()<<" elements.\n";
cout<<"I will call the clear member function ... \n";
values.clear();
cout<<"Now the values vector has "
<<values.size()<<" elements.\n";
return 0;
}
結果:
7. 檢測一個空矢量
要確定一個矢量是否為空,可以使用empty成員函數。如果矢量為空,則該函數將返回true;如果矢量中存儲有元素,則返回false。假設numberVector是一個矢量,以下是其應用示例:
if(numberVector.empty())
cout<<"No values in numberVector.\n";
示例代碼:
#include <iostream>
#include <vector>
using namespace std;
double avgVector(vector<int>);
int main()
{
vector<int> values;
int numValues;
double average;
cout<<"How many values do you want to average? ";
cin>>numValues;
//Get the values and store them in a vector
for(int count = 0; count < numValues; count++)
{
int tempValue;
cout<<"Enter an integer values: ";
cin>>tempValue;
values.push_back(tempValue);
}
//Get the average of the values and display it
average = avgVector(values);
cout<<"Average: "<<average<<endl;
return 0;
}
double avgVector(vector<int> vect)
{
int total = 0;
double avg = 0.0;
if(vect.empty())
cout<<"No values to average.\n";
else
{
for(int count = 0; count < vect.size(); count++)
total+=vect[count];
avg = static_cast<double>(total)/vect.size();
}
return avg;
}
結果:
8. 矢量成員函數匯總
成員函數 描述
at(position) 返回vector中位於position位置的元素的值。
示例:x = vect.at(5); //將vect[5]的賦值給x
capacity() 返回在不重新分配額外內存的情況下,可能存儲在矢量中的最大元素數量(它和由size成員函數返回的值並不是一回事)。
示例: x = vect.capacity(); //將vect的容量賦值給x。
clear() 清楚矢量的所有元素。
示例: vect.clear(); //從vect中移除所有元素
empty() 如果vector是空的,則返回true。否則,它返回false。示例:
if( vect.empty() ) //如果該矢量是空的
cout << "The vector is empty."; //顯示該消息
pop_back() 從矢量中刪除最后一個元素。
示例: vect.pop_back(); //移除vect的最后一個元素 ,使其大小減去1
push_back(value) 在矢量的最后一個元素中存儲一個值。如果矢量已滿或為空,則會創建一個新元素。
示例: vect.push_back(7); //在vect的最后一個元素中存儲7.
reverse() 反轉矢量中元素的順序(最后一個元素變成第一個元素,第一個元素成為最后一個元素)。
示例: vect.reverse(); //反轉vect中元素的順序
resize(n)、resize(n,value) 調整矢量的大小以使其具有n個元素,其中n大於矢量當前大小。如果包含可選的參數value,則每個新元素都將使用該value值進行初始化。如果不指定value的話,所有沒有元素的位置上都被初始化為0,vect當前已經有4個元素情況下的示例:
vect.resize(6,99) //將兩個元素添加到矢量的末尾,每個元素的初始化為99
size() 返回矢量中元素的數量。示例:
numElements = vect.size();
swap(vector2) 將矢量的內容與vector2的內容交換。示例:
vect1.swap(vect2); //交換vect1和vect2的內容