首页 > 解决方案 > 在向量中搜索一个字符串,然后在c++中找到该字符串的位置

问题描述

我正在尝试从文本文件中删除一个字符串。为此,我想将文件读入一个向量,然后我想搜索这个字符串的位置,所以我可以使用 vector::erase 来删除它。从向量中删除字符串后,我可以将向量写入一个新文件。

到目前为止,我已经完成了所有这些,但要找到字符串的位置。我使用 < algorithm > 的 std::find 找到了各种解决方案,但这些答案试图检查这个字符串是否存在,而不是它的位置。

下面是如何设置文本文件的示例。有一个字符串,后跟一个整数,然后是不带空格的 .txt。每个字符串都在换行符上。

file123.txt
Bob56.txt'
Foo8854.txt

在这种情况下,向量将是“file123.txt”、“bob56.txt”、“Foo8854.txt”。

这是我已经制作的代码:

std::vector<std::string> FileInVector;
std::string str;
int StringPosition;

std::fstream FileNames;
FileNames.open("FileName Permanent Storage.txt");
while (std::getline(FileNames, str)) {
  if(str.size() > 0) {
      FileInVector.push_back(str); // Reads file, and this puts values into the vector
  }
}

//This is where it would find the position of the string: "bob56.txt" as an example

FileInVector.erase(StringPosition); // Removes the string from the vector
remove("FileName Permanent Storage.txt"); // Deletes old file
std::ofstream outFile("FileName Permanent Storage.txt"); // Creates new file
for (const auto &e : FileInVector) outFile << e << "\n"; // Writes vector without string into the new file

标签: c++filevectorfinderase

解决方案


std::find将迭代器返回到找到的元素并std::vector::erase接受迭代器。std::distance如果需要,可用于计算索引。

小例子:

#include <vector>
#include <string>
#include <algorithm>

#include <iostream>


void print(const auto& vec){
    for(const auto& e:vec){
        std::cout<<e<<' ';
    }
    std::cout<<'\n';
}

int main(){
    std::vector<std::string> vec{"a","b","c","d"};
    auto it = std::find(vec.begin(),vec.end(),"c");
    
    if(it!=vec.end())//If found
    {
        std::cout<<"Index "<<std::distance(vec.begin(),it)<<'\n';
        vec.erase(it,it+1);
        print(vec);
    }
}

输出:

Index 2
a b d 

也就是说,有一个简单的O(1)内存(就加载的行而言)解决方案:读取行并立即只写回那些与字符串不匹配的行。


推荐阅读