Initializing a ublas vector from a C array(从 C 数组初始化 ublas 向量)
问题描述
我正在使用 C++ ublas 库编写一个 Matlab 扩展,我希望能够从 Matlab interpeter 传递的 C 数组初始化我的 ublas 向量.如何在不(为了效率)显式复制数据的情况下从 C 数组初始化 ublas 向量.我正在寻找以下代码行的内容:
I am writing a Matlab extension using the C++ ublas library, and I would like to be able to initialize my ublas vectors from the C arrays passed by the Matlab interpeter. How can I initialize the ublas vector from a C array without (for the sake of efficiency) explicitly copying the data. I am looking for something along the following lines of code:
using namespace boost::numeric::ublas;
int pv[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
vector<int> v (pv);
一般来说,是否可以从数组初始化 C++ std::vector ?像这样:
In general, is it possible to initialize a C++ std::vector from an array? Something like this:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int pv[4] = { 4, 4, 4, 4};
vector<int> v (pv, pv+4);
pv[0] = 0;
cout << "v[0]=" << v[0] << " " << "pv[0]=" << pv[0] << endl;
return 0;
}
但是在初始化时不会复制数据.在这种情况下,输出是
but where the initialization would not copy the data. In this case the output is
v[0]=4 pv[0]=0
但我希望输出相同,其中更新 C 数组会更改 C++ 向量指向的数据
but I want the output to be the same, where updating the C array changes the data pointed to by the C++ vector
v[0]=0 pv[0]=0
推荐答案
std::vector 和 ublas::vector 都是容器.容器的全部意义在于管理其包含对象的存储和生命周期.这就是为什么当您初始化它们时,它们必须将值复制到它们拥有的存储中.
Both std::vector and ublas::vector are containers. The whole point of containers is to manage the storage and lifetimes of their contained objects. This is why when you initialize them they must copy values into storage that they own.
C 数组是大小和位置固定的内存区域,因此就其性质而言,您只能通过复制将它们的值放入容器中.
C arrays are areas of memory fixed in size and location so by their nature you can only get their values into a container by copying.
您可以使用 C 数组作为许多算法函数的输入,所以也许您可以这样做以避免初始副本?
You can use C arrays as the input to many algorithm functions so perhaps you can do that to avoid the initial copy?
这篇关于从 C 数组初始化 ublas 向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 C 数组初始化 ublas 向量
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
