简体   繁体   English

排序向量<const char *>

[英]Sorting a vector<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;
}

Here I tried to put my path in a vector beacuse i need ordinated list, but the cout's output is this: 在这里,我尝试将路径放入向量中,因为我需要纵坐标列表,但是cout的输出是这样的:

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. 提前致谢。

As the comments say, don't use char* . 就像评论所说,不要使用char* Second, you should use a debugger. 其次,您应该使用调试器。

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()如何对对象进行排序:

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

But the best course is definitely to use string or directly path as the type of the vector elements. 但是最好的方法肯定是使用string或直接使用path作为矢量元素的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM