我正在使用多线程并想要合并结果.例如:
std::vector<int> A;
std::vector<int> B;
std::vector<int> AB;
Run Code Online (Sandbox Code Playgroud)
我希望AB按顺序拥有A的内容和B的内容.做这样的事情最有效的方法是什么?
Kir*_*sky 292
AB.reserve( A.size() + B.size() ); // preallocate memory
AB.insert( AB.end(), A.begin(), A.end() );
AB.insert( AB.end(), B.begin(), B.end() );
Run Code Online (Sandbox Code Playgroud)
Shi*_*rik 54
这正是成员函数std::vector::insert的用途
std::vector<int> AB = A;
AB.insert(AB.end(), B.begin(), B.end());
Run Code Online (Sandbox Code Playgroud)
bra*_*ing 26
取决于您是否真的需要物理连接两个向量,或者您希望给出迭代的连接外观.boost :: join函数
http://www.boost.org/doc/libs/1_43_0/libs/range/doc/html/range/reference/utilities/join.html
会给你这个.
std::vector<int> v0;
v0.push_back(1);
v0.push_back(2);
v0.push_back(3);
std::vector<int> v1;
v1.push_back(4);
v1.push_back(5);
v1.push_back(6);
...
BOOST_FOREACH(const int & i, boost::join(v0, v1)){
cout << i << endl;
}
Run Code Online (Sandbox Code Playgroud)
应该给你
1
2
3
4
5
6
Run Code Online (Sandbox Code Playgroud)
注意boost :: join不会将两个向量复制到一个新容器中,而是生成一对覆盖两个容器跨度的迭代器(范围).将会有一些性能开销,但可能会少于将所有数据首先复制到新容器.
Ron*_*sse 10
在 Bradgonesurfing 的回答的方向上,很多时候人们并不真的需要连接两个向量 (O(n)),而只是像连接它们一样处理它们 (O(1))。如果这是你的情况,它可以在不需要 Boost 库的情况下完成。
诀窍是创建一个向量代理:一个包装类,它操作对两个向量的引用,外部视为一个连续的向量。
用法
std::vector<int> A{ 1, 2, 3, 4, 5};
std::vector<int> B{ 10, 20, 30 };
VecProxy<int> AB(A, B); // ----> O(1). No copies performed.
for (size_t i = 0; i < AB.size(); ++i)
std::cout << AB[i] << " "; // 1 2 3 4 5 10 20 30
Run Code Online (Sandbox Code Playgroud)
执行
template <class T>
class VecProxy {
private:
std::vector<T>& v1, v2;
public:
VecProxy(std::vector<T>& ref1, std::vector<T>& ref2) : v1(ref1), v2(ref2) {}
const T& operator[](const size_t& i) const;
const size_t size() const;
};
template <class T>
const T& VecProxy<T>::operator[](const size_t& i) const{
return (i < v1.size()) ? v1[i] : v2[i - v1.size()];
};
template <class T>
const size_t VecProxy<T>::size() const { return v1.size() + v2.size(); };
Run Code Online (Sandbox Code Playgroud)
主要优势
创建它是 O(1)(恒定时间),并且需要最少的额外内存分配。
一些需要考虑的事情
根据Kiril V. Lyadvinsky的回答,我做了一个新版本.此代码段使用模板和重载.有了它,你可以写vector3 = vector1 + vector2和vector4 += vector3.希望它可以提供帮助.
template <typename T>
std::vector<T> operator+(const std::vector<T> &A, const std::vector<T> &B)
{
std::vector<T> AB;
AB.reserve( A.size() + B.size() ); // preallocate memory
AB.insert( AB.end(), A.begin(), A.end() ); // add A;
AB.insert( AB.end(), B.begin(), B.end() ); // add B;
return AB;
}
template <typename T>
std::vector<T> &operator+=(std::vector<T> &A, const std::vector<T> &B)
{
A.reserve( A.size() + B.size() ); // preallocate memory without erase original data
A.insert( A.end(), B.begin(), B.end() ); // add B;
return A; // here A could be named AB
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
182619 次 |
| 最近记录: |