简体   繁体   中英

Sorting vector using custom function that will accept vector of any type and std::less/std::greater as comparator

I'm trying to sort a vector(in this particular case containing std::make_unique<std::string> but it should be able to work with different types as well). Here is the code that I was provided:

template <typename T>
void print_vector_of_pointers(const std::vector<T>& vec) {
 for (const auto& ptr : vec) {
 std::cout << *ptr << ' ';
 }
 std::cout << '\n';
}
int main() {
 auto vec = std::vector<std::unique_ptr<std::string>>();
 vec.push_back(std::make_unique<std::string>("ghi"));
 vec.push_back(std::make_unique<std::string>("abc"));
 vec.push_back(std::make_unique<std::string>("jkl"));
 vec.push_back(std::make_unique<std::string>("def"));
 print_vector_of_pointers(vec);
 auto sorted = sorted_view(vec, std::less());
 print_vector_of_pointers(sorted);
 print_vector_of_pointers(vec);
}

Output should be:

ghi abc jkl def
//abc def ghi jkl wrong, of course as you've stated it will sort the pointers, not what it actually contains
ghi abc jkl def

Compiler is giving me this error regardless of what I'm trying to do:

cannot deduce template arguments for 'less' from ()

And I'm not sure whether I should only write a template for function sorted_view() and write some template for std::less so it can take vector of any kind or I should also overload the () operator. Right now any trials while writing sorted_view() resulted in the compiler error as I've attached above. Any help would be greatly appreciated.

You are asking the compiler to deduce std::less<std::unique_ptr<std::string>> from nothing. You will need to specify std::less<std::unique_ptr<std::string>> to construct one, or std::less<> to construct a polymorphic one.

Note that std::less<std::unique_ptr<std::string>> will not compare the strings, it will order the pointers based on an implementation-defined total order.

Ordinarily, you wouldn't use std::vector<std::unique_ptr<std::string>> , but std::vector<std::string> instead.

You claim to use C++17 (since you used its tag). Most probably you have not enabled it in your project. Just add a flag that enables it, eg -std=c++17 for Clang or GCC, or /std:c++17 for MSVS.

If you are using CMake, you can just use set(CMAKE_CXX_STANDARD 17) .

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