在C++使用array
前言
在使用Drogon搭建博客的时候,在获取数据的时候,一直是都在使用vector,因为不确定返回的元素的个数,所以使用vector是很合适的.在能确定元素个数的时候,应该使用数组.简单说一下C++的容器有那些:
array使用
std::array<int, 10> arr = { 1,2,3,9,6,8,7,4,5 }; //指定arr的元素个数为10
if (arr.empty()) { //检查数组是否为空
}
std::cout << "arr size:" << arr.size() << std::endl; //获取数组的个数
std::cout << "sort before:" << std::endl;
for (auto& v : arr) //循环数组的元素值
{
std::cout << v << std::endl;
}
std::sort(arr.begin(), arr.end());
std::cout << "sort before:" << std::endl;
for (auto& v : arr)
{
std::cout << v << std::endl;
}
arr.fill(0);//将数组内的所有元素值赋值为0
数组转set和map
std::unordered_set<int> set;
for (auto& v : arr)
{
set.emplace(v); //将数组元素放入set中
}
std::array<std::string, 3> content = { "hello","hi","test"};
std::unordered_map<std::string, int> map;
for (auto &item :content)
{
map.emplace(std::pair<std::string, int>(item, 0)); //将数组元素放入map中
}
秋风
2023-04-02