int findStringPosition(const std::vector<std::string>& vec, const std::string& str) {
auto it = std::find(vec.begin(), vec.end(), str);
if (it != vec.end()) {
return std::distance(vec.begin(), it) + 1; // 返回字符串在向量中的位置(从1开始计数)
}
return -1; // 如果没找到,返回-1表示未找到
}
This function accepts two parameters: one is a vector of strings vec
and the other is the string to be found str
. It uses the function from the standard library std::find
to find elements in the vector range that are equal to the target string. If a matching element is found, the element's position in the vector (counting from 1) is returned. If no matching element is found, -1 is returned indicating not found.
Note the following points:
- This function needs to include
<algorithm>
the header file to usestd::find
the function. - Use
auto
keyword definitionsit
to deduce iterator types. std::distance
The function is used to calculate the distance betweenit
the iterator andvec.begin()
(that is, the position of the element in the vector). The result needs to be added by 1 to meet the requirement of counting from 1.
Here is an example demonstrating how to use this function:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<std::string> vec = {
"apple", "banana", "orange", "grape"};
int position = findStringPosition(vec, "orange");
if (position != -1) {
std::cout << "字符串在向量中的位置是:" << position << std::endl;
} else {
std::cout << "未找到字符串" << std::endl;
}
return 0;
}
Hope the above answers are helpful to you! If you have any further questions, please feel free to ask.