Pra*_*shi 4 c++ templates 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;
Run Code Online (Sandbox Code Playgroud)
我写了这段代码,可以在 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;
}
Run Code Online (Sandbox Code Playgroud)
但是,想检查是否有更好的方法来编写相同的代码。感谢您的时间和精力。
如果您希望简化代码,可以使用std::accumulatewith 自定义操作,如下所示:
#include <vector>
#include <numeric>
int main() {
std::vector<std::vector<int>> foo {
{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }
};
auto bar = std::accumulate(foo.begin(), foo.end(), decltype(foo)::value_type{},
[](auto& dest, auto& src) {
dest.insert(dest.end(), src.begin(), src.end());
return dest;
});
}
Run Code Online (Sandbox Code Playgroud)
我的示例的缺点是它不会为新元素保留空间,而是在必要时重新分配空间。
我的第一个示例仅适用于具有成员类型value_type且具有成员函数的类型insert。这意味着foo不能是例如std::vector<std::unique_ptr<std::vector<int>>>.
上述问题可以通过在两个函数模板上使用SFINAE来解决,如下所示:
template<typename T, typename = typename T::value_type>
T flatten(const std::vector<T>& v) {
return std::accumulate(v.begin(), v.end(), T{}, [](auto& dest, auto& src) {
dest.insert(dest.end(), src.begin(), src.end());
return dest;
});
}
template<typename T, typename = typename T::element_type::value_type>
typename T::element_type flatten(const std::vector<T>& v) {
using E = typename T::element_type;
return std::accumulate(v.begin(), v.end(), E{}, [](auto& dest, auto& src) {
dest.insert(dest.end(), src->begin(), src->end());
return dest;
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1145 次 |
| 最近记录: |