I.Giới thiệu :
Vector thực ra nó cũng như mãng vậy nhưng cách xài thì linh hoạt hơn nhiều, và đây là 1 số điểm nổi trội của vector so với mãng :
- Bạn không cần phải khai báo kích thước của mãng ví dụ int A[100]..., vector có thể tự động nâng kíck thước lên.
- Nếu bạn thêm 1 phần tử vào vector đã đầy rồi, thì vector sẽ tự động tăng kíck thước của nó lên để dành chỗ cho giá trị mới này.- Vector còn có thể cho bạn biết số lượng các phần tử mà bạn đang lưu trong nó.
- Dùng số phần tử âm vẫn được trong vector ví dụ A-10], A[-3], rất tiện trong việc cài đặt các giải thuật cần kĩ thuật lính canh.
II.Cách dùng vector :
Để có thể xài vectors thì bạn phải thêm cho nó 1 header file sau :
PHP Code:
#include <vector>
và phải có
PHP Code:
using namespace std
Vì vector bản chất là thuộc STL( Standard Template Library).
III.Cú pháp :
Cú pháp của vector cũng rất đơn giản ví dụ :
PHP Code:
vector<int> A ;
Câu lệnh trên định nghĩa 1 vector có kiểu int. Chú ý kiểu của vector được để trong 2 cái ngoặc nhọn. Vì kíck thước của vector có thể nâng lên, cho nên không cần khai báo cho nó có bao nhiêu phần tử cũng được, hoặc nếu thích khai báo thì bạn cũng có thể khai báo như sau :
PHP Code:
vector<int> A(10);
Câu lệnh trên khai báo A là 1 vector kiểu int có 10 phần tử. Tuy nhiên như đã nói ở trên, mặc dù size = 10, nhưng khi bạn add vào thì nó vẫn cho phép như thường.
Và ta cũng có thể khởi tạo cho các phần tử trong vector bằng cú pháp đơn giản như sau :
PHP Code:
vector<int> A(10, 2);
Trong câu lện trên thì 10 phần tử của vector A sẽ được khởi tạo bằng 2.
Đồng thời ta cũng có thể khởi tạo cho 1 vector bằng giá trị của 1 vector khác, ví dụ :
PHP Code:
vector<int> A(10,2);
vector<int> B(A);
Với dòng lệnh trên thì vector B sẽ là bản sao của vector A.
Một số ví dụ về khai báo vector :
PHP Code:
vector<float> A;
vector<int> B(15);
vector<char> C(25, 'A');
Sau đây sẽ là 1 đoạn code nhỏ mô tả cách xài vector :
Ví dụ 1
PHP Code:
//Chương trình này sẽ lưu vào 2 vector "hours" và "payRate"
//5 người employees và hour work của họ.
#include <iostream>
#include <iomanip>
#include <vector> // Nhớ cái này nha !!
using namespace std; // Cái này nữa
int main()
{
const int NUM_EMPLOYEES = 5; // Number of employees
vector<int> hours(NUM_EMPLOYEES); // Một vector hours kiểu int
vector<double> payRate(NUM_EMPLOYEES); // Một vector payRate kiểu
//double
int index;
// Nhập dữ liệu
cout << "Enter the hours worked by " << NUM_EMPLOYEES;
cout << " employees and their hourly rates.\n";
for (index = 0; index < NUM_EMPLOYEES; index++)
{
cout << "Hours worked by employee #" << (index + 1);
cout << ": ";
cin >> hours[index];
cout << "Hourly pay rate for employee #";
cout << (index + 1) << ": ";
cin >> payRate[index];
}
// In ra dữ liệu nhập vào
cout << "\nHere is the gross pay for each employee:\n";
cout << fixed << showpoint << setprecision(2);
for (index = 0; index < NUM_EMPLOYEES; index++)
{
double grossPay = hours[index] * payRate[index];
cout << "Employee #" << (index + 1);
cout << ": $" << grossPay << endl;
}
return 0;
}
Output
Code:
Enter the hours worked by 5 employees and their hourly rates.
Hours worked by employee #1: 10 [enter]
Hourly pay rate for employee #1: 9.75 [enter]
Hours worked by employee #2: 15 [enter]
Hourly pay rate for employee #2: 8.62 [enter]
Hours worked by employee #3: 20 [enter]
Hourly pay rate for employee #3: 40 [enter]
Hours worked by employee #4: 18.75 [enter]
Hourly pay rate for employee #4: Hours worked by employee #5: 40 [enter]
Hourly pay rate for employee #5: 15.65 [enter]
Here is the gross pay for each employee:
Employee #1: $97.50
Employee #2: $129.30
Employee #3: $800.00
Employee #4: $13.50
Employee #5: $626.00
Press any key to continue . . .
Chú ý về chương trình trên là cả 2 vector đều có size là 5, và chương trình sẽ dùng vòng lặp for để lưu các giá trị của cả 2 vector :
PHP Code:
for (index = 0; index < NUM_EMPLOYEES; index++)
{
cout << "Hours worked by employee #" << (index + 1);
cout << ": ";
cin >> hours[index];
cout << "Hourly pay rate for employee #";
cout << (index + 1) << ": ";
cin >> payRate[index];
}
IV.Cách sử dụng hàm thành viên của vector "push_back" :
Chú ý bạn không thể dùng toán tử [] để truy xuất các phần tử mà nó không tồn tại, nghĩa là ví dụ vector size = 10, mà bạn truy xuất 11 là banh xác. Để thêm vào 1 giá trị cho vector mà nó không có size trước hoặc đã full thì ta dùng hàm thành viên "push_back". Ví dụ :
PHP Code:
A.push_back(25);
Với câu lệnh trên thì giả sử ta đang có 1 vector A kiểu int, với size bao nhiêu đó, nếu nó chưa full thì 25 sẽ thay cho phần tử cuối cùng. Còn nếu không full thì nó sẽ tạo 1 chỗ mới dành cho thằng 25 này. Đoạn code dưới đây sẽ mô tả cách dùng của hàm push_back này :
Ví dụ 2:
PHP Code:
#include <iostream>
#include <iomanip>
#include <vector> // Needed to define vectors
using namespace std;
int main()
{
vector<int> hours; // hours bây h là vector rỗng
vector<double> payRate; // payRate cũng là 1 vector rỗng
int numEmployees;
int index;
// Lấy số lượng employees
cout << "How many employees do you have? ";
cin >> numEmployees;
// Nhập dữ liệu
cout << "Enter the hours worked by " << numEmployees;
cout << " employees and their hourly rates.\n";
for (index = 0; index < numEmployees; index++)
{
int tempHours; // To hold the number of hours entered
double tempRate; // To hold the payrate entered
cout << "Hours worked by employee #" << (index + 1);
cout << ": ";
cin >> tempHours;
hours.push_back(tempHours); // Thêm phần tử vào vector hours.
cout << "Hourly pay rate for employee #";
cout << (index + 1) << ": ";
cin >> tempRate;
payRate.push_back(tempRate); // Thêm phần tử vào vector payRate
}
//In ra giá trị
cout << "Here is the gross pay for each employee:\n";
cout << fixed << showpoint << setprecision(2);
for (index = 0; index < numEmployees; index++)
{
double grossPay = hours[index] * payRate[index];
cout << "Employee #" << (index + 1);
cout << ": $" << grossPay << endl;
}
return 0;
}
Output
Code:
How many employees do you have? 3 [enter]
Enter the hours worked by 3 employees and their hourly rates.
Hours worked by employee #1: 40 [enter]
Hourly pay rate for employee #1: 12.63 [enter]
Hours worked by employee #2: 25 [enter]
Hourly pay rate for employee #2: 10.35 [enter]
Hours worked by employee #3: 45 [enter]
Hourly pay rate for employee #3: 22.65 [enter]
Here is the gross pay for each employee:
Employee #1: $505.20
Employee #2: $258.75
Employee #3: $1019.25
Press any key to continue . . .
V.Xác định kíck thước của vector thông qua hàm size():
Không giống với mãng, dùng vector ta có thể thông báo được kíck thước hiện thời mà nó đang có với cú pháp cực kì đơn giản như sau :
PHP Code:
int numberValues = A.size()
Ví dụ 3
PHP Code:
#include <iostream>
#include <vector>
using namespace std;
// Function prototype
void showValues(vector<int>);
int main()
{
vector<int> values;
// Thêm vào vector values 7 giá trị
for (int count = 0; count < 7; count++)
values.push_back(count * 2);
//In ra kết quả
showValues(values);
return 0;
}
//**************************************************
// Chú ý định nghĩa của hàm showValues *
// Hàm này nhận vector kiểu int là đối, và giá trị *
// của 1 phần tử sẽ được in ra * *
//**************************************************
void showValues(vector<int> vect)
{
for (int count = 0; count < vect.size(); count++)
cout << vect[count] << endl;
}
Output
Code:
0
2
4
6
8
10
12
Press any key to continue . . .
VI.Xoá 1 phần tử trong vector bằng hàm thành viên pop_back
Cú pháp cũng đơn giản như sau :
Và sau đây là ví dụ về cách xài :
ví dụ 4
PHP Code:
// Chương trình này mô tả cách xài của hàm pop_back()
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> values;
//Thêm dữ liệu vào vector values.
values.push_back(1);
values.push_back(2);
values.push_back(3);
cout << "The size of values is " << values.size() << endl;
//Xoá là đây!!.
cout << "Popping a value from the vector...\n";
values.pop_back();
cout << "The size of values is now " << values.size() << endl;
// Xoá tiếp.
cout << "Popping a value from the vector...\n";
values.pop_back();
cout << "The size of values is now " << values.size() << endl;
//Xoá nữa, xoá cho hết thì thôi ^^.
cout << "Popping a value from the vector...\n";
values.pop_back();
cout << "The size of values is now " << values.size() << endl;
return 0;
}
Output
Code:
The size of values is 3
Popping a value from the vector...
The size of values is now 2
Popping a value from the vector...
The size of values is now 1
Popping a value from the vector...
The size of values is now 0
Press any key to continue . . .
VII. Dùng hàm thành viên clear() để xoá sạch sẽ các phần tử của vector
Nếu muốn diệt cỏ tận gốc thì dùng hàm clear với cú pháp như sau :
Ví dụ 5
PHP Code:
// Mô tả cách dùng hàm clear().
#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;
}
Code:
The values vector has 100 elements.
I will call the clear member function...
Now, the values vector has 0 elements.
Press any key to continue . . .
VII. Dùng hàm thành viên empty() để kiểm tra xem vector có rỗng hay không
Để xác định vector có rỗng hay không ta dùng hàm thành viên empty(), hàm này trả về true nếu vector rỗng, và false ngược lại. Cú pháp :
PHP Code:
if(A.empty() == true){
cout << "No values in A \n";
}
Ví dụ 7
PHP Code:
// This program demonstrates the vector's empty member function.
#include <iostream>
#include <vector>
using namespace std;
// Function prototype
double avgVector(vector<int>);
int main()
{
vector<int> values; // Khai báo vector values kiểu int
int numValues; // số lượng pần tử
double average; // biến lưu giá trị trung bình
// Lấy số lượng phần tử để tính trung bình
cout << "How many values do you wish to average? ";
cin >> numValues;
// Lưu giá trị vào vector.
for (int count = 0; count < numValues; count++)
{
int tempValue;
cout << "Enter a value: ";
cin >> tempValue;
values.push_back(tempValue);
}
// Tính giá trị trung bình và in ra.
average = avgVector(values);
cout << "Average: " << average << endl;
return 0;
}
//*************************************************************
// Hàm argVector này sẽ nhận 1 đố số là 1 vector *
// kiểu int. hàm này trả về giá trị trung bình của các phần tử *
// của vector. Nếu vector rỗng thì lỗi sẽ được báo,
//và hàm trả về 0.0 *
//*************************************************************
double avgVector(vector<int> vect)
{
int total = 0; //Tổng
double avg; // giá trị trung bình
if (vect.empty()) //kiểm tra xem vector có rỗng không
{
cout << "No values to average.\n";
avg = 0.0;
}
else
{
for (int count = 0; count < vect.size(); count++)
total += vect[count];
avg = total / vect.size();
}
return avg;
}
Output 1
Code:
How many values do you wish to average? 5 [enter]
Enter a value: 12 [enter]
Enter a value: 18 [enter]
Enter a value: 3 [enter]
Enter a value: 7 [enter]
Enter a value: 9 [enter]
Average: 9
Press any key to continue . . .
Output 2
Code:
How many values do you wish to average? 0 [enter]
No values to average.
Average: 0
Press any key to continue . . .
Một số hàm khác và chức năng
- at(element) : Trả về giá trị của phần tử thứ element của vector. Ví dụ :
- capacity() : Trả về số lượng các phần tử mà vector đang lưu trữ. Ví dụ :
PHP Code:
x = A.capacity();
- reverse() : Đảo thứ tự của các phần tử( phần tử đầu thành phần tử cuối...) Ví dụ :
- swap(vertor2); : Đổi chỗ nội dung của vector1 với vector2. Ví dụ :
PHP Code:
vect1.swap(vect2);
- resize(elements, value) : Định nghĩa lại kíck thước bằng elements, mỗi elements này sẽ được khởi tạo với giá trị là value. Ví dụ :