如何在使用和无发现的情况下使用和不使用的字符串向量搜索元素

how to search an element in a vector of strings using with and without find

本文关键字:元素 字符串 向量搜索 情况下 发现      更新时间:2023-10-16

我正在尝试通过使用向量来找到一种搜索单词的方法,但是下面的程序没有提供必需的元素

int main(int argc, char *argv[])
{
    std::ifstream input_file("test.txt");
    std::string line;
    std::vector<std::string> elements;
    for (int line_no = 1; std::getline(input_file, line); ++line_no)
    {
        elements.push_back(line);
    }
    std::vector<std::string>::iterator it = find(elements.begin(), elements.end(), ".");
    if (it != elements.end())
        std::cout << "element found: " << (*it) << std::endl;
    else
        std::cout << "element not found " << std::endl;
    std::cin.get();
    return 0;
}

我尝试了下面没有找到的情况,但是如果失败,否则就会给出类似上述情况的答案

    std::vector<std::string>::iterator it = elements.begin();
    for (; it != elements.end(); ++it)
    {
        if ((*it) == ".")
        {
            std::cout << "element found: " << (*it);
        }
        else
        {
            std::cout << "element not found" << std::endl;
        }
    }

以下是我的输入文件text.txt

中的
This is Arif.
I work.

我代码的解决方案是什么,为什么在两种方法中,else else block在块中不给出输出?

您遇到的问题是std::getline一次读取整行。您的两个示例都在检查整个字符串并将其与"."进行比较,因此它永远不会匹配。另外,如果您要做的是检查整个行是否包含一个周期(以及在哪里(,则可以使用std::string::find

int main(int argc, char *argv[])
{
    std::ifstream input_file("test.txt");
    std::string line;
    std::vector<std::string> elements;
    for (int line_no = 1; std::getline(input_file, line); ++line_no)
    {
        elements.push_back(line);
    }
    std::vector<std::string>::const_iterator it;
    for (it = elements.begin(); it != elements.end(); ++it)
    {
        std::string temp(*it);
        size_t found = temp.find(".");
        if (found != std::string::npos)
        {
            std::cout << "element found at position " << found << std::endl;
        }
        else
        {
            std::cout << "element not found " << std::endl;
        }
    }
    std::cin.get();
    return 0;
}