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表示未找到
}
この関数は 2 つのパラメータを受け入れます。1 つは文字列のベクトルvec
、もう 1 つは検索する文字列ですstr
。標準ライブラリの関数を使用して、std::find
ターゲット文字列と等しいベクトル範囲内の要素を検索します。一致する要素が見つかった場合は、ベクトル内の要素の位置 (1 から数えて) が返されます。一致する要素が見つからない場合は、見つからないことを示す -1 が返されます。
次の点に注意してください。
- この関数を
<algorithm>
使用するには、ヘッダー ファイルをインクルードする必要がありますstd::find
。 auto
キーワード定義を使用してit
イテレータの型を推測します。std::distance
この関数は、it
イテレータとvec.begin()
(つまり、ベクトル内の要素の位置) との間の距離を計算するために使用されます。1 からカウントするという要件を満たすために、結果は 1 加算する必要があります。
この関数の使用方法を示す例を次に示します。
#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;
}
上記の回答がお役に立てば幸いです。他にご質問がございましたら、お気軽にお問い合わせください。