gpt4 book ai didi

c++ - 解引用迭代器 (c++)

转载 作者:行者123 更新时间:2023-11-28 00:28:22 29 4
gpt4 key购买 nike

我在取消引用返回非指针值的操作结果时遇到问题。

在这张 map 中我有指向矩阵的指针

map<string, GeneralMatrix*> matrixes;

这就是矩阵运算的样子

GeneralMatrix & add(const GeneralMatrix & m2) {
//Check for compatible matrixes
if (height != m2.height || width != m2.width) {
cout << "Matrix sizes must match!" << endl;
return *this;
}
//Create new empty matrix
GeneralMatrix &m3 = createNew(width, m2.height);
//Set every number to sum of this and given matrix
for (int i = 0; i < height; i++) {
for (int j = 0; j < m2.width; j++) {
double val = m2.get(i, j);
if (val != 0) {
val += get(i, j);
m3.set(i, j, val);
}
}
}
return m3;
}

如您所见,add 方法返回我想插入到我的 map 中的非指针矩阵。

这是我尝试过的:

map<string, GeneralMatrix *>::iterator itop1 , itop2;
//now seting iterators to their position

//there is the problem
matrixes.insert(pair<string, GeneralMatrix *>(result, (*itop1->second->add(*itop2->second))));

问题是我无法找到如何插入对的第二个参数。由于类型不同,它总是以错误结束。

尝试 n1:

itop1->second->add(itop2->second)

添加方法需要指针

尝试 n2:

itop1->second->add(*itop2->second)

结果是非指针,需要是指针

尝试 n3:

(*itop1->second->add(*itop2->second))

main.cpp:611:68: 错误:“operator*”不匹配(操作数类型为“GeneralMatrix”)

那么如何解引用结果呢?

最佳答案

理想情况下,您会更改 matrixes输入 map<string, GeneralMatrix> .

或者你可以保留一个 std::list<GeneralMatrix>存储矩阵,你在列表中给出一个指向矩阵的指针。

裸指针被认为是不好的风格。指针应该告诉他们对项目的所有权状态,例如 unique_ptr , shared_ptrweak_ptr .这也将负责内存管理。

如果你的类(class)表现良好并且 map 拥有自己的指针,你可以这样做:

matrixes.insert(std::make_pair(std::string("name"), new GeneralMatrix(std::move(m)));

在哪里m是您要移动到 map 中的矩阵。

如果 map 中的指针不拥有指针,您可以使用 &m 插入 map 的地址。 ,但这需要您将矩阵存储在某个持久性位置,例如 list如上所示。

编辑:迭代器的具体问题可以这样解决:

matrixes.insert(pair<string, GeneralMatrix *>(result, &(*itop1)));

关于c++ - 解引用迭代器 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23974293/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com