在使用std::find()查找数组中的字符串时遇到问题

C++ Having trouble using std::find() to locate a string within an array

本文关键字:字符串 问题 遇到 数组 std find 查找      更新时间:2023-10-16

对于一个作业项目,我需要从数组中找到一个字符串。在过去的一个小时里,我一直在努力使这个函数工作,但我只是让自己更困惑了。我很确定find()返回找到值的地址。我做错了什么?

下面的代码:

类成员方法:

bool ArrayStorage::stdExists(string word)
{
    if (arrayOfWords != NULL)
    {
        size_t findResult = find(&arrayOfWords[0], &arrayOfWords[arrayLength], word);
        std::cout << "word found at: " << findResult << 'n';
        return true;
    }
return false;
}

(string word) from main:

string find = "pixel";

声明数组的成员方法

void ArrayStorage::read(ifstream &fin1)
{
    int index = 0;
    int arrayLength = 0;
    string firstWord;
    if(fin1.is_open())
        {
            fin1 >> firstWord;
            fin1 >> arrayLength;
            setArrayLength(arrayLength);
            arrayOfWords = new string[arrayLength];
            while(!fin1.eof())
            {
                fin1 >> arrayOfWords[index];
                index++;
            }
        }
}

头文件:

class ArrayStorage
{
private:
    string* arrayOfWords;
    int arrayLength;
    int value;
public:
    void read(ifstream &fin1); //reads data from a file
    void write(ofstream &out1); //output data to an output stream(ostream)
    bool exists(string word); //return true or false depending whether or not a given word exists
    bool stdExists(string word); //^^ use either std::count() or std::find() inside here
    //setters
    void setArrayLength(int value);
    //getters
    int getArrayLength();
    ArrayStorage::ArrayStorage() : arrayOfWords(NULL)
    {
    }
    ArrayStorage::~ArrayStorage()
    {
        if (arrayOfWords)
        delete []arrayOfWords;
    }
};

g++甚至不编译这段代码,并给出精确的错误信息:

错误:从'std::basic_string*'到'size_t {aka long unsigned int}'的无效转换[-fpermissive]

所以,你需要把代码改成:
string* findResult = find(&arrayOfWords[0], &arrayOfWords[arrayLength], word);

如果该指针等于&arrayOfWords[arrayLength],则没有找到匹配项

find返回的不是地址,而是与参数类型相同的迭代器。它是指向存储在arrayOfWords中的任何类型的指针。

回应你的评论:如果arrayOfWords包含指向字符串的指针,你需要使用find_if,因为操作符==不能将指针与某物进行比较。