Monday, March 7, 2022

Basics: Array & Dynamic Array

Introduction to Array

#include <iostream>
int main() {
// 1. Initialize
int a0[5];
int a1[5] = {1, 2, 3}; // other element will be set as the default value
// 2. Get Length
int size = sizeof(a1) / sizeof(*a1);
cout << "The size of a1 is: " << size << endl;
// 3. Access Element
cout << "The first element is: " << a1[0] << endl;
// 4. Iterate all Elements
cout << "[Version 1] The contents of a1 are:";
for (int i = 0; i < size; ++i) {
cout << " " << a1[i];
}
cout << endl;
cout << "[Version 2] The contents of a1 are:";
for (int& item: a1) {
cout << " " << item;
}
cout << endl;
// 5. Modify Element
a1[0] = 4;
// 6. Sort
sort(a1, a1 + size);
}
/*
Finished in 3 ms
The size of a1 is: 5
The first element is: 1
[Version 1] The contents of a1 are: 1 2 3 0 0
[Version 2] The contents of a1 are: 1 2 3 0 0
*/

Introduction to Dynamic Array

#include <iostream>
int main() {
// 1. initialize
vector<int> v0;
vector<int> v1(5, 0);
// 2. make a copy
vector<int> v2(v1.begin(), v1.end());
vector<int> v3(v2);
// 2. cast an array to a vector
int a[5] = {0, 1, 2, 3, 4};
vector<int> v4(a, *(&a + 1));
// 3. get length
cout << "The size of v4 is: " << v4.size() << endl;
// 4. access element
cout << "The first element in v4 is: " << v4[0] << endl;
// 5. iterate the vector
cout << "[Version 1] The contents of v4 are:";
for (int i = 0; i < v4.size(); ++i) {
cout << " " << v4[i];
}
cout << endl;
cout << "[Version 2] The contents of v4 are:";
for (int& item : v4) {
cout << " " << item;
}
cout << endl;
cout << "[Version 3] The contents of v4 are:";
for (auto item = v4.begin(); item != v4.end(); ++item) {
cout << " " << *item;
}
cout << endl;
// 6. modify element
v4[0] = 5;
// 7. sort
sort(v4.begin(), v4.end());
// 8. add new element at the end of the vector
v4.push_back(-1);
// 9. delete the last element
v4.pop_back();
}
/*
The size of v4 is: 5
The first element in v4 is: 0
[Version 1] The contents of v4 are: 0 1 2 3 4
[Version 2] The contents of v4 are: 0 1 2 3 4
[Version 3] The contents of v4 are: 0 1 2 3 4
*/

Introduction to 2D Array

#include <iostream>
template <size_t n, size_t m>
void printArray(int (&a)[n][m]) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cout << a[i][j] << " ";
}
cout << endl;
}
}
int main() {
cout << "Example I:" << endl;
int a[2][5];
printArray(a);
cout << "Example II:" << endl;
int b[2][5] = {{1, 2, 3}};
printArray(b);
cout << "Example III:"<< endl;
int c[][5] = {1, 2, 3, 4, 5, 6, 7};
printArray(c);
cout << "Example IV:" << endl;
int d[][5] = {{1, 2, 3, 4}, {5, 6}, {7}};
printArray(d);
}
/*
Example I:
-1511528224 32563 -1511527904 32563 -1511524608
32563 2 0 54005184 0
Example II:
1 2 3 0 0
0 0 0 0 0
Example III:
1 2 3 4 5
6 7 0 0 0
Example IV:
1 2 3 4 0
5 6 0 0 0
7 0 0 0 0
*/
view raw 2D Array.cpp hosted with ❤ by GitHub

No comments:

Post a Comment