如何使用向量将多个字符串传递给函数

时间:2019-01-30 01:56:13

标签: c++ string function vector

我有一个读取文件以查找特定单词的功能。我目前正在搜索的系统是一个特定的单词,并且不区分大小写。我不能简单地使用.find(“ word” &&“ Word”)

据我所知,最简单的方法是在向量​​中同时包含单词的两个版本,以便函数可以同时查找这两个词,但是我不知道如何将向量传递给函数

任何帮助将不胜感激。谢谢

2 个答案:

答案 0 :(得分:0)

在c ++中,您可以将向量作为参考或绝对值传递给函数。要作为参考,您可以遵循此方法。

int fun(vector<string>&arr) {
int value = 0;
//your operation
return value;
}

int main() {
vector<string> arr;
//Your logic
fun(arr);
}

答案 1 :(得分:0)

您可以为向量中的每个可能单词调用find。但是我建议尽可能使用小写字母

#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
int main()
{
    std::string str = "HeLlo WorLd";
    std::vector<std::string> vec{ "HELLO","HeLlo","hEllO","WORLD","WorLd" };

    std::for_each(vec.begin(), vec.end(), [&](const std::string& comp) 
    {
        auto found = str.find(comp);
        if (found != std::string::npos)
            std::cout << "Found World " << comp << " in str at " << std::distance(str.begin(), str.begin() + found) << std::endl;
    });

    return 0;
}