如果我在堆上创建一个向量,是否意味着我可以从任何其他函数访问它?如何?

If I create a vector on the heap, does that mean I could access it from any other function? How?

此语句在堆上创建一个向量:

std::vector<int>* pVector = new std::vector<int>();

所以,如果我在 main() 或某处声明它,我如何才能在另一个函数中访问它?例如:

#include <iostream>
#include <vector>
    
void insert(int value);

int main (){
    int n = 1;
    std::vector<int>* pVector = new std::vector<int>();
    insert(n);
    return 0;
}

void insert (int value){
    pVector->push_back(value); //ERROR "was not declared in this scope"
    std::cout << pVector[0] << "\n"; //ERROR
}

我正在自学,堆、指针和引用比我预期的要复杂得多,因此非常感谢您的帮助。

这与堆使用无关。

pVector只是main()的一个局部变量,所以只有main()可以使用它。从任何其他函数访问 std::vector 对象的唯一方法是明确地将 pointer/reference 传递给它。

您可以使用输入参数传递它,例如:

#include <iostream>
#include <vector>
    
void insert(std::vector<int>& vec, int value);

int main (){
    int n = 1;

    std::vector<int>* pVector = new std::vector<int>();
    insert(*pVector, n);
    ...
    delete pVector;

    /* this works, too:
    std::vector<int> vec;
    insert(vec, n);
    ...
    */

    return 0;
}

void insert (std::vector<int>& vec, int value){
    vec.push_back(value);
    std::cout << vec[0] << "\n";
}

或者,您可以使用全局变量,例如:

#include <iostream>
#include <vector>
    
std::vector<int>* pVectorToInsertInto;
void insert(int value);

int main (){
    int n = 1;

    std::vector<int>* pVector = new std::vector<int>();
    pVectorToInsertInto = pVector;
    insert(n);
    ...
    delete pVector;

    /* this woks, too:
    std::vector<int> vec;
    pVectorToInsertInto = &vec;
    insert(n);
    ...
    */

    return 0;
}

void insert (int value){
    pVectorToInsertInto->push_back(value);
    std::cout << (*pVectorToInsertInto)[0] << "\n";
}

一般来说,尽可能避免使用全局变量。