1

I am creating a vector of int pairs to create 28 domino pieces. After creating a piece, how do I access it using the pointer? I tried x->first, x[0]->first, x.first. I seem to be misunderstanding something. Here is the code, for example, how would I access the first element in the pair I just created.

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

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

x->push_back(make_pair(1, 3));
Defqon
  • 71
  • 5
  • 4
    Pro tip: Don't use a `vector < pair >*`. Just use a `vector < pair >`. having pointers to standard containers is generally pointless. – NathanOliver Nov 04 '19 at 22:07
  • 3
    [The general rule of thumb for using `new` is don't.](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new) – user4581301 Nov 04 '19 at 22:14
  • This logic of using pointers to address data in containers is old-fashioned C style. If you want to code in C++, you should follow the advice of @NathanOliver-ReinstateMonica and others and just don't do it. – RHertel Nov 04 '19 at 22:21
  • There are certain cases where dynamic allocation of a standard container on the heap is necessary, and for that use a smart pointer (not new); but stack allocation at compile time is usually a preferable option, as others suggest. C++ lets you decide which is best. – neutrino_logic Nov 04 '19 at 23:21

2 Answers2

2

Since you made a pointer, you need to dereference it:

(*x)[0].first

or

x->operator[](0).first

or

x->at(0).first (to get bounds checking)

But don't make a pointer to the vector. Simply use std::vector<std::pair<int, int>> x; and you can do x[0].first directly.

Ted Lyngmo
  • 37,764
  • 5
  • 23
  • 50
1

The only obvious reason to use a pointer here is if you want to be able to dynamically create new domino sets at runtime, say by calling a function. For that, using a smart pointer is the way to go. For example:

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

This approach should be robust against memory leaks and is much preferable to using new.

neutrino_logic
  • 1,239
  • 1
  • 4
  • 11