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