如何以正确的方式找到向量中的元素-C

how to find an element in vector in the right way - C++

本文关键字:向量 元素 方式找      更新时间:2023-10-16

我正在尝试从向量删除元素。但是我认为,我有一个特定的问题:

我的数据来自阅读文件:

移动ctrl a,f3

复制ctrl v,shift v

搜索F3,F4

  1. 尝试从文件中读取
  2. 输入一个单词,我想听到它(e.x。:移动)
  3. 的问题是,我只需要输入一个(例如示例中的)单词,然后将整个命令字符串( move ctrl a,f3 )。

    我需要的只是一个单词找到字符串。但是在下面的代码中,我无法执行此操作,请帮助,请解决问题。在下面的代码中,我只能找到一个单词,如果在文件中只有一个单词,而不是( move ctrl a,f3 ),但是如果字符串由几个单词组成..找不到。

     std::vector<std::string> HotMap::remove_element(std::vector<std::string> MyVector){
    //remove a element ,reading a vector of cmds, then deletting one chosen of them
    std::string delete_str;
    std::vector<std::string>::iterator iter_vec;
    std::cout << "Enter an element,which you want to delete: " << std::endl;
    std::cin >> delete_str;
    for (auto & c : delete_str) c = tolower(c);                                         //For the standard for the right searching,all letters are in lower registr
    
    //Here, iter_ve is my vector(vec_get_smd) it swiches to algorithm 
    //std::ind that look for a cmd command ,which user is trying to input
    iter_vec = std::find(MyVector.begin(), MyVector.end(), delete_str);
    if(iter_vec!= MyVector.end())                                                       //Check if is there an element that yoy want earse 
    {
        std::cout << "Found a element and earsed it!" << std::endl;
        MyVector.erase(iter_vec);
    }
    else
    {
        std::cout << "The element wasn't found!" << std::endl;
    }
    for (iter_vec = MyVector.begin(); iter_vec != MyVector.end(); ++iter_vec)           //Just for myself, showing results
    {
        std::cout << *iter_vec << std::endl;
    }
    return std::vector<std::string>(MyVector); }
    

    我的结果:

read KEYS from a file TWO,below

move,fsf,fsdf,aaa

copy

search

Enter an element,which you want to delete: move

The element wasn't found!

我想,您需要尝试使用std::search()

std::vector<std::string> delete_word(" move");

auto iterator=std::search (MyVector.begin(),MyVector.end(),delete_word.begin(), delete_word.end());

它试图在MyVector中找到您的 delete_word