简体   繁体   中英

Copy vector to vector

I'm trying to copy one vector to another using `std::copy``

vector<note_name> notes =  AppSettings::getAllNotes();
copy(notes.begin(), notes.end(), song.noteList);

The function getAllNotes() returns a vector<note_name> and noteList is a public member of the same type. When I try to run I'm getting:

在此处输入图像描述

So I think there's some problem with the fact that the vector uses the type note_name , but I don't know how to fix it. Any ideas?

You need an output iterator , too. If noteList already has the required size, say:

copy(notes.begin(), notes.end(), song.noteList.begin());

If it is empty and you want to insert the copied range, #include <iterator> and say:

copy(notes.begin(), notes.end(), std::back_inserter(song.noteList));


However, as @Mike points out, it may be even simpler to say one of the following:

song.noteList = notes;                            // keep both

AppSettings::getAllNotes().swap(song.noteList);   // dispose of the temporary

2 methods I like from here are:

  1. Pass the vector in the constructor:
std::vector<int> v1({ 7, 6, 4, 5 });
std::vector<int> v2(v1);
  1. assign() function:
std::vector<int> v1({ 7, 6, 4, 5 });
std::vector<int> v2;
v2.assign(v1.begin(), v1.end());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM