1、数组的基本操作
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);
}
2、动态数组的基本操作
大多数编程语言都提供内置的动态数组,它仍然是一个随机存取的列表数据结构,但大小是可变的。例如,在 C++ 中的 vector
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,地址取地址二级指针,加1就直接移动一个数组的大小## 标题
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();
}
下文来源于链接: https://www.cnblogs.com/Tang-tangt/p/9352093.html.
最大值最小值
可以用max_element()及min_element()函数,二者返回的都是迭代器或指针。
头文件:#include
1.求数组的最大值或最小值
1)vector容器
例 vector vec
最大值:int maxValue = *max_element(v.begin(),v.end());
最小值:int minValue = *min_element(v.begin(),v.end());
2)普通数组
例 a[]={1,2,3,4,5,6};
最大值:int maxValue = *max_element(a,a+6);
最小值:int minValue = *min_element(a,a+6);
2.求数组最大值最小值对应的下标
1)vector容器
例 vector vec
最大值下标:int maxPosition = max_element(v.begin(),v.end()) - v.begin();
最小值下标:int minPosition = min_element(v.begin(),v.end()) - v.begin();
2)普通数组
例 a[]={1,2,3,4,5,6};
最大值下标:int maxPosition = max_element(a,a+6) - a;
最小值下标:int minPosition = min_element(a,a+6) - a;