繁体   English   中英

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

[英]How to access elements of vector of pairs using a pointer?

我正在创建一个整数对向量来创建 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));

由于您创建了一个指针,因此您需要取消引用它:

(*x)[0].first

或者

x->operator[](0).first

或者

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

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

在这里使用指针的唯一明显原因是,如果您希望能够在运行时动态创建新的 domino 集,例如通过调用 function。 为此,使用智能指针是 go 的方法。 例如:

#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;
}

这种方法应该对 memory 泄漏具有鲁棒性,并且比使用新方法更可取。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM