我有一张包含以下数据的 map :
id prev abundance thing
1573 -1 0 book
1574 1573 39 beds
1575 1574 41 tray
1576 1575 46 cups
我写的代码是这样的:
struct Abund
{
int prev;
int abundance;
string thing;
}
map<int id, Abund*> oldMap;
我现在需要创建一个新 map ,它应该如下所示:
id2 prev2 prevAbun next2 nextAbun thing2
1573 1574 39 book
1574 1573 0 1575 41 beds
1575 1574 39 1576 46 tray
1576 1575 41 cups
因此,为此我创建了一个新映射和新结构:
struct NewAbund
{
vector<int> prev2;
vector<int> prevAbun;
vector<int> next2;
vector<int> nextAbun;
string thing2;
NewAbund() :
prev2(0),
prevAbun(0),
next2(0),
nextAbun(0),
thing2() {}
NewAbund(
vector<int> nodeprev2,
vector<int> prev_cnt2,
vector<int> nodenext2,
vector<int> next_cnt2,
string node_thing2) :
prev2(nodeprev2), prevAbun(prev_cnt2), next2(nodenext2), nextAbun(next_cnt2), thing2(node_thing2) {}
}
NewAbund(const Abund& old)
{
thing2 = old.thing;
prev2.push_back(old.prev);
prevAbun.push_back(old.abundance);
}
map<int id, NewAbund*> newMap;
现在我完全不知道如何将元素从一张 map 填充到另一张 map 。 :(
最佳答案
您想将旧 map (Abund
) 中的元素填充到新 map (NewAbund
) 的元素中。您需要做的第一件事是将 Abund
对象转换为 NewAbund
对象。这是通过添加一个新的构造函数 NewAbund(const Abund& old)
struct NewAbund
{
vector<int> prev2;
vector<int> prevAbun;
vector<int> next2;
vector<int> nextAbun;
string thing2;
NewAbund(const Abund& old) {
//create a NewAbund using the old data
}
};
一旦我们有了将旧数据转换为新数据的方法,我们只需将所有内容从旧 map 移动到新 map ,如下所示。
typedef map<int id, Abund*>::iterator iter;
iter it = oldMap.begin();
iter end = oldMap.end();
for(; it != end; ++it) {
newMap[it->first] = new NewAbund(*(it->second));
}
关于c++ - 如何重新组合 map 并将元素插入新 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12735078/