访问指向矢量 c++ 的指针
Accessing a pointer to a vector c++
我在访问以下向量时遇到问题。我是向量的新手,所以这可能是我做错的一个小语法事情。这是代码....
void spellCheck(vector<string> * fileRead)
{
string fileName = "/usr/dict/words";
vector<string> dict; // Stores file
// Open the words text file
cout << "Opening: "<< fileName << " for read" << endl;
ifstream fin;
fin.open(fileName.c_str());
if(!fin.good())
{
cerr << "Error: File could not be opened" << endl;
exit(1);
}
// Reads all words into a vector
while(!fin.eof())
{
string temp;
fin >> temp;
dict.push_back(temp);
}
cout << "Making comparisons…" << endl;
// Go through each word in vector
for(int i=0; i < fileRead->size(); i++)
{
bool found = false;
// Go through and match it with a dictionary word
for(int j= 0; j < dict.size(); j++)
{
if(WordCmp(fileRead[i]->c_str(), dict[j].c_str()) != 0)
{
found = true;
}
}
if(found == false)
{
cout << fileRead[i] << "Not found" << endl;
}
}
}
int WordCmp(char* Word1, char* Word2)
{
if(!strcmp(Word1,Word2))
return 0;
if(Word1[0] != Word2[0])
return 100;
float AveWordLen = ((strlen(Word1) + strlen(Word2)) / 2.0);
return int(NumUniqueChars(Word1,Word2)/ AveWordLen * 100);
}
错误在行中
if(WordCmp(fileRead[i]->c_str(), dict[j].c_str()) != 0)
和
cout << fileRead[i] << "Not found" << endl;
问题似乎是,因为它以指针的形式,IM 用于访问它的当前语法无效。
在指向向量的指针上使用 []
不会调用 std::vector::operator[]
。 若要根据需要调用std::vector::operator[]
,必须具有向量,而不是向量指针。
使用指向向量的指针访问向量的第 n 个元素的语法为:(*fileRead)[n].c_str()
。
但是,您应该只传递对向量的引用:
void spellCheck(vector<string>& fileRead)
那么它只是:
fileRead[n].c_str()
您可以使用一元 * 从向量*获取向量和:
cout << (*fileRead)[i] << "Not found" << endl;
两个访问选项:
-
(*fileRead)[i]
-
fileRead->operator[](i)
改进方法的一种选择
- 按引用传递
你可以像这样通过引用传递文件读取:
void spellCheck(vector<string> & fileRead)
或者当你像这样使用它时添加一个derefere:
if(WordCmp( (*fileRead)[i]->c_str(), dict[j].c_str()) != 0)
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错