0

std::vector V contains elements a1, a2 ,a3, a4, a5, a6 and I need to copy elements from a2 to a4 in a new std::vector NV.

How is it possible to copy range of vector into a new vector? i did this uin my code as per recommendations but still i am not able to figure out?The part involved is this one.

                       vector<int>::const_iterator first = v.begin() + i+1;
                       vector <int>::const_iterator last = v.begin() + i+k;
                       vector<int>:: nv(first, last);
nwp
  • 9,623
  • 5
  • 38
  • 68
kolaveri
  • 59
  • 1
  • 2
  • 15

1 Answers1

0

You can construct the NV directly using this:

std::vector<T> NV(std::next(V.begin(),1),std::next(V.begin(),3));

Example:

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
    auto print=[](const auto& container){
        for(const auto& item:container){
            std::cout << item << "\t";     
        }
        std::cout << "\n";
    };
    std::vector<std::string> V{ "a1", "a2" ,"a3", "a4","a5","a6"};
    print(V);
    std::vector<std::string> NV(std::next(std::begin(V),1),std::next(std::begin(V),4));
    print(NV);
}

Live Demo

Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160
  • @Human HELFAWI can u look athe above code where i am trying to copy from the index i+1 to index i+k of avector into new vector nv – kolaveri Mar 21 '16 at 15:06