2013-03-30 180 views
0

功能現在可以,主題已實現。感謝大家。C++指向結構的指針陣列

我有以下的類裏面結構非常簡單:

struct Data 
{ 
    string name1; 
    string name2; 
    string name3; 
    string name4; 
} 

我初始化:

Data **data; 
data=new Data*[size]; 

問題是所有指針數組的元素從所述位置移動N右邊,這樣我就可以在N中插入一個新的元素了。我已經嘗試了各種各樣的東西,但是一切都以指向同一個對象的元素數組結束......

我有類似的功能,刪除元素並將所有內容都移到左側。它的正常工作:

int Del_element(/*some parameters*/) 
{ 
    found=Bin_search(Name1,Name2); //binary search. Returns index of element. 
    if (found<0) return 0; //element wasn't found 

    delete data[found]; //delete pointer 
    for (int i=found; i<index-1; i++) //shift all pointers to the left 
    { 
     data[i]=data[i+1]; 
    } 
    index--; 
    return 1; 
} 

我實現的功能是以下:

void re_size() 
{ 
int size_old=size; 
size*=2; 
Data **tmp_array; 

tmp_array = new Data*[size]; 

copy(data, data+size_old, tmp_array); 
delete []data; 
data=new Data*[size]; 
data=tmp_array; 
} 



int Add(const string & Name1,const string & Name2,const string & Name3, const string & Name4) 
    { 
     int found=Bin_search(Name1,Name2); //binary search. Return positive number if found, or negative as the position to insert new element; 

    if (found>0) //if element already exists 
    { 
     return 0; 
    } 


if ((index+1)==size) {re_size();} 

data[index]= new Record(Name1,Name2,Name3,Name4); 
if (index>0) 
{ 
    for (int i=index; i>-found; i--) 
    { 
    *data[i]=*data[i-1]; 
    } 

    data[-found]->name1=Name1; 
    data[-found]->name2=Name1; 
    data[-found]->name3=Name1; 
    data[-found]->name4=Name1; 
} 

index++; 
return 1; 
} 

基本上,我在數組的末尾初始化新的元素,然後從數組的末尾,以發現位置複製的元件和將值複製到數據中[-found]。

+0

這功課嗎?此外,你已經給了我們*可用的代碼*,但不是沒有的代碼? – mfontanini

+0

我更新了我的答案。覈實。 – JalalJaberi

+0

爲什麼你不使用'std :: vector'? – mfontanini

回答

0

你沒有顯示非工作代碼,所以我不得不猜測你做錯了什麼。

我敢打賭,你將元素0轉換爲1,1,1轉換爲2,2轉換爲3等。但是當你將1轉換爲2時,它包含原來在0中的內容。然後當你將2轉換爲3時,它包含你剛剛從0中移出的內容,最初爲0。依此類推。

你需要做的,從年底開始轉變:N-1到N,N-2到N-1,N-3到N-2等

你是事情的事實移動指針是完全不相關的,你會遇到與數組數組相同的問題。

+0

謝謝你的回覆。我已經添加了非工作功能,希望它能提供幫助。其實我從頭到尾轉移,但似乎並不奏效。 – John

0

首先,Del_element功能是在這裏刪除一個新的傳入指針的元素。如果它是真的,那麼它不起作用,因爲你只是佔用釋放的元素(data[first])與新的(data[first+1])。

但是,如果您應該確定您的意思是N等於size並且新的傳入指針必須位於大小的位置,則可以。

但是,您必須顯示真實且更完整的代碼。

好的,那樣更好。首先,我認爲在返回類型爲int的函數中返回false並不是那麼好。其次,我覺得這裏有一個很大的問題for (int i=index-1; i>-found; i--)。爲什麼i>-found

+0

那麼,它應該從數組的末尾到我需要插入新元素,轉移數值的地方。因此,新的初始化數據[index + 1] = new Data(「」,「」,「」,「」)將具有數組的最後一個元素的值,依此類推。它也是 - 找到的,因爲找到的值總是負值(當找不到元素時)。 – John

+0

@約翰首先,你必須關心'索引'。 'index + 1 JalalJaberi