0

I have a relatively simple algorithm that walks an std::vector looking for two neighbouring tuples. Once the tuples left and right of the X value are found I can interpolate between them. Somehow this works:

  std::vector<LutTuple*>::iterator tuple_it;
  LutTuple* left = NULL;
  LutTuple* right = NULL;
  bool found = 0;

  // Only iterate as long as the points are not found
  for(tuple_it = lut.begin(); (tuple_it != lut.end() && !found); tuple_it++) {
    // If the tuple is less than r2 we found the first element
    if((*tuple_it)->r < r) {
        left = *tuple_it;
    }
    if ((*tuple_it)->r > r) {
        right = *tuple_it;
    }
    if(left && right) {
        found = 1;
    }
  }

while this:

  std::vector<LutTuple*>::iterator tuple_it;
  LutTuple* left = NULL;
  LutTuple* right = NULL;

  // Only iterate as long as the points are not found
  for(tuple_it = lut.begin(); tuple_it != lut.end() && !left && !right; tuple_it++) {
    // If the tuple is less than r2 we found the first element
    if((*tuple_it)->r < r) {
        left = *tuple_it;
    }
    if ((*tuple_it)->r > r) {
        right = *tuple_it;
    }
  }

does not. Why is that? I'd expect two NULL ptrs like this to evaluate to true together when negated.

4

3 回答 3

5

一旦找到任何一个,第二个循环就会终止。将条件更改为:

tuple_it != lut.end() && !(left && right)

或者

tuple_it != lut.end() && (!left || !right)

继续,直到找到两者。

于 2012-04-10T15:21:40.547 回答
4

有一个逻辑问题。

在您拥有的第一个片段中(基本上)!(left && right)

在第二个片段中,您有:!left && !right.

这些是不等价的。

如果你建立真值表,你会发现它!(left && right)等价于(!left || !right)

于 2012-04-10T15:23:26.160 回答
0

我希望两个像这样的 NULL ptr 在被否定时一起评估为真。

这根本不符合逻辑。不要“否定”指针并期望它们在强制进入布尔表达式时会评估什么。相反,我建议明确地将它们与 NULL 进行比较。

此外,将用于继续循环的复杂布尔表达式移动到单独的行中,否则很难在逻辑上遵循代码。

于 2012-04-10T15:22:13.317 回答