在使用std::find()查找数组中的字符串时遇到问题
C++ Having trouble using std::find() to locate a string within an array
对于一个作业项目,我需要从数组中找到一个字符串。在过去的一个小时里,我一直在努力使这个函数工作,但我只是让自己更困惑了。我很确定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,因为操作符==不能将指针与某物进行比较。
相关文章:
- setlocale的C++土耳其字符串问题
- C++字符串问题-如何访问字符串元素
- 提升,从字符串问题中获得时间
- 字符串问题中的系统( "command" ) 字符串
- 从文件和字符串问题中读取
- 将C++函数转换为 C#(字符串问题)
- 有关字符串C++问题
- Visual Studio和Xcode之间的Chaiscript字符串问题
- 回文字符串问题:为什么我必须放+1而不是-1才能让这个代码工作
- Dll导入Marshal C++字符串问题
- 崩溃:字符串问题
- 正在寻找另一种解决二进制字符串问题的尝试
- C++ Win32 是字符串问题
- 迭代器字符串问题
- Python 3:Python/C API字符串问题
- 带有空格的C++字符串问题
- 有些字符串问题
- C++11 std::regex_replace()创建带有特定字符串问题的regexp
- Turbo C++的字符串问题
- 棘手的子字符串问题