如何使用指针访问对向量的元素?

我正在创建一个整数对向量,以创建28个多米诺骨牌。创建作品后,如何使用指针访问它?我试过x-> first,x [0]-> first,x.first。我似乎误会了一些东西。 这是代码,例如,如何访问刚创建的对中的第一个元素。

vector < pair <int,int>>* x;

x = new vector<pair <int,int>>;

x->push_back(make_pair(1,3));
cairuojin 回答:如何使用指针访问对向量的元素?

自创建指针以来,您需要取消对其的引用:

(*x)[0].first

x->operator[](0).first

x->at(0).first(以进行边界检查)

但是不要指向向量。只需使用std::vector<std::pair<int,int>> x;,您就可以直接x[0].first

,

在这里使用指针的唯一明显原因是,如果您希望能够在运行时动态创建新的多米诺集,例如通过调用函数。为此,必须使用智能指针。例如:

#include <iostream>
#include <memory>
#include <vector>
#include <map>

std::unique_ptr<std::vector<std::pair<int,int>>> dominoFactory() {
    //note syntax with make_unique
    std::unique_ptr<std::vector<std::pair<int,int>>> vec = 
                    std::make_unique<std::vector<std::pair<int,int>>>();
    //make a pair object to serve as a loader for the vector
    std::pair<int,int> temp;
    for (int i = 6; i >= 0; i--) {
        for (int j = 0; j <= i; j++) {
            temp = std::make_pair(i,j);
            vec->push_back(temp);
        }
    }
    return vec;
}

int main() {
    //transfer ownership to a unique_ptr in the calling function:
    std::unique_ptr<std::vector<std::pair<int,int>>> pieces = dominoFactory();
    //dereference the pointer to access the vector internals
    for (auto x : *pieces) {
        //use pair methods to display each value
        std::cout << x.first << " : " << x.second << std::endl;
    }
    return 0;
}

这种方法应该能够防止内存泄漏,并且比使用new更好。

本文链接:https://www.f2er.com/3163429.html

大家都在问