问题描述
我在其他地方找不到答案,所以我想我只需要问这个:我试图得到一个向量的别名(其中存储int指针),如下:
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;
}
}
}
}
问题是似乎存在电流[a] [b]的指数的反转。我想要能够使用当前作为一个普通的向量,但现在的索引是相反的:
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;
,所以 * current [i] [j] = current1 [j] [i]
。我的语法有错误吗?
so that *current[i][j] = current1[j][i]
for some reason. Is there a mistake in my syntax?
推荐答案
我相信你的问题是 []
的优先级高于一元的 *
。所以你得到 *(current [j] [k])
而不是(* current)[j] [k]
,这是你想要的。
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);
然后只需删除您的额外负载 *
。
vector <int*>& current = (ENGINES[i].SITE);
and then just remove your extra loading *
operators on access to current
.
这篇关于别名向量正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!