Như các bạn đã biết, array là 1 collection các kiểu dữ liệu đồng nhất (mảng các số nguyên, mảng các số thực,…). Mảng trong STL giúp cho developer define đối tượng array gồm có phần dữ liệu + function.
Cú pháp
array <object_type, array_size> array_name;
object_type: kiểu dữ liệu (int, float, CString,…)
array_size: số lượng phần tử trong mảng, phải là hằng số.
array_name: tên đối tượng array
Function
Tên hàm | Giải thích |
at(i) |
|
Toán tử [i] |
|
front() |
|
back() |
|
fill(i) |
|
swap() |
|
operators ( == , != , > , < , >= , <= ) |
|
empty( ) |
|
size( ) |
|
max_size( ) |
|
begin( ) |
|
end( ) |
|
Ví dụ: Implement các function của array.
#include <iostream> #include <array> using namespace std; int main () { std::array<int,10> array1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; std::array<int,10> array2 = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; /* Function at()*/ cout << "array1[2] = " << array1.at(2) << endl; // prints 3 cout << "array2[9] = " << array2.at(9) << endl; // prints 20 /* Operator []*/ cout << "array1[5] = " << array1[5] << endl; // prints 6 /* Function front()*/ cout << "array1.front() = " << array1.front() << endl; // prints 1 /* Function back()*/ cout << "array1.back() = " << array1.back() << endl; // prints 10 /* Function fill()*/ array1.fill(11); // fill 11 for all elements of array1 /* Function swap()*/ array1.swap(array2); /* operators ( == , != , > , < , >= , <= ) */ if (array1 == array2) cout << "array1 is equal to array2" << endl; else if (array1 > array2) cout << "array1 is greater than array2" << endl; else cout << "array1 is less than array2" << endl; /* Function empty()*/ if (array1.empty()) cout << "array1 is empty" << endl; else cout << "array1 is NOT empty" << endl; /* Function size()*/ cout << "size = " << array1.size() << endl; /* Function max_size()*/ cout << "max_size = " << array1.max_size() << endl; /* Function begin(), end()*/ cout << "array 1 = "; for (auto i = array1.begin(); i != array1.end(); ++i) { cout << *i << " "; // prints 11, 12, 13,...20 } system("pause"); }
Leave a Reply
You must be logged in to post a comment.