【发布时间】:2013-12-28 08:05:17
【问题描述】:
我有一个问题,涉及确定两个向量是否包含相同的两个元素。元素可以在向量中的任何位置,但它们必须是相邻的。
为更多示例编辑
例如,以下两个向量在比较时会返回 false。
向量 1 = [ 0, 1, 2, 3, 4, 6 ]
向量 2 = [ 1, 4, 2, 0, 5, 3 ]
但以下两个会返回 true:
向量 1 = [ 0, 1, 2, 3, 4, 5 ]
向量 2 = [ 4, 2, 1, 5, 0, 3 ]
因为第一个向量中的 1,2 将对应于第二个向量中的 2,1。
正确:
向量 1 = [ 0, 1, 2, 3, 4, 5 ]
向量 2 = [ 1, 4, 2, 0, 5, 3 ]
{5,0} 是一对,尽管围绕向量循环(我最初说这是错误的,感谢您发现“来自莫斯科的弗拉德”)。
正确:
向量 1 = [ 0, 1, 2, 3, 4, 5 ]
向量 2 = [ 4, 8, 6, 2, 1, 5, 0, 3 ]
{2,1} 仍然是一对,即使它们不在同一位置
实际应用是我有一个多边形(面),N 个点存储在一个向量中。为了确定一组多边形是否完全包围了一个 3D 体积,我测试了每个面以确保每条边都被另一个面共享(其中一条边由两个相邻点定义)。
因此,Face 包含指向 Points 的指针向量...
std::vector<Point*> points_;
为了检查一个 Face 是否被包围,Face 包含一个成员函数...
bool isSurrounded(std::vector<Face*> * neighbours)
{
int count = 0;
for(auto&& i : *neighbours) // for each potential face
if (i != this) // that is not this face
for (int j = 0; j < nPoints(); j++) // and for each point in this face
for (int k = 0; k < i->nPoints(); k++ ) // check if the neighbour has a shared point, and that the next point (backwards or forwards) is also shared
if ( ( this->at(j) == i->at(k) ) // Points are the same, check the next and previous point too to make a pair
&& ( ( this->at((j+1)%nPoints()) == i->at((k+1)%(i->nPoints())) )
|| ( this->at((j+1)%nPoints()) == i->at((k+i->nPoints()-1)%(i->nPoints())) )))
{ count++; }
if (count > nPoints() - 1) // number of egdes = nPoints -1
return true;
else
return false;
}
现在,显然这段代码很糟糕。如果我在 2 周后回到这个问题,我可能不会理解它。那么面对原来的问题,你会如何整齐的检查这两个向量呢?
请注意,如果您尝试破译提供的代码。 at(int) 返回面中的点,nPoints() 返回面中的点数。
非常感谢。
【问题讨论】:
-
啊——另一个使用“2周规则”的人。
-
我应该指定两个向量可以是任意长度。
-
再举几个“不匹配”和“匹配”的例子(不同的长度,不同的位置),包括极端情况(开始/结束——它们是一对吗?)
标签: c++ algorithm c++11 vector stl