如何在向量中找到元素?

时间:2012-10-29 12:39:09

标签: c++ vector iterator

我已将Coord结构定义为

struct Coord { 
int x;
int y;
int z; 
};

重载运算符!=对于Coord

bool Coord::operator !=(Coord& crd)const {
if(this->x != crd.x)
{
    if(this->y != crd.y)
    {
        if(this->z != crd.z)
            return true;
        else
            return false;
    }
    else
        return false;
    return true;
}
else
    return false;
}

然后将矢量变量初始化为

vector<Coord> vcoord;

现在我使用以下代码来获取具有特定Coord对象的向量索引

int Index::getVIndex(Coord crd) { 
vector<Coord>::iterator it;
int indx;

it = vcoord.begin();
while(it != vcoord.end() && (*it) != crd)
    ++it;

indx = distance(vcoord.begin(),it);
cerr << (*it).x << " " << (*it).y << " " << indx << endl;
return indx;
}

但indx的值始终为0.请帮助获得正确的结果。

3 个答案:

答案 0 :(得分:3)

您的Coord结构需要一个not-equals运算符才能执行此操作:

(*it) != crd

<击>

not-equals运算符的逻辑不正确。最好和最简单的选择是提供相等比较并使用std::find

struct Coord { 
int x;
int y;
int z; 
};

bool operator == (const Coord& lhs, const Coord& rhs)
{
  return lhs.x==rhs.x && lhs.y==rhs.y && lhs.z==rhs.z;
}

然后,您可以使用!=来实现==,但如果您使用std::find,则默认情况下使用==,则不需要它:

vector<Coord>::iterator it = std::find(vcoord.begin(), vcoord.end(), crd);

答案 1 :(得分:2)

仅当所有坐标不同时,!=运算符才会返回true;如果任何不同,它应该返回true。这意味着如果第一个元素的任何坐标与函数参数匹配,则函数将返回零。

你的版本是一种冗长的写作方式:

return x != crd.x && y != crd.y && z != crd.z;

应该是:

return x != crd.x || y != crd.y || z != crd.z;

通过==

实现逻辑,可能更容易理解逻辑
bool operator==(Coord const & lhs, Coord const & rhs) {
    return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z;
}
bool operator!=(Coord const & lhs, Coord const & rhs) {
    return !(lhs == rhs);
}

另外,根据==的定义,您可以使用std::find而不是滚动自己的循环:

auto found == std::find(vcoord.begin(), vcoord.end(), crd);
if (found == vcoord.end()) {
    // Decide what to do if not found.
    // Returning zero is a bad idea, since there's no way distinguish that 
    // from a successful outcome.
} else {
    return std::distance(vcoord.begin(), found);
}

答案 2 :(得分:1)

您错误地在不等式运算符中实现了逻辑。 它应该是

bool Coord::operator !=(const Coord& crd)const {
  return x != crd.x || y != crd.y || z != crz.z;
}

您的实施在逻辑上等同于

  return x != crd.x && y != crd.y && z != crz.z;