静态数组
因为不良的习惯,上来写把代码写错
std::array<int,5> newArray();
newArray[0] = 0;
newArray[1] = 1;
这里带了()之后1,就变成了一个函数的声明,返回值为std::array<int,5 >,名叫newArray的函数。
在这里charno说,有没有什么办法可以在函数传参时中不输入具体的数组的大小,首先想到的当然是模板啦:
#include<iostream>
#include<array>
#define LOG(x) std::cout << x << std::endl
template<typename T, int N>
void PrintArray(const std::array<T,N>& data) {
for (size_t i = 0; i < data.size(); i++)
{
LOG(data[i]);
}
}
int main() {
std::array<int,5> newArray;
newArray[0] = 0;
newArray[1] = 1;
PrintArray(newArray);
}
for_each的方法,当然也可以使用for循环进行操作:
#include<algorithm>
#define LOG(x) std::cout << x << std::endl
void Print(int& n) {
LOG(n);
}
std::for_each(newArray.begin(),newArray.end(),Print);
在讲解array源码的时候,理解了为什么说调试级别宏非常好用,因为使用宏实现了在调试时提醒数组越界,在开发环境下没有提示!!!
array和普通数组相比,有边界检查,array存储在栈中,当速度最快的时候,是和普通数组一样的,它实际并不存储大小,size大小是直接给的模板参数,类中并不存储size变量,所以并不返回size变量,也不影响性能,而且有一些封装好的操作,更为便捷,比如下图中的排序:
std::array<int,5> newArray;
newArray[0] = 1;
newArray[1] = 0;
//这实际是一个数组类,可以进行一些额外的操作
PrintArray(newArray);
std::sort(newArray.begin(), newArray.end());
函数指针
正常情况下我们使用函数指针是这样的:
#define LOG(x) std::cout << x << std::endl;
template<typename T>
void HelloWorld(T x) {
LOG(x)
}
HelloWorld(8);
如果去掉括号,就是函数指针了,前面的类型就是函数指针的类型:
void(*lhx)(int) = HelloWorld<int>;
一般使用typdef或者auto自动来接收:
auto func = HelloWorld<int>;
void(*lhx)(int) = HelloWorld<int>;
使用typedef和之前的方法稍有不同:
typedef void(*HelloWorldFunction)(std::string);
HelloWorldFunction function = HelloWorld<std::string>;
const std::string x = (std::string)"xx";
function(x);
接下来我们使用函数指针来进行传参操作:
#define LOG(x) std::cout << x << std::endl;
template<typename T>
void PrintValue(T x) {
LOG(x)
}
void Each(const std::vector<int>& tmp,void(*printFunc)(int)) {
for (int temp : tmp) {
printFunc(temp);
}
}
#main
std::vector<int> data = { 0,1,2,3 };
Each(data, PrintValue);
稍微提了一下匿名函数:
Each(data, [](int value) {
LOG(value)
})
lambda表达式
不需要通过函数的定义,就可以定义一个函数的办法,设置函数指针指向函数任何地方,我们都可以将它设置为lambda。
在lambda中,要想传递表达式外的参数,需要使用符号:
int x = 5;
auto lambda = [&x](int value) {
LOG(x)
};
=传递所有变量,通过值传递
&传递所有,通过引用传递
或者传入&a,通过引用传递,具体还可以用什么可以查阅文档。
auto lambda = [=](int value) mutable{
x = 5; LOG(x)
};
符号位等号不加mutable会报错。
std::vector<int> data = { 0,1,2,3,5};
auto res = std::find_if(data.begin(), data.end(), [](int value) {return value > 3; });
LOG(*res)
返回第一个大于3的值,如果没有的话会报错!!不知道为什么?
#define LOG(x) std::cout << x << std::endl;
template<typename T>
void PrintValue(T x) {
LOG(x)
}
void Each(const std::vector<int>& tmp, const std::function<void(int)>& func) {
for (int temp : tmp) {
func(temp);
}
}
std::vector<int> data = { 0,1,2,3,5};
Each(data, PrintValue<int>);