改写了一下排序的程序,写了个简单的demo,作为学习记录。直接上代码吧
//created:2020.04.06 by Andison
#include<iostream>
#include<vector>
#include<algorithm>
#include <opencv2/opencv.hpp>
using namespace std;
//读取路径下的特定格式文件的路径,返回按文件名升序排列的文件路径vector
int getFilePaths(vector<string> &filepaths, cv::String filePath);
int main()
{
vector<string> filePaths;
cv::String folderPath = "C:\\Users\\sun\\Desktop\\paths\\*.txt";
double t1 = cv::getTickCount();
getFilePaths(filePaths, folderPath);
double t2 = cv::getTickCount();
cout << "Time elapsed: " << 1000 * (double)(t2 - t1) / cv::getTickFrequency() <<" ms."<< endl;
getchar();
return 0;
}
// 名称按升序排列,来源博客: https://blog.csdn.net/sss_369/article/details/87740843
int getFilePaths(vector<string> &filepaths, cv::String filePath)
{
filepaths.clear();
cout << "Read files from: " << filePath << endl;
vector<cv::String> fn;
cv::glob(filePath, fn, false);
if (fn.size() == 0)
{
cout << "file " << filePath << " not exits" << endl;
return -1;
}
//prepare pair for sort
vector<pair<int, string>> v1;
pair<int, string> p1;
vector<cv::String >::iterator it_;
for (it_ = fn.begin(); it_ != fn.end(); ++it_)
{
//1.获取不带路径的文件名,1.txt
string::size_type iPos = (*it_).find_last_of('\\') + 1;
string filename = (*it_).substr(iPos, (*it_).length() - iPos);
//2.获取不带后缀的文件名,1
string name = filename.substr(0, filename.rfind("."));
//3.构建键和值的pair
try {
//防止文件夹中出现非整数的文件名导致的错误
p1 = make_pair(stoi(name), (*it_).c_str());
}catch(exception e)
{
cout << "Crushed -> " << e.what() << endl;
//continue; 直接continue一样
it_ = fn.erase(it_);
//https://www.cnblogs.com/shiliuxinya/p/12219149.html
it_--; //erase函数的返回的是指向被删除元素的下一个元素的迭代器,所以执行erase()后要把迭代器减1,指向前面一个
}
v1.emplace_back(p1);
}
//cout << "v1.sie(): " << v1.size()<<endl;
sort(v1.begin(), v1.end(), [](auto a, auto b) {return a.first < b.first; });
vector<pair<int, string> >::iterator it;
for (it = v1.begin(); it != v1.end(); ++it)
{
//cout << it->first << endl;
//cout << it->second << endl;
filepaths.emplace_back(it->second);
}
return 0;
}