2016-07-24 16 views
1

我想插入存在於容器A到容器B的方式元件即等效於以下:插入N個元素到其它使用迭代

auto iter = /* iterator from somewhere in A */ 
for (auto i=0; i<N && iter++ != A.cend(); i++) 
    B.push_back(*iter); 

但是用插入件來代替,而沒有對循環,像這樣;

B.insert(B.end(), iter, iter + N); 
+2

你嘗試了嗎?它應該工作。你正在使用哪個容器? –

+0

我試過了,它不起作用。 –

+1

「它不起作用」,那取決於容器,而且你沒有提供這些信息。 http://ideone.com/4QQY0r – kfsone

回答

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

你可以看到文檔here,它在c++11選項卡中,range (3)簽名。