将字符串向量与字符串进行比较

Comparing vector of strings to a string

本文关键字:字符串 比较 向量      更新时间:2023-10-16

我还没有对此进行编码,因为我不确定哪种方法是解决这个问题的最佳方法。

对于启动器,现在程序要做的只是将与程序同一目录中的所有文件的名称放入一个字符串中,然后打印出该数组。

我想做的是通过文件扩展名进行对这些。将有一个特定的扩展名列表供用户选择,之后所有具有该扩展名的文件都将返回给用户。

我只是不确定该怎么做。想到的第一件事是通过向量迭代并将每个字符串与所需扩展程序进行比较,如果有匹配,则将该字符串推入另一个针对该文件扩展名的向量。我只有5个扩展名,所以我不必为每个扩展程序制作大量的新向量。

替代品我认为永远不要填充原始向量,然后首先请用户请求,然后通过文件迭代并将所有文件匹配到特定的向量是有意义的。完成后,如果他们选择了另一个选项,则将简单地清除并用新文件名重新填充。

关于如何实际进行比较的任何技巧,我对C 语法不太好,使用其他类型的容器也是明智的吗?

非常感谢你们愿意付出我的方式的所有建议,非常感谢!

#include <iostream>
#include <filesystem>
#include <vector>
using namespace std;
using namespace std::tr2::sys;

void scan( path f, unsigned i = 0 )
{
string indent(i,'t');
cout << indent << "Folder = " << system_complete(f) << endl;
directory_iterator d( f );
directory_iterator e;
vector<string>::iterator it1;
std::vector<string> fileNames;

for( ; d != e; ++d )
{
    fileNames.push_back(d->path());
    //print out conents without use of an array
    /*cout << indent << 
        d->path() << (is_directory( d->status() ) ? " [dir]":"") <<
        endl;*/
    //if I want to go into subdirectories
    /*if( is_directory( d->status() ) )
        scan( f / d->path(), i + 1 );*/
}
for(it1 = fileNames.begin(); it1 != fileNames.end(); it1++)
{
 cout << *it1 << endl;
}

}

int main()
{
    path folder = "..";
    cout << folder << (is_directory( folder ) ? " [dir]":"") << endl;
    scan( folder );
}

您不是表示'排序',而是表示'filter'。排序完全意味着其他东西。

您的第二个选项似乎最好,为什么要与两个向量一起工作?

至于比较,困难是您要寻找的东西在字符串的末尾,并且大多数搜索功能从字符串的开头开始运行。但是,C 中有一个方便的东西称为反向迭代器,该迭代器从末端从头开始扫描一个字符串,而不是从一开始就向前扫描。您调用rbegin()rend()获取字符串的反向迭代器。这是使用反向迭代器的比较功能。

#include <algorithm>
#include <string>
// return true if file ends with ext, false otherwise
bool ends_with(const std::string& file, const std::string& ext)
{
    return file.size() >= ext.size() && // file must be at least as long as ext
        // check strings are equal starting at the end
        std::equal(ext.rbegin(), ext.rend(), file.rbegin());
}