升压::文件系统的std ::排序:在排序麻烦保留信息通过 [英] Boost::filesystem, std::sort: trouble retaining information on sort passes
问题描述
我试图用的std ::排序
在包含从升压读取信息::文件系统:: dictionary_iterator <数据类型/ code>。看来,作为排序算法做了
N
比较, N
是文件目录中的数量,则该信息已被丢失,我结束了段错误。 Valgrind的说我使用未初始化的值,做无效的读取。
I'm trying to use std::sort
on a data type that contains information read from a boost::filesystem::dictionary_iterator
. It appears that as the sorting algorithm has done n
comparisons, n
being the number of files in the directory, that information gets lost and I end up segfaulting. Valgrind says I'm using uninitialized values and doing invalid reads.
我怎样才能改变我的文件
数据类型或算法,使信息保持通行证之间?
How can I change my File
data type or algorithms so that the information is kept between passes?
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
struct File {
fs::path path;
fs::file_status status;
};
bool comp(const File& a, const File& b) {
static size_t count = 0;
std::cout << "Compare function called " << ++count << " times" << std::endl;
std::string a_filename = a.path.filename().native();
std::string b_filename = b.path.filename().native();
return a_filename.compare(b_filename);
}
int main() {
std::vector<File> vec;
// Read directory
fs::directory_iterator it("/etc"), end;
for (; it != end; it++) {
File f = *(new File);
f.path = it->path();
f.status = it->status();
vec.push_back(f);
}
std::sort(vec.begin(), vec.end(), comp);
// Clean up
for (std::vector<File>::iterator it = vec.begin(); it != vec.end(); it++)
delete &(*it);
return 0;
}
(这不是我的实际方案,但表现出相同的行为。)
(This is not my actual program, but exhibits the same behavior.)
推荐答案
调用比较()是错误的,它返回一个int,可以是-1,0或1样的strcmp()。使用一个简单的调用为std ::以下()(a_filename,b_filename)来代替。另外,还要确保你有单元测试是确保比较创建一个严格弱排序,因为需要的std ::排序。
The call to compare() at the end is wrong, it returns an int that can be -1, 0 or 1 like strcmp(). Use a simple call to std::less()(a_filename, b_filename) instead. Also make sure you have unit tests that make sure the comparator creates a strict-weak ordering, as is required for std::sort.
比较内部检查:
inline bool do_compare(const File& a, const File& b)
{
/* ... */
}
bool compare(const File& a, const File& b)
{
bool const res = do_compare(a, b);
if(res)
assert(!do_compare(b, a));
return res;
}
如果NDEBUG被定义(即,断言()停用)编译器应该能够优化这对相同量$ C $的c如前。而现在,我希望你多的乐趣写code是排序文件名9.png,10.png和顺序11.png。 ;)
If NDEBUG is defined (i.e. assert() deactivated) the compiler should be able to optimize this to the same amount of code as before. And now, I wish you much fun writing the code that sorts the filenames 9.png, 10.png and 11.png in that order. ;)
这篇关于升压::文件系统的std ::排序:在排序麻烦保留信息通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!