#include <iostream> // std::cout
#include <algorithm> // std::copy
#include <vector> // std::vector
template <typename T>
void func(std::vector<T> & in, std::vector<T> & out)
{
std::copy ( in.begin(), in.begin()+7, out.begin() );
}
int main () {
std::vector<int> myints={10,20,30,40,50,60,70};
std::vector<int> myvector;
myvector.reserve(7);
func(myints, myvector);
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
以上代码参考自:http://www.cplusplus.com/reference/algorithm/copy
但copy在单独的函数内不生效是为什么呢?
reserve
是不行的,你需要resize
reserve 只是分配的内存,但是 vector 里还没有元素。所以
begin() == end()
,并且不可写。