C++ - 获取向量的内部指针

q09*_*987 5 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;
}
Run Code Online (Sandbox Code Playgroud)

但是,我不确定这种方法是否合适.

谢谢

Ton*_*roy 5

是的,考虑到你提到的注意事项(以及其他明显的注意事项,例如没有使用指针进入超出范围的矢量等),这很好.指针将有效并且无效,其方式与进入容器的迭代器完全相同.

  • 不,这不是一个黑客.应该在C程序使用数组的地方使用向量. (2认同)