2015-04-14 235 views
-4

我需要在代码中的很多位置将std::vector<std::vector<T>>转换为std::vector<T>(逐行)。我明显知道如何自己实现它,但是在boost或stl中是否有任何短代码解决方案? (我只能使用C++ 98)展开std :: vector <std :: vector <T>>转换为std :: vector <T>

UPD:我需要一些非常短的解决方案,比如一些函数的单线调用(可能带有boost lambda),没有循环,因此C++ pushing elements of a vector of vectors into a vector的解决方案是不可接受的。

UPD2:请不要用循环发布答案,我知道该怎么做。问题是以短代码的方式,而不是想法。

+0

[C++将向量向量推入矢量的元素的可能重复](http://stackoverflow.com/questions/18875334/c-pushing-elements-of-a-vector-of-vectors-into- a-vector) – NathanOliver

+0

在调用之后,你仍然需要完整的载体矢量吗? – Bathsheba

+2

我不明白如何在没有循环的情况下做到这一点。 – NathanOliver

回答

3

由于在很多地方,编写自己的小包装函数将它放在所有这些地方可能是个好主意。内部包装的逻辑可以根据性能进行定制,因为它现在处于单一位置。最简单的可能是

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

如果需要,可以定制/优化哪个。

+0

正如我所说,我知道,如何自己做。我需要一些解决方案,在那里将被称为某个函数(例如一些遍历器),没有一个循环。请仔细阅读问题。 – brachistochron

+0

我不同意;这可能是一个很好的答案,也许是因为使用'size_t'而不是'vector :: size_type'并且依赖于返回值优化。 – Bathsheba

+0

@brachistochron那么,当我回答时,没有关于循环的条件:)。无论哪种方式,您都需要访问原始向量的每个元素以复制它,因此无论如何都会出现循环 - 遍历某些boost lambda只会隐藏循环。建议的解决方案基本上是一样的 - 在呼叫站点暴露短的功能,将收敛逻辑封装在一个地方:) –

1

如果没有循环,没有办法做到这一点,事实上,任务几乎是使用循环的海报小孩。那么,如果我们是迂腐的,嵌套循环。

你可以做的是隐藏你使用更高级别的结构进行循环的事实,但是底层实现将会是一组嵌套循环。

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,并且使用lambdas清理这些代码更容易。

相关问题