C++ 使用迭代器和内存位置检查列表中对象的实例

C++ 使用迭代器和内存位置检查列表中对象的实例,c++,list,this,C++,List,This,我有一门课,像这样: class Particle() { void CalcSomething(Super& arg){ for(unsigned long long index = 0; index < arg.NumberOfParticle(); index ++){ if(this != arg.ParticleMemoryPointer(index)){

我有一门课,像这样:

class Particle()
{

    void CalcSomething(Super& arg){
        for(unsigned long long index = 0; index < arg.NumberOfParticle(); index ++){                              
            if(this != arg.ParticleMemoryPointer(index)){
                // Do the calculations
            }
        }
    }

}

编辑2我们不能使用std::vector。(我们知道您在想它!)

将元素插入
列表后,只要该列表和该元素存在,其指针就永远不会失效。有关更多信息,请参阅此答案:

只需确保插入列表后,不会将原始的未插入元素与插入的元素进行比较-插入将移动或复制元素到列表中

出于您的预期目的,我忍不住觉得有一种更简单的方法,它不需要
粒子
了解
超级
,甚至不需要检查指针:

(伪代码)

您可以将其与C++11中的lambda函数一起使用:

int main() {
    list<Particle> particles;

    pair_wise(particles.begin(), particles.end(),
              [](Particle& lhs, Particle& rhs) {
                  lhs.doSomething(rhs);
              });                  
}
intmain(){
列出粒子;
成对(particles.begin(),particles.end(),
[](粒子和左侧、粒子和右侧){
lhs.剂量测定法(rhs);
});                  
}
或C++11之前版本,例如,使用函数指针:

void calcSomething(Particle& lhs, Particle& rhs) {
    lhs.calcSomething(rhs);
}

int main() {
    list<Particle> particles;

    pair_wise(particles.begin(), particles.end(),
              calcSomething);                  
}
void计算方法(颗粒和左侧、颗粒和右侧){
lhs.计算方法(rhs);
}
int main(){
列出粒子;
成对(particles.begin(),particles.end(),
计算方法);
}

小心-您正在将
无符号long long
作为
无符号int
传递到ParticleMemoryPointer。您确定要将同一个超级对象传递到CalcSomething吗?可能你不小心传递了一份原始super的副本。这是一种非常低效的方法来循环每一对粒子<代码>前进
在<代码>列表迭代器上。发抖。@PeterWood负责人不在乎需要多长时间,只要我们在内存中放入大量对象。std::list的每项开销比std::vector(正好为0)多得多。如果您担心无法分配足够的连续存储,请使用std::deque@PeterWood,工作通常是一个词,人们用它来描述按预期运行的东西,不管它是什么。在这种情况下,预期或期望的行为是
this!=参数ParticleMemoryPointer(索引)
。我希望这能帮你把事情弄清楚。@EdwardBird的咆哮撇开不谈(你们喝了咖啡吗?)指针一旦插入列表中就不会改变,所以比较指针是有效的。@EdwardBird我很抱歉,我忘记了我的原则。@聪旭没有咖啡,我们就要睡觉了。我们绝不容忍那些在添加无意义/垃圾邮件/无用评论之前不动脑筋的人。从问题中的代码(尽管不是解释)可以清楚地看出,
应该如何工作。对任何冒犯表示歉意。感谢您的输入,了解指针的比较应该是有用的。“我明天会调查的。”彼得伍德我很高兴你欣赏我的幽默感。
for particle in particles(start, end - 1):
    for otherParticle in particles(particle + 1, end)
        DoSomething(particle, otherParticle)
template<typename Iter, typename Func>
void pair_wise(Iter it, Iter last, Func func) {
    while(it != last) {
        Iter other = it;
        ++other;
        while(other != last) {
            func(*it, *other);
            ++other;
        }
        ++it;
    }
}
(1, 2), (1, 3), (1, 4)
(2, 3), (2, 4)
(3, 4)
int main() {
    list<Particle> particles;

    pair_wise(particles.begin(), particles.end(),
              [](Particle& lhs, Particle& rhs) {
                  lhs.doSomething(rhs);
              });                  
}
void calcSomething(Particle& lhs, Particle& rhs) {
    lhs.calcSomething(rhs);
}

int main() {
    list<Particle> particles;

    pair_wise(particles.begin(), particles.end(),
              calcSomething);                  
}