2015-10-23 26 views
3

我給下面的代碼來說明我的問題,你可以在他們http://cpp.sh/的std ::載體,它的初始化指針一致性

// Example program 
#include <iostream> 
#include <string> 
#include <vector> 

int main() 
{ 
    int *p; 
    p = new int [10]; 
    for(int i=0; i<10; i++) 
     p[i] = i; 

    std::vector<int> vecArray(p,p+10); 
    vecArray[3]=300; 

    for(int i=0; i<10; i++) 
     std::cout<<vecArray[i]<<std::endl; 

    for(int i=0; i<10; i++) 
     std::cout<<p[i]<<std::endl; 

    delete []p; 
} 

從代碼可以看出,指針p用於initialze後矢量vecArray然後當向量的內容被改變也不會affact在指針的內容。我的問題是:爲什麼vctor的內容總是與指針相同?

+0

你想在'P [3]'後'vecArray [3] = 300改變數值;'? – SingerOfTheFall

+0

所有容器類都存儲數據的硬拷貝,否則它們將毫無用處。 – Lundin

+0

@SingerOfTheFall是的。 – feelfree

回答

4

矢量的內容是你的動態分配的數組的內容的副本。

你要明白,你的示例代碼分配10個整數次,一次當你顯式調用new,另一個當你構建你的vector

您可以同時通過,共享相同的存儲,例如,首先構建載體,然後獲取一個指向它的數據:

#include <iostream> 
#include <vector> 

int  main(void) 
{ 
    std::vector<int> vecArray(10); 

    for(int i=0; i<10; i++) 
    vecArray[i] = i; 

    const int* p = vecArray.data(); 

    vecArray[3]=300; 

    for(int i=0; i<10; i++) 
    std::cout<<vecArray[i]<<std::endl; 

    for(int i=0; i<10; i++) 
    std::cout<<p[i]<<std::endl; 
} 
+4

應該注意的是,由於重新分配,對向量(例如插入)執行一些操作之後,由vector :: data()或者迭代器返回的內部數據的指針都不能保證有效。 – Kamajii

+0

請注意,當'vecArray'被修改時,'p'可能指向無效內存。通過添加新的元素。 –

+0

@Drax謝謝,這是一個不錯的解決方案。但在我的情況下,我想要矢量共享指針。在你的例子中,它是共享向量的指針。 – feelfree

2

你可以讓你vector包含指針int

你推在動態分配的數組的向量地址。

#include <iostream> 
#include <string> 
#include <vector> 

int main() 
{ 
    int *p; 
    p = new int [10]; 
    for(int i=0; i<10; i++) 
     p[i] = i; 

    std::vector<int*> vecArray; 
    for(int i=0; i<10; i++) 
     vecArray.push_back(&p[i]); //push_back addresses in the vector 

    p[3]=300; //you can also: *(vecArray[3])=300; 

    for(int i=0; i<10; i++) 
     std::cout<<*vecArray[i]<<std::endl; // Deference your pointer to get the value 

    for(int i=0; i<10; i++) 
     std::cout<<p[i]<<std::endl; 

    delete []p; 
} 
1

這是vector其使用範圍

template <class InputIterator> vector (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type());

構造而這正是描述:

Range constructor: Constructs a container with as many elements as the range [first,last), with each element emplace-constructed from its corresponding element in that range, in the same order.

它說ëmplace-constructed從其對應的元件。所以這意味着它會通過指針創建對象的新副本。

這就是爲什麼The underlying type an std::vector uses must be CopyAssignable

因此隨着夏季的矢量創建設置爲從數組元素的副本。所以如果你改變一個元素中的任何一個元素,它就不會在其他元素中反映出來。