使用std::find根据字符串向量检查字符串时出现的问题

Issue using std::find to check strings against a vector of strings

本文关键字:字符串 问题 检查 向量 find 使用 std      更新时间:2023-10-16

我是一名C++新手,在掌握一些概念方面遇到了困难,特别是在while循环中检查数组时遇到了std::find。

我有一点PHP背景,但对C++/较低级别的语言非常陌生。我的具体问题是在程序快结束时,我有while(check>>单词){}循环。Visual basic在std::find上也给了我一个错误。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[]){
    //Open the dictionary file(it is called words.txt).
    ifstream myFile;
    myFile.open("dictionary.txt");
    //Define a vector of strings called words.
    std::vector<string> dictionary;
    //For each word in the dictionary file
    string word;
    while (myFile >> word){
        //Append the word to the words vector.
        dictionary.push_back(word);
    }
    //Open the file to be checked(the file is specified on the command line)
    ifstream check;
    check.open(argv[2]);
    //For each word in that file
    while (check >> word){
        //check vector dictionary to see if check >> word exists
        if (std::find(dictionary.begin(), dictionary.end(), word)){
            //If the word is not contained in the dictionary vector print the word.
        }
    }
    return 0;
}

如果这个问题得到了回答,我很抱歉,但我已经看了一些线索,我会继续看,直到我得到它,但我仍然有点迷路。我也会继续努力解决我自己的问题!

谢谢你的帮助!

编辑:Visual basic给出了一个intellisense错误;然而,当我把while循环改为这个时,它就消失了

while (check >> word){
    //check vector dictionary to see if check >> word exists
    if (std::find(dictionary.begin(), dictionary.end(), word) == dictionary.end()){
        //If the word is not contained in the dictionary vector print the word.
        cout << word << endl;
    }
}

您的条件应该是:

std::find(dictionary.begin(), dictionary.end(), word) == dictionary.end()

请注意,在您的情况下,您可以使用map,然后使用

dictionary.count(word) == 0

我认为你最大的问题之一是你认为C++是一种较低级别的语言。你在这些事情上走了很长的路,在这个过程中,你自己的生活变得更加困难。

我可能会这样做:

std::ifstream in("dictionary.txt");
// read all the words from the file:
std::vector<std::string> dictionary{std::istream_iterator<std::string>(in),
                                    std::istream_iterator<std::string>() };
// If the words might not already be sorted, sort them:
// std::sort(dictionary.begin(), dictionary.end());
// open the file to check:
std::ifstream check(argv[2]);
// print out the words that aren't in the dictionary:
std::copy_if(std::istream_iterator<std::string>(check), 
             std::istream_iterator<std::string>(),
             std::ostream_iterator<std::string>(std::cout, "n"),
             [&](std::string const &word) { 
                 return !std::binary_search(dictionary.begin(), dictionary.end(), word);
             });

这通常具有显著的速度优势,因为它使用二进制搜索,而不是通过字典进行线性搜索。

这个怎么样

int len = dictionary.size();
bool flag = true;
for(int i = 0; i < len; i++)
{
    if(dictionary[i] == word) {
        flag = false;
        break;
    }
}
if(flag)
    cout<<word<<"n";
else
;