array容器
#include <iostream>
#include <array>
#include <algorithm>
#include <numeric>
void display(const std::array<int,5> &arr){
for (const auto &i: arr)
std::cout << i << " ";
std::cout << std::endl;
}
void test1()
{
std::array <int,5> arr1 {1, 2, 3, 4, 5};
std::array <int,5> arr2;
arr2 = {10, 20, 30, 40, 50};
display(arr1);
display(arr2);
arr1[0] = 9;
arr1.at(1) = 8;
display(arr1);
std::cout << "获取第一个元素:" << arr1.front() << std::endl;
std::cout << "获取最后一个元素:" << arr1.back() << std::endl;
}
void test2()
{
std::array <int,5> arr1 {1, 2, 3, 4, 5};
std::array <int,5> arr2 {10, 20, 30, 40, 50};
arr1.swap(arr2);
display(arr1);
display(arr2);
}
void test3()
{
std::array <int,5> arr1 {1, 2, 3, 4, 5};
int *ptr = arr1.data();
std::cout << ptr << std::endl;
std::cout << *ptr << std::endl;
*ptr = 1000;
display(arr1);
}
void test4()
{
std::array <int,5> arr1 {4, 3, 2, 1, 5};
display(arr1);
std::sort(arr1.begin(), arr1.end());
display(arr1);
}
void test5()
{
std::array <int,5> arr1 {4, 3, 2, 1, 5};
std::array<int, 5>::iterator min_val = std::min_element(arr1.begin(), arr1.end());
auto max_val = std::max_element(arr1.begin(), arr1.end());
std::cout << "min: " << *min_val << std::endl;
std::cout << "max: " << *max_val << std::endl;
}
void test6()
{
std::array <int,5> arr1 {4, 3, 1, 6, 2};
std::cout << *arr1.begin() << std::endl;
std::cout << *(arr1.end()-1) << std::endl;
auto adjacent = std::adjacent_find(arr1.begin(), arr1.end());
if (adjacent != arr1.end())
std::cout << " " << *adjacent << std::endl;
else
std::cout << " 没有找到相邻两个相同的元素" << *adjacent << std::endl;
}
void test7()
{
std::array <int,5> arr1 {1, 1, 1, 1, 1};
int sum = std::accumulate(arr1.begin(), arr1.end(), 0);
std::cout << sum << std::endl;
}
void test8()
{
std::array <int,5> arr1 {1, 1, 1, 1, 1};
int counts = std::count(arr1.begin(), arr1.end(), 1);
std::cout << "1 共出现了 " <<counts << "次" <<std::endl;
}
int main()
{
test8();
}