gpt4 book ai didi

c++ - 从集合 mySet 中获取信息

转载 作者:行者123 更新时间:2023-12-03 12:50:56 26 4
gpt4 key购买 nike

所以我有

set<MyClass> mySet;

在 MyClass 中,我有一个静态 int 来计算发生的比较次数。我试图从中获取这些信息,但不知道如何获取。

这是我尝试过的:

set<MyClass>::iterator it = mySet.begin();
int count = it->getCompareCount();

int count = mySet.begin()->getCompareCount();

这些都不起作用(是的,我知道它们本质上是完全相同的东西),但我可以从像 std::list 或 std::vector 这样的索引中获取这些信息

示例:

vector<MyClass> myVector;
for (int i = 0; i < 10; i ++)
{
myVector.push_back(MyClass(i,"Some Name", i*2);
}
int count = myVector.at(2).getCompareCount(); //which by default is going to be 0 as no compares have taken place

有人可以帮我吗?当我执行上面所说的操作时,netbeans 说“错误:将‘const MyClass’作为‘int MyClass::getCompareCount()’的‘this’参数传递会丢弃限定符 [-fpermissive]”。

编辑

getCompareCount() 声明:

int MyClass::getCompareCount()
{
return compareCount;
}

最佳答案

std::set 中的元素在插入集合后就不再可变。当您取消引用迭代器(如 it-> 中)时,它会返回您放入集合中的对象的 const 引用。另一方面,您对 getCompareCount() 的定义是一个非常量实例函数,这意味着它只能在该类的非常量实例上调用。将函数定义如下应该可以解决您的问题。

int MyClass::getCompareCount() const
{
return compareCount;
}

顺便说一句,由于compareCount是一个静态int,您可能也希望将函数定义为静态,以便您可以使用类调用它,而不必获取实例来调用它。

static int MyClass::getCompareCount()
{
return compareCount;
}
//To Call it
MyClass::getCompareCount()

关于c++ - 从集合 <MyClass> mySet 中获取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21920694/

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