c++ - 将字符串 vector 与字符串进行比较

标签 c++ string vector compare

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

对于初学者来说,该程序现在所做的只是将与该程序位于同一目录中的所有文件的名称放入一个字符串数组中,然后将该数组打印出来。

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

我只是不确定该怎么做。首先想到的是遍历 vector 并将每个字符串与另一个具有所需扩展名的字符串进行比较,如果匹配则将该字符串插入另一个特定于该文件扩展名的 vector 。我正在寻找的只有 5 个扩展,所以我不必为每个扩展制作一大堆新 vector 。

备选方案我认为从不填充原始 vector 也可能有意义,首先接受用户请求然后遍历文件并将具有匹配扩展名的所有文件推送到特定 vector 中。完成后,如果他们选择另一个选项, vector 将被简单地清除并重新填充新文件名。

关于如何实际进行比较的任何提示,我对 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 );
}

最佳答案

您不是指“排序”,而是指“过滤”。排序意味着完全不同的东西。

你的第二个选项似乎是最好的,为什么要用两个 vector 做额外的工作?

至于比较,难点在于你要找的东西在字符串的末尾,而大多数搜索函数都是从字符串的开头开始操作的。但是在 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());
}

关于c++ - 将字符串 vector 与字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13217326/

相关文章:

c++ - 尝试交换 vector 中的两个元素时断言失败

c++ - STL 容器和大量数据

c++ - condition_variable::notify_one 不会立即解除等待?

c# - 如何在 C# 中将大的多行文本分配给字符串?

c++ - 使用给定的行 vector 和查找以最大形式排列的二进制矩阵的列 vector 和

c++ - 运行时固定大小的 std::vector?

c++ - 如果按类型比较是糟糕的设计,那么在这种情况下我该怎么办? (多态性)

c++ - GLSL Shader程序随机编译失败

java - 对在 Java 中追加字符串感到困惑

javascript - 如何使用 Javascript 执行字符串拆分并访问数组的值?