要比较一个向量中两个对象的字符串,可以使用以下代码示例:
#include
#include
#include
int main() {
std::vector vec = {"apple", "banana", "carrot", "banana"};
std::string str1 = "banana";
std::string str2 = "carrot";
bool isEqual1 = false;
bool isEqual2 = false;
for (const std::string& str : vec) {
if (str == str1) {
isEqual1 = true;
}
if (str == str2) {
isEqual2 = true;
}
}
if (isEqual1) {
std::cout << str1 << " is present in the vector." << std::endl;
} else {
std::cout << str1 << " is not present in the vector." << std::endl;
}
if (isEqual2) {
std::cout << str2 << " is present in the vector." << std::endl;
} else {
std::cout << str2 << " is not present in the vector." << std::endl;
}
return 0;
}
在这个示例中,我们创建了一个std::vector
类型的向量,并初始化了一些字符串元素。然后,我们定义了两个要比较的字符串str1
和str2
。
接下来,我们使用一个循环遍历向量中的每个元素,并比较它们与str1
和str2
是否相等。如果找到了相等的元素,我们将对应的布尔变量isEqual1
和isEqual2
设置为true
。
最后,我们根据isEqual1
和isEqual2
的值输出结果,以指示这两个字符串是否在向量中存在。
请注意,这个代码示例只是一种解决方法。根据实际需求,可能需要使用不同的算法或数据结构来完成比较操作。