,c++,vector,const-char"/>

首页 > 解决方案 > Sorting a vector

问题描述

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;
}

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:

Thanks in advance.

标签: c++vectorconst-char

解决方案


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

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

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

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

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


推荐阅读