Aliasing vector correctly

2019-06-24 05:07发布

问题:

I have not been able to find the answer elsewhere, so I guess I just have to ask this one: I am trying to get an alias for a vector (in which int pointers are stored), as below:

    void conversion(Engine * ENGINES) 
    {//The Engine class has a vector of int* as a public data member called SITE
        for (int i = 0; i < 3; i++)
        {
            vector <int*>* current = &(ENGINES[i].SITE);//the problematic line
            int j_max = current -> size();
            cout << j_max << endl;
            for (int j = 0; j < j_max; j++)
            {
                for (int k = 0; k < 3; k++)
                {
                     if (*current[j][k] == 2)
                    *current[j][k] = 1;
                     if (*current[j][k] == -1)
                    *current[j][k] = 0;
                }
            }
        }
    }

The problem is that there seems to be an inversion of the indices for the *current[a][b]. I want to be able to use current as a normal vector, but now the indexing is reversed compared to:

vector <int*> current1 = ENGINES[1].SITE;

so that *current[i][j] = current1[j][i] for some reason. Is there a mistake in my syntax?

回答1:

I believe your problem is that [] has higher precedence than unary *. So you're getting *(current[j][k]) instead of (*current)[j][k], which is what you want.

However you could eliminate that problem by just taking a reference rather than a pointer:

vector <int*>& current = (ENGINES[i].SITE); and then just remove your extra loading * operators on access to current.



回答2:

The problem is that [] has greater precedence than * (dereference), so *current[i][j] is interpreted as *(current[i][j]), which is probably not what you want.

Actually, this idiom of aliasing is commonly expressed as a reference, not a pointer:

vector <int*>& current = ENGINES[i].SITE;

and use simply current[i][j].



回答3:

As I suspected in my comment, use a reference.

vector <int*> &current = ENGINES[i].SITE;