【问题标题】:C++ Having trouble using std::find() to locate a string within an arrayC++ 使用 std::find() 在数组中定位字符串时遇到问题
【发布时间】:2013-05-17 20:08:47
【问题描述】:

对于一个家庭作业项目,我需要从一个数组中找到一个字符串。现在我一直在努力让这个功能在过去的一个小时里工作,我只是让自己更加困惑。我很确定 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;
}

(字符串单词)来自 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;
    }

};

【问题讨论】:

  • arrayOfWords 是如何声明的?
  • &amp;arrayOfWords[arrayLength] 看起来很可疑。 std::begin(arrayOfWords)std::end(arrayOfWords) 这样的东西在这里是明确的。
  • @chris 越过结束指针是你的好 ole,为什么可疑?
  • arrayOfWords 在头文件中被声明为字符串指针数组,并且通过在同一类声明中的单独成员方法中创建动态数组来将值发送给它。在我的其他方法中传递 arrayOfWords 的值没有任何问题,数组工作正常。
  • @chris begin 和 end 只有在 arrayOfWords 真的是一个数组而不是一个指针时才有效。你无法从这段代码中看出区别。

标签: c++ arrays string sorting find


【解决方案1】:

g++ 甚至不编译此代码,并带有精确的错误消息:

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

所以,您需要将代码更改为:

string* findResult = find(&arrayOfWords[0], &arrayOfWords[arrayLength], word);

如果此指针等于 &arrayOfWords[arrayLength],则找不到匹配项。

【讨论】:

  • 绝对的老大哥你杀了它!非常感谢,我现在也明白其中的道理了。
  • 另一件事:可能是 bool stdExists(const string& word) const;会更好的风格(通过 const 引用传递参数可能更有效,const 方法的 const 正确性)
  • 我一定要注意!感谢您的帮助。
【解决方案2】:

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

回复您的评论:如果 arrayOfWords 包含指向字符串的指针,您需要使用 find_if 因为 operator== 无法将指向某物的指针与某物进行比较。

【讨论】:

  • 如果我需要实际使用 find 而不是 find_if,那么我重新调整代码以适应需要会是一个漫长的过程吗?
  • 鉴于您接受的代码,您的评论是错误的。你有一个字符串数组,而不是一个指向字符串的指针数组...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
  • 2019-11-19
  • 1970-01-01
  • 2012-09-21
  • 2013-12-27
  • 2015-01-27
相关资源
最近更新 更多