我有一个方法将 std::vector 作为其参数之一。有没有一种方法可以通过将 std::vector 分配给矩阵来初始化矩阵?这是我在下面尝试做的事情。有谁知道我如何实现将 vector (甚至 double 指针)分配给矩阵?提前致谢。迈克
void Foo(std::vector v)
{
matrix<double> m(m, n, v);
// work with matrix...
}
最佳答案
这是如何做到这一点的另一个例子:
#include <algorithm>
#include <vector>
#include <boost/numeric/ublas/storage.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
namespace ublas = boost::numeric::ublas;
template <typename T, typename F=ublas::row_major>
ublas::matrix<T, F> makeMatrix(std::size_t m, std::size_t n, const std::vector<T> & v)
{
if(m*n!=v.size()) {
; // Handle this case
}
ublas::unbounded_array<T> storage(m*n);
std::copy(v.begin(), v.end(), storage.begin());
return ublas::matrix<T>(m, n, storage);
}
int main () {;
std::vector<double> vec {1, 2, 3, 4, 5, 6};
ublas::matrix<double> mm = makeMatrix(3,2,vec);
std::cout << mm << std::endl;
}
关于c++ - 使用 std::vector 或数组初始化 boost 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8109443/