我编写了一个模板函数,用于展开两级嵌套的vector。然而,第二级向量可以是另一个向量、指向向量的unique_ptr或shared_ptr。
例如:
std::vector<std::unique_ptr<std::vector<int>>> f1;
std::vector<std::shared_ptr<std::vector<int>>> f2;
std::vector<std::vector<int>> f3;
std::vector<std::unique_ptr<std::vector<std::string>>> f4;
std::vector<std::shared_ptr<std::vector<std::string>>> f5;
std::vector<std::vector<std::string>> f6;
我写了这段代码,它在coliru上运行良好。
#include <vector>
#include <string>
#include <algorithm>
#include <memory>
#include <iostream>
#include <sstream>
template<typename T>
const T* to_pointer(const T& e) {
return &e;
}
template<typename T>
const T* to_pointer(const std::unique_ptr<T>& e) {
return e.get();
}
template<typename T>
const T* to_pointer(const std::shared_ptr<T>& e) {
return e.get();
}
template <typename T, typename K,
typename = typename std::enable_if<
std::is_same<K, std::unique_ptr<std::vector<T>>>::value or
std::is_same<K, std::shared_ptr<std::vector<T>>>::value or
std::is_same<K, std::vector<T>>::value
>::type
>
std::vector<T> flatten(std::vector<K>& source) {
std::vector<T> result;
size_t size = 0;
for (const auto& e : source) {
size += to_pointer(e)->size();
}
result.reserve(size);
for (const auto& e : source) {
auto ptr = to_pointer(e);
auto begin = ptr->begin();
auto end = ptr->end();
std::copy(begin, end, std::back_inserter(result));
}
return result;
}
然而,我想检查是否有更好的方法来编写相同的代码。感谢您的时间和精力。