【问题标题】:How to access elements of vector of pairs using a pointer?如何使用指针访问对向量的元素?
【发布时间】:2019-11-04 22:05:43
【问题描述】:

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

【问题讨论】:

  • 专业提示:不要使用vector &lt; pair &lt;int, int&gt;&gt;*。只需使用vector &lt; pair &lt;int, int&gt;&gt;。拥有指向标准容器的指针通常是没有意义的。
  • 这种使用指针来寻址容器中数据的逻辑是老式的 C 风格。如果你想用 C++ 编写代码,你应该听从@NathanOliver-ReinstateMonica 和其他人的建议,不要这样做。
  • 在某些情况下,需要在堆上动态分配标准容器,为此使用智能指针(不是新的);但是正如其他人所建议的那样,编译时的堆栈分配通常是一个更可取的选择。 C++ 让您决定哪个是最好的。

标签: c++ c++11 vector std-pair


【解决方案1】:

既然你做了一个指针,你需要解引用它:

(*x)[0].first

x-&gt;operator[](0).first

x-&gt;at(0).first(进行边界检查)

但不要创建指向向量的指针。只需使用std::vector&lt;std::pair&lt;int, int&gt;&gt; x;,您就可以直接使用x[0].first

【讨论】:

  • 或使用x-&gt;at(0).first 进行边界检查。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多