2015-07-10 99 views
0

我正在使用C++中的armadillo矩陣庫,並且我想創建一個使用「auxiliare內存」的vec。這樣做的標準方法是在用Armadillo C++聲明後創建輔助內存的vec

vec qq(6); qq<<1<<2<<3<<4<<5<<6; 
double *qqd = qq.memptr(); 
vec b1(qqd, 6, false); 

所以在這裏,如果我改變在B1的元素,在QQ中的元素髮生變化,這就是我想要的。但是,在我的程序中,我聲明b1矢量全局,所以當我定義它時,我無法調用使b1使用「auxiliare內存」的構造函數。犰狳中有沒有一個功能可以實現我想要的功能?爲什麼我運行下面的代碼時會得到不同的結果?

vec b1= vec(qq.memptr(), 3, false); //changing b1 element changes one of qq's element 

vec b1; 
b1= vec(qq.memptr(), 3, false); //changing b1 element does not chagne qq's 

那麼,如何使矢量使用從其他矢量的內存時,當它是全局聲明?

回答

0

使用全局變量通常是bad idea

但是如果你堅持使用他們,這裏是使用輔助存儲器全球犰狳載體的一種可能的方式:

#include <armadillo> 

using namespace arma; 

vec* x; // global declaration as a pointer; points to garbage by default 

int main(int argc, char** argv) { 

    double data[] = { 1, 2, 3, 4 }; 

    // create vector x and make it use the data array 
    x = new vec(data, 4, false); 

    vec& y = (*x); // use y as an "easier to use" alias of x 

    y.print("y:"); 

    // as x is a pointer pointing to an instance of the vec class, 
    // we need to delete the memory used by the vec class before exiting 
    // (this doesn't touch the data array, as it's external to the vector) 

    delete x; 

    return 0; 
    }