【问题标题】:searching vectors in c++在 C++ 中搜索向量
【发布时间】: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;};。然后你可以使用一个向量,省去很多麻烦。

标签: c++ search vector find


【解决方案1】:

像这样。

auto i = find(words.begin(), words.end(), search);
if (i != words.end())
{
    auto pos = i - words.begin();
    // do something
}
else
{
    // word not found
}

您没有任何地方可以查找这些内容吗?这与std::find 的基本用法差不多,因此您应该能够自己回答这些问题。

我想您的其他问题可以使用std::find_if 来解决,或者只需编写一个实现您需要的搜索条件的循环。

【讨论】:

  • 嗨,约翰,我尝试了您给出的上述代码,但它给了我像 ibb.co/hsTjvRd 这样的错误。请帮忙
  • @AkashDeSilvaTry std::find 而不是 find。我应该注意到您有一个名为Files::find 的方法,它使编译器感到困惑。不要忘记#include &lt;algorithm&gt;
  • @AkashDeSilva 我现在意识到我可能误解了你的问题。当你说“我如何使用 find() 函数”时,你指的是你自己的 find 函数吗?我以为你指的是std::find。无论如何,我的回答确实有效,但如果您不是专门询问std::find,我不会推荐它。我只是建议您编写一个简单的循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
  • 1970-01-01
  • 2014-07-19
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
相关资源
最近更新 更多