标签 c++ 下的文章

C++ | Lambda表达式


干啥的

C++ lambda表达式是一种匿名函数,它可以在需要函数对象的地方使用,而不需要显式地定义一个函数。

语法

[capture] (params) opt -> ret { body; }
[捕获列表](参数)mutable(可选)异常属性(可选)->返回类型{函数体}

示例

std::function<int(double)> func = [](double x)->int{ return round(x); }
std::cout << func(1.3) << endl;

捕获列表

lambda表达式的捕获列表用于指定在lambda函数体中可以访问的外部变量。捕获列表可以为空,也可以包含一个或多个捕获项,每个捕获项可以是变量、引用或者this指针。

捕获列表有以下几种形式:

  • 值捕获(value capture):通过值捕获,lambda表达式会在创建时拷贝外部变量的值,并在函数体中使用该拷贝。捕获列表使用方括号[]表示,后面跟着要捕获的变量名。例如:[x, y]表示值捕获变量x和y。
  • 引用捕获(reference capture):通过引用捕获,lambda表达式会在创建时绑定到外部变量的引用,并在函数体中使用该引用。捕获列表使用方括号[]表示,后面跟着要捕获的变量名前加上&符号。例如:[&x, &y]表示引用捕获变量x和y。
  • 隐式捕获(implicit capture):通过隐式捕获,lambda表达式会根据使用的外部变量自动推断捕获方式。捕获列表使用方括号[]表示,但不指定具体的变量名。例如:[=]表示值捕获所有外部变量,[&]表示引用捕获所有外部变量。
  • this指针捕获:通过this指针捕获,lambda表达式可以访问当前对象的成员变量。捕获列表使用方括号[]表示,后面跟着this关键字。例如:[this]表示通过值捕获当前对象的指针。

捕获列表中的变量可以在lambda函数体中使用,但不能修改(除非使用mutable关键字)。捕获列表的选择取决于外部变量的生命周期和使用方式,需要根据具体情况进行选择。

代码示例

#include <iostream>

class Example {
public:
    Example(int x) : x(x) {}

    void lambdaExample() {
        int y = 10;
        int z = 20;

        // 值捕获x,引用捕获y,隐式捕获z
        auto lambda = [&y, z, this]() mutable {
            std::cout << "x: " << x << std::endl;
            std::cout << "y: " << y << std::endl;
            std::cout << "z: " << z << std::endl;
            std::cout << "a: " << a << std::endl;

            x++; // 值捕获的变量可以修改,需要使用mutable关键字
            y++;
            // z++; // 隐式捕获的变量不能修改
            a++;
        };

        lambda();

        std::cout << "x after lambda: " << x << std::endl;
        std::cout << "y after lambda: " << y << std::endl;
        std::cout << "z after lambda: " << z << std::endl;
        std::cout << "a after lambda: " << a << std::endl;
    }

private:
    int x;
    int a = 100;
};

int main() {
    Example example(5);
    example.lambdaExample();

    return 0;
}

/**
x: 5
y: 10
z: 20
a: 100
x after lambda: 6
y after lambda: 11
z after lambda: 20
a after lambda: 101
**/

在上述示例中,lambda表达式中的捕获列表包含了部分捕获形式。值捕获了外部变量x,引用捕获了外部变量y,this指针捕获了成员变量a和变量x。lambda函数体中打印了捕获的变量,并对值捕获的变量进行了修改(需要使用mutable关键字)。在lambda函数执行后,可以看到外部变量z的值没有改变,而成员变量x,y,a的值增加了。


C/C++ Linux创建文件夹


描述

系统做linux适配的时候发现不能追迹,最后检查发现不能在对应目录创建相关文件夹导致的。

包含头文件

#include <sys/stat.h>  
#include <sys/types.h>

函数

函数原型:   int mkdir(const char *pathname, mode_t mode);   
函数说明:   mkdir()函数以mode方式创建一个以参数pathname命名的目录,mode定义新创建目录的权限。   
返回值:   若目录创建成功,则返回0;否则返回-1,并将错误记录到全局变量errno中。

mode模式类型:

S_IRWXU 00700权限,代表该文件所有者拥有读,写和执行操作的权限
S_IRUSR(S_IREAD) 00400权限,代表该文件所有者拥有可读的权限
S_IWUSR(S_IWRITE) 00200权限,代表该文件所有者拥有可写的权限
S_IXUSR(S_IEXEC) 00100权限,代表该文件所有者拥有执行的权限
S_IRWXG 00070权限,代表该文件用户组拥有读,写和执行操作的权限
S_IRGRP 00040权限,代表该文件用户组拥有可读的权限
S_IWGRP 00020权限,代表该文件用户组拥有可写的权限
S_IXGRP 00010权限,代表该文件用户组拥有执行的权限
S_IRWXO 00007权限,代表其他用户拥有读,写和执行操作的权限
S_IROTH 00004权限,代表其他用户拥有可读的权限
S_IWOTH 00002权限,代表其他用户拥有可写的权限
S_IXOTH 00001权限,代表其他用户拥有执行的权限

示例结果

屏幕截图 2023-03-29 071402.png


C++: 自定义错误码类,实现归拢错误信息。


需求

求解器老报错,还得找错误在哪,其实大多数都是一些属性没配置才导致报错,在报错的地方throw出来就能知道具体是哪些错误,把错误编码,这样就能把类似宏这种的返回编码,然后根据编码能查到具体错误信息。

用法

// 定义相关错误
static Error E_NOT_FOUND_PTR(100010001,"未发现指针");

// 响应相关错误
throw E_NOT_FOUND_PTR;

// 查询相关错误并输出
try{
    // 生产代码
} catch (Error info) {
    cout << "[ERROR] [" << info << "] [" << Error::GetErrorString(info) << "]" << endl;
}

类代码

#include <string>
#include <map>
#include <cassert>

class Error
{
public:
    Error(int value, const std::string& str)
    {
        m_value = value;
        m_message =    str;
        #ifdef _DEBUG
        ErrorMap::iterator found = GetErrorMap().find(value);
        if (found != GetErrorMap().end())
        assert(found->second == m_message);
        #endif
        GetErrorMap()[m_value] = m_message;
    }

    operator int() { return m_value; }

private:
    int m_value;
    std::string m_message;

    typedef std::map<int, std::string> ErrorMap;
    static ErrorMap& GetErrorMap()
    {
        static ErrorMap errMap;
        return errMap;
    }

public:

    static std::string GetErrorString(int value)
    {
        ErrorMap::iterator found = GetErrorMap().find(value);
        if (found == GetErrorMap().end())
        {
            assert(false);
            return "";
        } else {
            return found->second;
        }
    }
};

HDF5: C++ 类封装(创建、写入操作)


简介

直接用c的代码写呢太麻烦,用官网的c++用例写呢还乱码,逼得我只能自己写个类来处理了,要不写的东西太多,c的太繁琐,所以自己封装个类方便调用。

hdf5 封装c++ 类

#ifndef _OPEN_HDF5_
#define _OPEN_HDF5_

#include <iostream>
#include <string>
#include <vector>
#include <typeinfo>
#include "h5Cpp.h"

using namespace std;

struct H5TITLE{
    string name;
    string type;
};

/******** ATTR ********/
class CRattr
{
private:
    hid_t hand_id;
public:
    CRattr(hid_t id){
        hand_id = id;
    };
    ~CRattr(){};
    template <class T>
    shared_ptr<CRattr> attr(string key, T value, int len=1){
        hid_t attr_type, attr_space;
        hsize_t attr_dims[1] = { len };
        char* value2 = new char(len);
        if(typeid(T) == typeid(string) || typeid(T) == typeid(char*)){
            attr_type = H5Tcopy(H5T_C_S1);
            H5Tset_size(attr_type, H5T_VARIABLE);
        }else if(typeid(T) == typeid(int)){
            attr_type = H5T_NATIVE_INT;
        }else if(typeid(T) == typeid(double)){
            attr_type = H5T_NATIVE_DOUBLE;
        }else{
            return NULL;
        }
        attr_space = H5Screate_simple(1, attr_dims, NULL);
        hid_t attr = H5Acreate(hand_id, key.c_str(), attr_type, attr_space, H5P_DEFAULT, H5P_DEFAULT);
        if(typeid(T) == typeid(string) || typeid(T) == typeid(char*)){
            H5Awrite(attr, attr_type, value2);
        }else{
            H5Awrite(attr, attr_type, value);
        }
        shared_ptr<CRattr> tmp = make_shared<CRattr>(hand_id);
        return tmp;
    }
};

/******** DATA ********/
class CRdata
{
private:
    hid_t hand_id;
    string dataset_name;
public:
    CRdata(hid_t id, string name){
        hand_id = id;
        dataset_name = name;
    };
    ~CRdata(){};
    template <class T>
    shared_ptr<CRattr> insert(int len, T* wdata, vector<H5TITLE> &title){
        herr_t status;
        hsize_t dims[1] = { len };
        hid_t memtype, space, dset, strtype = H5Tcopy(H5T_C_S1);
        status = H5Tset_size(strtype, H5T_VARIABLE);
        status = H5Tset_cset(strtype, H5T_CSET_UTF8);
        memtype = H5Tcreate(H5T_COMPOUND, sizeof(T));
        int sizet = 0;
        for (int i = 0; i < title.size(); i++)
        {
            if (title.at(i).type == "string" || title.at(i).type == "char") {
                H5Tinsert(memtype, title.at(i).name.c_str(), sizet, strtype);
            } else if (title.at(i).type == "double") {
                H5Tinsert(memtype, title.at(i).name.c_str(), sizet, H5T_NATIVE_DOUBLE);
            } else if (title.at(i).type == "int") {
                H5Tinsert(memtype, title.at(i).name.c_str(), sizet, H5T_NATIVE_INT);
            }
            sizet += sizeof(char*);
        }
        space = H5Screate_simple(1, dims, NULL);
        // 创建数据集
        dset = H5Dcreate(hand_id, dataset_name.c_str(), memtype, space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
        // 插入数据
        status = H5Dwrite(dset, memtype, H5S_ALL, H5S_ALL, H5P_DEFAULT, wdata);

        shared_ptr<CRattr> tmp = make_shared<CRattr>(dset);
        return tmp;
    };
    template <class T>
    shared_ptr<CRattr> insertList(int rows, int cols, T* wdata){
        hid_t space, dset;
        hid_t memtype;
        if (typeid(T) == typeid(double)) {
            memtype = H5T_NATIVE_DOUBLE;
        } else if (typeid(T) == typeid(long double)){
            memtype = H5T_NATIVE_LDOUBLE;
        } else {
            memtype = H5T_NATIVE_INT;
        }

        hsize_t dims[] = { rows, cols };
        space = H5Screate_simple(2, dims, NULL);
        // 创建数据集
        dset = H5Dcreate(hand_id, dataset_name.c_str(), memtype, space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
        // 插入数据
        herr_t status = H5Dwrite(dset, memtype, H5S_ALL, H5S_ALL, H5P_DEFAULT, wdata);
        shared_ptr<CRattr> tmp = make_shared<CRattr>(dset);
        return tmp;
    };
};

/******** GROUP ********/
class CRgroup
{
private:
    hid_t hand_id;
public:
    CRgroup(hid_t id){
        hand_id = id;
    };
    ~CRgroup(){};
    shared_ptr<CRgroup> gopen(string group_name){
        hid_t group_id = H5Gcreate(hand_id, group_name.c_str(), H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
        shared_ptr<CRgroup> tmp = make_shared<CRgroup>(group_id);
        return tmp;
    };
    shared_ptr<CRdata> dataset(string dataset_name){
        shared_ptr<CRdata> tmp = make_shared<CRdata>(hand_id, dataset_name);
        return tmp;
    };
    template <class T>
    shared_ptr<CRattr> attr(string key, T* value, int len = 1){
        shared_ptr<CRattr> tmp = make_shared<CRattr>(hand_id);
        tmp->attr<T>(key, value, len);
        return tmp;
    }
};

/******** FILE ********/
class CRfile
{
private:
    hid_t hand_id;
public:
    CRfile(string file_name){
        hand_id = H5Fcreate(file_name.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
    };
    ~CRfile(){};
    shared_ptr<CRgroup> gopen(string group_name){
        shared_ptr<CRgroup> tmp = make_shared<CRgroup>(hand_id);
        return tmp.gopen(group_name);
    };
    shared_ptr<CRdata> dataset(string dataset_name){
        shared_ptr<CRdata> tmp = make_shared<CRdata>(hand_id, dataset_name);
        return tmp;
    };
    hid_t getHand() {
        return hand_id;
    }
};

#endif

封装的使用示例

    struct mtx{
        double x;
        double y;
        string z;
    };
    struct mt{
        double x;
        double y;
        char* z;
    };

    struct mtx mtt1[5];
    for (int i = 0; i < 5; i++)
    {
        mtt1[i].x = i;
        mtt1[i].y = i;
        mtt1[i].z = "test";
    }

    struct mt mtt2[5];
    for (int i = 0; i < 5; i++)
    {
        mtt2[i].x = mtt1[i].x;
        mtt2[i].y = mtt1[i].y;
        mtt2[i].z = (char*)mtt1[i].z.c_str();
    }

    double wdata[4] = {1,2,3,4};
    Rfile test("test.h5");

    struct mt *wdata2 = new struct mt[5];
    vector<H5TITLE> title = {{"X","double"},{"Y","double"},{"Z","char"}};
    for (int i = 0; i < 5; i++)
    {
        wdata2[i].x = mtt1[i].x;
        wdata2[i].y = mtt1[i].y;
        wdata2[i].z = (char*)mtt1[i].z.c_str();
    }
    
    test.gopen("gtest").gopen("gtest2").dataset("dset").insertList<double>(2,2,wdata);
    int value[1] = {1};
    test.dataset("dtest").insert<mt>(5, wdata2, title).attr<int>("Name", value, 1);
    test.gopen("att").attr<int>("test", value, 1).attr<int>("test2", value, 1);

图示

微信图片编辑_20211129145125.jpg


C++: 利用eigen来做Matlab转C++代码


引入Eigen

#include <Eigen/Dense>
using namespace Eigen;

定义变量

矩阵

方式说明
Matrix<double, 2, 3> M;定义M为2行3列(2x3)矩阵
Matrix3d M; 或 Matrix<double, 3, 3> M;定义M为3行3列(3x3)矩阵
MatrixXi M; 或 Matrix<int, Dynamic, Dynamic> M;定义M为动态int矩阵
MatrixXf M;定义M为动态float矩阵
MatrixXd M;定义M为动态double矩阵

向量

方式说明
Vector3d V;定义M为3行向量(默认列)(3x1矩阵)
RowVector3d V;定义V为3列向量(一行)(1x3矩阵)

运算

运算符matlab表达方式Eigen表达方式说明
+C=A+BM3 = M1.array() + M2.array()矩阵相加
-C=A-BM3 = M1.array() - M2.array()矩阵相减
*C=A*BM3 = M1.array() * M2.array()矩阵相乘
/C=A/BM3 = M1.array() / M2.array()矩阵相除

特殊运算

向量左除: A = [2,4,6] B = [1,2,3] A\B = A.ldlt().solve(B)
向量右除:A = [2,4,6] B = [1,2,3] A/B = SUM(A.*B)/SUM(B^2) = 2

// A simple quickref for Eigen. Add anything that's missing.
// Main author: Keir Mierle

include <Eigen/Dense>

Matrix<double, 3, 3> A; // Fixed rows and cols. Same as Matrix3d.
Matrix<double, 3, Dynamic> B; // Fixed rows, dynamic cols.
Matrix<double, Dynamic, Dynamic> C; // Full dynamic. Same as MatrixXd.
Matrix<double, 3, 3, RowMajor> E; // Row major; default is column-major.
Matrix3f P, Q, R; // 3x3 float matrix.
Vector3f x, y, z; // 3x1 float matrix.
RowVector3f a, b, c; // 1x3 float matrix.
VectorXd v; // Dynamic column vector of doubles
double s;

// Basic usage
// Eigen // Matlab // comments
x.size() // length(x) // vector size
C.rows() // size(C,1) // number of rows
C.cols() // size(C,2) // number of columns
x(i) // x(i+1) // Matlab is 1-based
C(i,j) // C(i+1,j+1) //

A.resize(4, 4); // Runtime error if assertions are on.
B.resize(4, 9); // Runtime error if assertions are on.
A.resize(3, 3); // Ok; size didn't change.
B.resize(3, 9); // Ok; only dynamic cols changed.

A << 1, 2, 3, // Initialize A. The elements can also be

 4, 5, 6,     // matrices, which are stacked along cols
 7, 8, 9;     // and then the rows are stacked.

B << A, A, A; // B is three horizontally stacked A's.
A.fill(10); // Fill A with all 10's.

// Eigen // Matlab
MatrixXd::Identity(rows,cols) // eye(rows,cols)
C.setIdentity(rows,cols) // C = eye(rows,cols)
MatrixXd::Zero(rows,cols) // zeros(rows,cols)
C.setZero(rows,cols) // C = zeros(rows,cols)
MatrixXd::Ones(rows,cols) // ones(rows,cols)
C.setOnes(rows,cols) // C = ones(rows,cols)
MatrixXd::Random(rows,cols) // rand(rows,cols)*2-1 // MatrixXd::Random returns uniform random numbers in (-1, 1).
C.setRandom(rows,cols) // C = rand(rows,cols)*2-1
VectorXd::LinSpaced(size,low,high) // linspace(low,high,size)'
v.setLinSpaced(size,low,high) // v = linspace(low,high,size)'
VectorXi::LinSpaced(((hi-low)/step)+1, // low:step:hi

                low,low+step*(size-1))  //

// Matrix slicing and blocks. All expressions listed here are read/write.
// Templated size versions are faster. Note that Matlab is 1-based (a size N
// vector is x(1)...x(N)).
//
/ PLEASE HELP US IMPROVING THIS SECTION /
/ Eigen 3.4 supports a much improved API for sub-matrices, including, /
/ slicing and indexing from arrays: /
/ http://eigen.tuxfamily.org/dox-devel/group__TutorialSlicingIndexing.html /
//
// Eigen // Matlab
x.head(n) // x(1:n)
x.head<n>() // x(1:n)
x.tail(n) // x(end - n + 1: end)
x.tail<n>() // x(end - n + 1: end)
x.segment(i, n) // x(i+1 : i+n)
x.segment<n>(i) // x(i+1 : i+n)
P.block(i, j, rows, cols) // P(i+1 : i+rows, j+1 : j+cols)
P.block<rows, cols>(i, j) // P(i+1 : i+rows, j+1 : j+cols)
P.row(i) // P(i+1, :)
P.col(j) // P(:, j+1)
P.leftCols<cols>() // P(:, 1:cols)
P.leftCols(cols) // P(:, 1:cols)
P.middleCols<cols>(j) // P(:, j+1:j+cols)
P.middleCols(j, cols) // P(:, j+1:j+cols)
P.rightCols<cols>() // P(:, end-cols+1:end)
P.rightCols(cols) // P(:, end-cols+1:end)
P.topRows<rows>() // P(1:rows, :)
P.topRows(rows) // P(1:rows, :)
P.middleRows<rows>(i) // P(i+1:i+rows, :)
P.middleRows(i, rows) // P(i+1:i+rows, :)
P.bottomRows<rows>() // P(end-rows+1:end, :)
P.bottomRows(rows) // P(end-rows+1:end, :)
P.topLeftCorner(rows, cols) // P(1:rows, 1:cols)
P.topRightCorner(rows, cols) // P(1:rows, end-cols+1:end)
P.bottomLeftCorner(rows, cols) // P(end-rows+1:end, 1:cols)
P.bottomRightCorner(rows, cols) // P(end-rows+1:end, end-cols+1:end)
P.topLeftCorner<rows,cols>() // P(1:rows, 1:cols)
P.topRightCorner<rows,cols>() // P(1:rows, end-cols+1:end)
P.bottomLeftCorner<rows,cols>() // P(end-rows+1:end, 1:cols)
P.bottomRightCorner<rows,cols>() // P(end-rows+1:end, end-cols+1:end)

// Of particular note is Eigen's swap function which is highly optimized.
// Eigen // Matlab
R.row(i) = P.col(j); // R(i, :) = P(:, j)
R.col(j1).swap(mat1.col(j2)); // R(:, [j1 j2]) = R(:, [j2, j1])

// Views, transpose, etc;
//
/ PLEASE HELP US IMPROVING THIS SECTION /
/ Eigen 3.4 supports a new API for reshaping: /
/ http://eigen.tuxfamily.org/dox-devel/group__TutorialReshape.html /
//
// Eigen // Matlab
R.adjoint() // R'
R.transpose() // R.' or conj(R') // Read-write
R.diagonal() // diag(R) // Read-write
x.asDiagonal() // diag(x)
R.transpose().colwise().reverse() // rot90(R) // Read-write
R.rowwise().reverse() // fliplr(R)
R.colwise().reverse() // flipud(R)
R.replicate(i,j) // repmat(P,i,j)

// All the same as Matlab, but matlab doesn't have *= style operators.
// Matrix-vector. Matrix-matrix. Matrix-scalar.
y = Mx; R = PQ; R = P*s;
a = bM; R = P - Q; R = sP;
a *= M; R = P + Q; R = P/s;

               R *= Q;          R  = s*P;
               R += Q;          R *= s;
               R -= Q;          R /= s;

// Vectorized operations on each element independently
// Eigen // Matlab
R = P.cwiseProduct(Q); // R = P .* Q
R = P.array() s.array(); // R = P . s
R = P.cwiseQuotient(Q); // R = P ./ Q
R = P.array() / Q.array(); // R = P ./ Q
R = P.array() + s.array(); // R = P + s
R = P.array() - s.array(); // R = P - s
R.array() += s; // R = R + s
R.array() -= s; // R = R - s
R.array() < Q.array(); // R < Q
R.array() <= Q.array(); // R <= Q
R.cwiseInverse(); // 1 ./ P
R.array().inverse(); // 1 ./ P
R.array().sin() // sin(P)
R.array().cos() // cos(P)
R.array().pow(s) // P .^ s
R.array().square() // P .^ 2
R.array().cube() // P .^ 3
R.cwiseSqrt() // sqrt(P)
R.array().sqrt() // sqrt(P)
R.array().exp() // exp(P)
R.array().log() // log(P)
R.cwiseMax(P) // max(R, P)
R.array().max(P.array()) // max(R, P)
R.cwiseMin(P) // min(R, P)
R.array().min(P.array()) // min(R, P)
R.cwiseAbs() // abs(P)
R.array().abs() // abs(P)
R.cwiseAbs2() // abs(P.^2)
R.array().abs2() // abs(P.^2)
(R.array() < s).select(P,Q ); // (R < s ? P : Q)
R = (Q.array()==0).select(P,R) // R(Q==0) = P(Q==0)
R = P.unaryExpr(ptr_fun(func)) // R = arrayfun(func, P) // with: scalar func(const scalar &x);

// Reductions.
int r, c;
// Eigen // Matlab
R.minCoeff() // min(R(:))
R.maxCoeff() // max(R(:))
s = R.minCoeff(&r, &c) // [s, i] = min(R(:)); [r, c] = ind2sub(size(R), i);
s = R.maxCoeff(&r, &c) // [s, i] = max(R(:)); [r, c] = ind2sub(size(R), i);
R.sum() // sum(R(:))
R.colwise().sum() // sum(R)
R.rowwise().sum() // sum(R, 2) or sum(R')'
R.prod() // prod(R(:))
R.colwise().prod() // prod(R)
R.rowwise().prod() // prod(R, 2) or prod(R')'
R.trace() // trace(R)
R.all() // all(R(:))
R.colwise().all() // all(R)
R.rowwise().all() // all(R, 2)
R.any() // any(R(:))
R.colwise().any() // any(R)
R.rowwise().any() // any(R, 2)

// Dot products, norms, etc.
// Eigen // Matlab
x.norm() // norm(x). Note that norm(R) doesn't work in Eigen.
x.squaredNorm() // dot(x, x) Note the equivalence is not true for complex
x.dot(y) // dot(x, y)
x.cross(y) // cross(x, y) Requires #include <Eigen/Geometry>

//// Type conversion
// Eigen // Matlab
A.cast<double>(); // double(A)
A.cast<float>(); // single(A)
A.cast<int>(); // int32(A)
A.real(); // real(A)
A.imag(); // imag(A)
// if the original type equals destination type, no work is done

// Note that for most operations Eigen requires all operands to have the same type:
MatrixXf F = MatrixXf::Zero(3,3);
A += F; // illegal in Eigen. In Matlab A = A+F is allowed
A += F.cast<double>(); // F converted to double and then added (generally, conversion happens on-the-fly)

// Eigen can map existing memory into Eigen matrices.
float array[3];
Vector3f::Map(array).fill(10); // create a temporary Map over array and sets entries to 10
int data[4] = {1, 2, 3, 4};
Matrix2i mat2x2(data); // copies data into mat2x2
Matrix2i::Map(data) = 2mat2x2; // overwrite elements of data with 2mat2x2
MatrixXi::Map(data, 2, 2) += mat2x2; // adds mat2x2 to elements of data (alternative syntax if size is not know at compile time)

// Solve Ax = b. Result stored in x. Matlab: x = A b.
x = A.ldlt().solve(b)); // A sym. p.s.d. #include <Eigen/Cholesky>
x = A.llt() .solve(b)); // A sym. p.d. #include <Eigen/Cholesky>
x = A.lu() .solve(b)); // Stable and fast. #include <Eigen/LU>
x = A.qr() .solve(b)); // No pivoting. #include <Eigen/QR>
x = A.svd() .solve(b)); // Stable, slowest. #include <Eigen/SVD>
// .ldlt() -> .matrixL() and .matrixD()
// .llt() -> .matrixL()
// .lu() -> .matrixL() and .matrixU()
// .qr() -> .matrixQ() and .matrixR()
// .svd() -> .matrixU(), .singularValues(), and .matrixV()

// Eigenvalue problems
// Eigen // Matlab
A.eigenvalues(); // eig(A);
EigenSolver<Matrix3d> eig(A); // [vec val] = eig(A)
eig.eigenvalues(); // diag(val)
eig.eigenvectors(); // vec
// For self-adjoint matrices use SelfAdjointEigenSolver<>