简体   繁体   中英

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:

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* . 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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