切换指针/值
我的类上有一个指针数组,需要对其进行排序。 排序工作正常,我只是不确定,我是否只切换类上的引用,或者整个类...
我的代码是这样的:
ITEM *items = new ITEM[set.pathc];
...
bool change = true;
while( change )
{
change = false;
for( i = 0; i < set.pathc-1; i++ )
{
if( compare( items+i, items+i+1, set.order, set.order_asc ) )
{
ITEM temp;
temp = *(items+i);
items[i] = items[i+1];
items[i+1] = temp;
change = true;
}
}
}
那么我的代码切换只是指针(我的意思是对象分配位置的地址)还是整个对象(比如复制所有私有变量,难道不需要“=”运算符吗?)?
我想只切换指针,因为我想它会快得多,我像这样尝试过,
ITEM *temp
temp = item+i;
item[i] = item+i+1;
item[i+1] = temp;
但它不起作用:-/(我什至无法编译代码)
提前感谢您的解释:)
I have an array of pointers on my class which I need to sort.
Sorting is working correctly, Im just not sure, whether Im switching just reference on class, or the whole class...
My code is like:
ITEM *items = new ITEM[set.pathc];
...
bool change = true;
while( change )
{
change = false;
for( i = 0; i < set.pathc-1; i++ )
{
if( compare( items+i, items+i+1, set.order, set.order_asc ) )
{
ITEM temp;
temp = *(items+i);
items[i] = items[i+1];
items[i+1] = temp;
change = true;
}
}
}
So is my code switching just pointers (I mean adresses of where the object is allocated) or the whole objects (like copying all of the private variables, wouldn't it need "=" operator for this?) ?
I want to switch just pointers because I guess it would be much more faster, I tried it like this
ITEM *temp
temp = item+i;
item[i] = item+i+1;
item[i+1] = temp;
but it didnt work :-/ (I couldnt even compile the code)
thanks in advance for explaining :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在混合概念:
temp
是一个指针,items[i]
是一个 ITEM,items+i+1
是一个指针。所以,如果你想使用指针,好的代码必须是:当然,你可以声明,就像现在一样:
但在这种情况下,切换代码不能使用指针,因为你没有在数组中存储指针,只是项目。
如果你的问题没有太多的切换情况,我建议不要使用 ITEM **,因为动态分配开销。
You are mixing concepts:
temp
is a pointer,items[i]
is an ITEM,items+i+1
is a pointer. So, if you want to use pointers, the good code must be:Of course, you can declare, as now:
but in this case, the switching code can't do with pointers because you are not storing pointers in your array, just ITEMS.
If there are no much switching situations in your problem, I suggest not using ITEM ** because dynamic allocation overhead.