【发布时间】:2019-05-15 09:58:52
【问题描述】:
假设我有几个整数向量和一个指向整数向量的指针。我将如何将指针的一个元素的值更改为其他整数向量之一中的地址?
背景是我已经构建了一个类,可以让我将桌面引入虚幻引擎,但是在每个滴答声中,它必须将包含结构的向量形式分配给另一个数据类的值每次滴答,我希望只复制几个元素(像素颜色值)的内存地址,这样我就不必浪费时间复制两次(对于桌面图像来说,这是数百万次操作)
#include <iostream>
#include <vector>
using namespace std;
// Print function
void PrintVector(vector<int> v)
{
for( int i = 0; i < v.size(); i++ )
{
cout << v[i] << ", ";
}
cout << endl;
}
int main()
{
vector<int> vector1;
vector<int> vector2;
vector<int> *ptrvector;
//Do some assignment so the vectors have values
for( int i = 0; i<3; i++)
{
vector1.push_back(i);
vector2.push_back(2*i);
}
//Assign the pointer to the address of vector1.
ptrvector = &vector1;
//Print out:
PrintVector(vector1); // (1,2,3)
PrintVector(vector2); // (2,4,6)
PrintVector(*ptrvector); // (1,2,3)
// We should see that lines 1 and 3 are the same
//BROKEN BIT::
//Ideally want something like
ptrvector[0] = &vector2[2];
PrintVector(*ptrvector); // (6,2,3);
//Such that if I were to do this:
vector2[2] = 20;
PrintVector(*ptrvector); // It should change as a side effect: (20,2,3)
}
额外问题:
假设我有这个:
TArray<FColor> ColorData;
TArray<FColor> *ptrColorData
//Where TArray is essentially a vector. FColor is a struct with members (R,G,B,A)
//ColorData is initialised somewhere and we set the ptrColorData to the address
ptrColorData = &ColorData;
//Somewhere down the line we have a long loop whereby we do
ColorData[i].B = somedata[i];
ColorData[i].G = somedata[i+1];
ColorData[i].R = somedata[i+3];
//somedata is updated per tick, asigning ColorData per tick as well slows it down.
// I wish to be able to do something on the lines of this
ptrColorData[i].B = &somedata[i];
ptrColorData[i].G = &somedata[i+1];
ptrColorData[i].R = &somedata[i+3];
// this is only called once to initialize. Because the memory address
//is unchanging and somedata changes by functions on its own it means when
// I tell my unreal engine to update a texture by passing (*ptrColorData)
// to a function it automatically has the new data when that function is
// next called.
【问题讨论】:
-
通过指针寻址
std::vector中的元素并非不可能,但我不建议这样做。请注意,一旦您将元素添加到向量,它可能会重新分配其内部存储。因此,所有指针都会损坏(悬空)。更好的是通过索引来寻址向量中的元素。 -
如果你坚持用指针来寻址向量元素……你可以像往常一样简单地使用地址运算符(
operator&())来获取向量元素的地址。例如。std::vector<int> vec = { 1, 2, 3, 4, 5 }; int *pA = &vec[2]; // pA points to vec[2] now. -
可能是我弄错了你的意图。
ptrvector[0] = &vector2[2];这将使用正确的间接方式:(*ptrvector)[0] = vector2[2];请注意,指向向量的指针不是指针向量。我相信您对此感到困惑... -
@Scheff 谢谢!我不太清楚指针的正确表示法。这正确地更新了指针的地址,但是如果我说分配
vector2[2] = someothernumbervector2[2]的地址会发生变化,这是我试图避免的。可能在这里想到了一些不可能的事情(我不知道它如何分配内存的全部细节)但目的是如果内存地址不变,我可以削减几百万个操作作为我的设置指针向量无需额外复制即可更新地址处的值。 -
"但是如果我说分配
vector2[2] = someothernumbervector2[2]的地址会改变" - 不,它不会改变它的地址
标签: c++ pointers vector struct