This code is a C++ function that finds a specific string in a given string vector and returns its position in the vector.

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 vecand the other is the string to be found str. It uses the function from the standard library std::findto 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 use std::findthe function.
  • Use autokeyword definitions itto deduce iterator types.
  • std::distanceThe function is used to calculate the distance between itthe iterator and vec.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.

Guess you like

Origin blog.csdn.net/m0_46376834/article/details/132738553