我希望以与以下内容相同的方式将容器A
中存在的元素插入容器B
:
auto iter = /* iterator from somewhere in A */
for (auto i=0; i<N && iter++ != A.cend(); i++)
B.push_back(*iter);
但是使用insert而不是for for循环,就像这样;
B.insert(B.end(), iter, iter + N);
答案 0 :(得分:2)
#include <algorithm>
#include <iterator>
auto a_iter = /* iterator from somewhere in A */, a_end = A.end();
std::copy_n(a_iter, std::min(N, std::distance(a_iter, a_end)), std::inserter(B, B.end()));
作为独立算法:
template<typename IterT, typename CollT>
std::insert_iterator<CollT> insert_n(
IterT a_iter, IterT a_end,
typename std::iterator_traits<IterT>::difference_type N,
CollT& B
) {
return std::copy_n(
a_iter,
std::min(N, std::distance(a_iter, a_end)),
std::inserter(B, B.end())
);
}
答案 1 :(得分:0)
我想你可以使用std::copy_if
和一个合适的lambda函数。
例如,如果你的容器是int的向量,就这样
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
int main()
{
std::vector<int> a { 2, 3, 5, 7, 9, 11, 13, 17, 19 };
auto i1 = a.cbegin()+3;
auto i2 = a.cbegin()+7;
std::vector<int> c1;
std::vector<int> c2;
constexpr int N = 5;
std::copy_if(i1, a.cend(), std::back_inserter(c1),
[&](int){ static int pos = -1; return ++pos < N; });
std::copy_if(i2, a.cend(), std::back_inserter(c2),
[&](int){ static int pos = -1; return ++pos < N; });
std::cout << "c1.size() = " << c1.size() << std::endl; // cout 5
std::cout << "c2.size() = " << c2.size() << std::endl; // cout 2
return 0;
}
答案 2 :(得分:0)
对于vector
容器,也许还有更多容器可以像这样工作:
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
vector<int> A = {4,5,6};
vector<int> B = {1,2,3};
unsigned int n = 5;
B.insert(B.end(), A.begin(), A.begin() + (n > B.size() ? B.size(): n));
for (auto it = B.begin(); it != B.end(); it++)
cout << *it << endl;
return 0;
}
,输出为:
1
2
3
4
5
6
您可以在c++11
标签range (3)
签名中看到文档here,