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 向量
基础教程推荐
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04