展开 std::vector<std::vector<T>> to std::vector<T>
Unroll std::vector<std::vector<T>> to std::vector<T>
我需要在代码中的很多地方将std::vector<std::vector<T>>
转换为std::vector<T>
(逐行)。我显然知道如何自己实现它,但是在 boost 或 stl 中是否有任何短代码解决方案?(我只能使用C++98)
UPD:我需要一些非常短的解决方案,比如某个函数的单行调用(可能带有 boost lambda),没有循环,所以C++向量向量的元素推送到向量中的解决方案是不可接受的。
UPD2:请不要用循环发布答案,我知道该怎么做。问题是简短的代码方式,而不是想法。
由于它在很多地方,编写自己的小包装函数来将其放在所有这些地方可能是个好主意。包装器内部的逻辑可以根据性能进行自定义,因为它现在位于单个位置。最简单的可能是
inline template <typename T>
std::vector<T> to_vector(const std::vector<std::vector<T>>& double_vec) {
std::vector<T> output;
for(std::vector<std::vector<T>>::size_type i=0; i < double_vec.size(); ++i) {
output.insert(output.end(), double_vec[i].begin(), double_vec[i].end());
}
return output;
}
如有必要,可以自定义/优化。
没有循环就没有办法做到这一点,事实上,这个任务几乎是使用循环的典型代表。好吧,如果我们迂腐,嵌套循环。
你可以做的是隐藏你通过使用更高级别的结构进行循环的事实,但底层实现将是一组嵌套循环。
template <typename T>
struct flatten_functor
{
flatten_functor(std::vector<T> &out)
: m_out(out)
{}
bool operator()(std::vector<T> const& to_append)
{
m_out.insert(m_out.end(), to_append.begin(), to_append.end());
return true;
}
private:
std::vector<T>& m_out;
};
template <typename T>
std::vector<T> flatten_vector(std::vector<std::vector<T> > const &in)
{
std::vector<T> retval;
flatten_functor<T> flatten_this(retval);
std::for_each(in.begin(), in.end(), flatten_this);
return retval;
}
如您所见,为了不真正隐藏您正在处理循环的事实,付出了很多努力。我不认为它比循环更具可读性,但话又说回来,这些天我大部分时间都在使用 C++11,使用 lambda 清理这段代码更容易。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中用vector填充一个简单的动态数组
- vector.resize()中的分配错误
- 使用std::vector的OpenCL矩阵乘法
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 在某些循环内使用vector.push_back时出现分段错误
- 当vector是tje全局变量时,c++中vector的内存管理
- std::vector的包装器,使数组的结构看起来像结构的数组
- 为什么(-1)%vector::size()总是返回0
- 在C++中将类(带有Vector成员)保存为二进制文件
- 编译器如何区分std::vector的构造函数
- 将 int 数组转换为 std::vector<int*>
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- EASTL矢量<向量<int>>连续的
- 在std::vector上存储带有模板的类实例
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 使用 std::vector<boost::shared_ptr<Base_Class>> 或 boost::p tr_vector 的性能注意事项是什么<Base>
- 将矩阵"shared_ptr<vector<vector>sp"的行"(*sp)[i]"<T>传递给接受"shared_ptr<vector<T>>
- 如何获取std::vector<DMatch>