对向量进行排序<const char *> [英] Sorting a vector&lt;const char *&gt;

查看:22
本文介绍了对向量进行排序<const char *>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for ( fs::directory_iterator dir_itr2( out_folder ); dir_itr2 != end_iter; ++dir_itr2 )
{
    cout << "Path del file da inserire nel vettore:" << dir_itr2->path().string().c_str() << endl;
    final_path.push_back(dir_itr2->path().string().c_str());


}

sort( final_path.begin(), final_path.end() );
cout << "Vettore di path da aprire in ordine" << endl;
for(vector<const char *>::iterator fp_itr2=final_path.begin(); fp_itr2!=final_path.end(); ++fp_itr2)
{       
    cout << "Path: " << *fp_itr2 << endl;
}

这里我试图将我的路径放在一个向量中,因为我需要纵列列表,但是 cout 的输出是这样的:

Here I tried to put my path in a vector beacuse i need ordinated list, but the cout's output is this:

Path del file da inserire nel vettore:/srv/FD/super_tracker/tracks/180426163618363.txt
Path del file da inserire nel vettore:/srv/FD/super_tracker/tracks/180426163654027.txt
Path del file da inserire nel vettore:/srv/FD/super_tracker/tracks/180530150135770.txt
Path del file da inserire nel vettore:/srv/FD/super_tracker/tracks/180426163414599.txt
Path del file da inserire nel vettore:/srv/FD/super_tracker/tracks/180530150235481.txt
Path del file da inserire nel vettore:/srv/FD/super_tracker/tracks/180530150132796.txt
Path: 
Path: 
Path: 
Path: 
Path: 
Path:

提前致谢.

推荐答案

正如评论所说,不要使用 char*.其次,您应该使用调试器.

As the comments say, don't use char*. Second, you should use a debugger.

您的 sort() 失败的原因是您正在根据指针指向的内存位置对指针进行排序,而不是使用指向的字符.

The reason your sort() fails is that you are sorting the pointers, according to the location in memory they point to, instead of using the characters pointed to.

您可以使用谓词来告诉 sort() 如何对您的对象进行排序:

You could use a predicate to tell sort() how to sort your objects:

sort(begin(final_path), end(final_path), 
    [](const char* a, const char *b) { return strcmp(a, b) < 0; }
);

但最好的当然是使用string或者直接path作为向量元素的类型.

But the best course is definitely to use string or directly path as the type of the vector elements.

这篇关于对向量进行排序<const char *>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆