I have a tree-like structure
class Directory
{
public:
void merge(Directory&& dir);
private:
std::map<Key, Directory> directories;
};
merge shall move each subdirectory in dir into directories. Can this be done without copying all Keys and directories?
I have tried to say
auto i=dir.begin();
while(i!=dir.end())
{
directories.insert(std::move(*i));
++i;
}
On non-copyable type Key, this fails with deleted copy ctor error for Key. Would emplace solve the problem? If so, how can I use a workaround for gcc older than 4.8 which does not support that method?
EDIT: I have found that the key returned by the iterator is const, and I should not change the key because that will make look-up:s fail. But , I will not need the key anymore so now I wonder if it in this case is it safe to typecast to non-const first.
I think you meant to do the following instead:
while(i!=dir.directories.end()) {
directories.insert(std::move(*i));
++i;
}
As it is, you are looping over the entries in your current directories
map, which is probably empty. This will loop over the directories in dir
instead and copy each into your local map.
EDIT: Saw your reply. I got this to compile:
class Directory {
public:
void merge(Directory& dir) {
std::map<Key, Directory>::iterator i=dir.directories.begin();
while(i!=dir.directories.end()) {
directories.insert(std::move(*i));
++i;
}
}
private:
std::map<Key, Directory> directories;
};
Is that what you wanted?
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.