std::vector<std::string> EdgePolarityVector = {"BlackToWhite","WhiteToBlack","Both"};C++遍历查找有无"BlackToWhite"元素
时间: 2024-10-15 18:16:50 浏览: 17
在C++中,你可以使用`std::find_if`函数来遍历`std::vector<std::string>`并查找特定元素。这里是如何操作`EdgePolarityVector`来查找"BlackToWhite"元素的示例:
```cpp
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> EdgePolarityVector = {"BlackToWhite", "WhiteToBlack", "Both"};
auto it = std::find_if(EdgePolarityVector.begin(), EdgePolarityVector.end(),
[](const std::string& str) { return str == "BlackToWhite"; });
if (it != EdgePolarityVector.end()) {
std::cout << "Found 'BlackToWhite' at index: " << std::distance(EdgePolarityVector.begin(), it) << std::endl;
} else {
std::cout << "'BlackToWhite' not found in the vector." << std::endl;
}
return 0;
}
```
这段代码会输出:"Found 'BlackToWhite' at index: 0",如果找到了"BlackToWhite",否则会显示它没找到。
阅读全文