如何将dlib中的矩阵转换为std::向量

how to convert a matrix in dlib to a std::vector

本文关键字:转换 std 向量 dlib      更新时间:2023-10-16

我在dlib中定义了一个列向量。如何将其转换为std::vector?

typedef dlib::matrix<double,0,1> column_vector;
column_vector starting_point(4);
starting_point = 1,2,3,4;
std::vector x = ??

感谢

有很多方法。你可以通过for循环复制它。或者使用std::vector构造函数,它接受迭代器:std::vector<double> x(starting_point.begin(), starting_point.end())

这将是您通常对矩阵进行迭代的方式(如果矩阵只有1列,则无关紧要):

// loop over all the rows
for (unsigned int r = 0; r < starting_point.nr(); r += 1) {
    // loop over all the columns
    for (unsigned int c = 0; c < starting_point.nc(); c += 1) {
        // do something here
    }   
}

那么,为什么不迭代列向量,并将每个值引入到新的std::vector中呢?下面是一个完整的例子:

#include <iostream>
#include <dlib/matrix.h>
typedef dlib::matrix<double,0,1> column_vector;
int main() {
    column_vector starting_point(4);
    starting_point = 1,2,3,4;
    std::vector<double> x;
    // loop over the column vector
    for (unsigned int r = 0; r < starting_point.nr(); r += 1) {
        x.push_back(starting_point(r,0));
    }
    for (std::vector<double>::iterator it = x.begin(); it != x.end(); it += 1) {
        std::cout << *it << std::endl;
    }
}