我是编程的新手,在我的作业中,任务是交换不同复制地图中的第二个元素,如果我更改复制版本中的某些内容,原始地图也将发生变化,但我不会知道如何编写复制功能。
template <class T, class P>
class map_swapper
{
public:
map_swapper(map <T, P>& Cmap)
{
map<T, P> & copym(Cmap);
}
void swap(const T &t1, const T &t2) // I don't know if this function here is good or not because of the undeclared identifier error I can't get here, it is just a guess.
{
P a;
a = copym[t1];
copym[t1] = copym[t2];
copym[t2] = a;
}
};
int main()
{
std::map<int, std::string> mapS1;
map_swapper<int, std::string> mapS2(mapS1);
mapS1[0] = "zero";
mapS1[1] = "one";
mapS1[2] = "two";
std::map<int, int> mapI1;
map_swapper<int, int> mapI2(mapI1);
mapI1[0] = 0;
mapI1[1] = 1;
mapI1[2] = 2;
mapS2.swap(0, 2);
mapI2.swap(0, 1);
for (typename std::map <int, std::string> ::iterator it = mapS1.begin(); it != mapS1.end(); it++)
{
std::cout << it->first << " ";
std::cout << it->second << std::endl;
}
for (typename std::map <int, int> ::iterator it = mapI1.begin(); it != mapI1.end(); it++)
{
std::cout << it->first << " ";
std::cout << it->second << std::endl;
}
return 0;
}
自从我在构造函数中声明了'copym'后,我得到了Error C2065 'copym': undeclared identifier
,但不知道如何将声明从那里拉出来而仅将构造函数用于赋值。
输出应为:
0 two
1 one
2 zero
0 1
1 0
2 2
答案 0 :(得分:0)
这是我的代码版本。未经测试,至少应该编译。
template <class T, class P>
class map_swapper
{
public:
map_swapper(map <T, P>& Cmap) : copym(Cmap)
{
}
void swap(const T &t1, const T &t2)
{
P a = copym[t1];
copym[t1] = copym[t2];
copym[t2] = a;
}
private:
map<T, P> & copym;
};
仍然认为使用类来做到这一点有点奇怪。