問題描述
我正在使用 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 向量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!