2012-10-29 72 views
0

我已经定义了一个结构坐标为如何在矢量中查找元素?

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

重载运算符!=为坐标

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.请帮助获得正确的结果。

+0

它是坐标还是坐标? –

+0

这是否甚至编译? – juanchopanza

+4

你在'vcoord'中输入了什么值,你传递给'getVIndex'什么值? 'Coord'定义了'operator!='是如何定义的?更好的是,你能发布一个小而完整的程序来证明问题吗? –

回答

3

你需要为了能够做到这一个不等于运营商为您 Coord结构:

(*it) != crd 

你没有,等于运算符是不正确的逻辑。最好的和最简单的方法是提供一个相等的比较和使用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); 
+0

这是不是std :: find给了一些编译时错误 – Abhi

+0

@abhi然后你做错了。 – juanchopanza

+0

你是否放弃了,因为你有错误,那你的评论意味着什么? – Caribou

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; 
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); 
} 
+0

谢谢大家指出我的错误,并帮助我,现在找到工作正常,我使用相同的。 – Abhi