【问题标题】:How to use a vector to pass multiple strings into a function如何使用向量将多个字符串传递给函数
【发布时间】:2019-01-30 01:56:12
【问题描述】:

我有一个函数可以读取文件以查找某个单词。然而,我目前搜索特定单词的系统不区分大小写。我不能简单地使用 .find("word" && "Word")

据我所知,最简单的方法是使用包含两个单词版本的向量,以便函数查找两者,但是我不知道如何将向量传递给函数.

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

【问题讨论】:

  • 为什么不总是将事物转换为小写/大写?或者您不打算处理“word”和“WORD”?然后您只需将字符串转换为小写,并找到单词的小写变体
  • 我建议在对字符串使用 find 之前也将其转换为小写或大写,然后您可以找到单个实例。 WORD WORD Word Word Word...等会很快变得复杂。特别是如果您的“单词”实际上比这更长。

标签: c++ string function vector


【解决方案1】:

您可以为向量中的每个可能的单词调用 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;
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多