我使用以下方法來獲得分配的內存空間,而不用擔心如何回收分配的資源。C++ - 獲取一個向量的內部指針
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> vecInts;
for(int iInd=0; iInd<10; i++)
vecInts.push_back(iInd);
int* pInt = &vecInts[0]; // Is this a good method?
// now can I use pInt to modify the value of the vecInts?
// I will NOT resize the vector and just simply manipulate the values inside
return 0;
}
但是,我不確定這樣的方法是否是好的方法。
謝謝
我們可以稱之爲Hack嗎?由於std :: vector沒有提供一個名爲const T * Get的函數? - 謝謝 – q0987
不,這不是黑客。一個向量應該用在C程序使用數組的地方。 –
在我看來不合理。這是衆所周知的安全,有時是有用的。例如,http://en.wikipedia.org/wiki/Vector_(C%2B%2B)舉例說明了如何使用這樣一個指針來調用'memcpy'和'printf'。如果你更習慣使用迭代器,那麼你總是可以使用一個,即使可能只是獲得地址ala'&(* v.begin())'(類似地只有在'v.size()> 0時纔有效' )。 –