【发布时间】:2020-08-31 13:50:04
【问题描述】:
I have 3 string vectors
1) contains words
2) contains definitions
3) contains types
我如何使用find() 函数在words vector 中查找单词并获取该单词所在的number(row) 。因为我需要从其他2 个向量中获取数据的数字。另外我如何查找相似的单词,例如具有“logy”的单词,或者用户指定范围之间的单词“超过 4 个字符”
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
class Files {
private:
vector<string>words;
vector<string>definitions;
vector<string>types;
public:
void read();
//void intro();
void displayall(vector <string>& words, vector <string>& types, vector <string>& definitions);
void find(vector <string>& words, vector <string>& types, vector <string>& definitions);
};
void Files::find(vector <string>& words, vector <string>& types, vector <string>& definitions)
{
string search;
cout << "Enter word : " << endl;
cin >> search;
//here i need a funtion to find the user enter word form the vector
}
void Files::displayall(vector <string> & words, vector <string>& types, vector <string>& definitions)
{
cout << "This function displays the whole dictionary " << endl;
for (int i = 0; i < words.size(); i++)
cout <<'\n'<< words.at(i) << '\n' << types.at(i) << '\n' << definitions.at(i) << endl;
}
void Files::read()
{
string word;
string definition;
string type;
string blank;
int i = 0;
ifstream out("Text.txt");
do
{
(getline(out, word, '\n'));
words.push_back(word);
getline(out, definition, '\n');
definitions.push_back(definition);
getline(out, type, '\n');
types.push_back(type);
getline(out, blank, '\n');
i++;
cout << "number of line " << i << ' ' << word << endl;
} while (!out.eof());
displayall(words,definitions,types);
}
int main()
{
Files d;
d.read();
}
【问题讨论】:
-
std::find查找元素,然后std::distance获取到返回的迭代器(也恰好是向量索引)的“距离”。 -
退后一步,定义一个代表您的条目之一的类型,例如
struct Entry { string word; string definition; string type;};。然后你可以使用一个向量,省去很多麻烦。