所以我正在做一个赋值,我需要在一个 vector 中搜索一个有 4 个变量的对象。 字符串,字符串,整数,整数。我对编程很陌生。如果我只使用第一个字符串进行搜索,我就可以使用二进制搜索。但不确定如何使其匹配所有四个字段。
vector 按第一个字符串排序,如果第一个字符串匹配则按第二个字符串排序,如果第二个字符串匹配则排序但第一个 int 等。
到目前为止我的代码是
bool Room::searchRoom(string name, string initial, int number1, int number2) {
size_t mid, left = 0;
size_t right = testVector.size();
while (left < right) {
mid = left + (right - left) / 2;
if (name > testVector[mid].getName()) {
left = mid + 1;
} else if (name < testVector[mid].getName()) {
right = mid;
} else {
return true;
}
return false;
}
}
最佳答案
您可以添加 operator<
到你的类(class)(或 cmp
函数)
然后使用经典算法。
class A
{
public:
// Other stuff
bool operator < (const A& rhs) const {
if (field1 != rhs.field1) return field1 < rhs.field1;
if (field2 != rhs.field2) return field2 < rhs.field2;
if (field3 != rhs.field3) return field3 < rhs.field3;
return field4 < rhs.field4;
}
private:
std::string field1;
std::string field2;
int field3;
int field4;
};
关于具有多个 vector 条件的 C++ 二进制搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19115055/