【发布时间】:2013-06-02 17:44:59
【问题描述】:
我想对名为ORIGIN 的std::map 的值进行for 循环,如下所示,从较低的值到较高的值:
我需要重载 < 运算符才能做到这一点。
myclass
{
typedef std::vector<tactics*> origin_of_tactics;
typedef map<float, origin_of_tactics, CompareFloat> ::iterator iter_type;
iter_type it;
map<float, origin_of_tactics, CompareFloat> ORIGIN;
for (it = ORIGIN.find(low_value_in_bar); it <= ORIGIN.find(high_value_in_bar); it++)
{
}
} // end of myclass
我看到了一个重载运算符的示例,我尝试更改它,但我不确定如何在我的课堂上使用它。 如果它是正确的方法:
class Complex
{
public:
typedef std::vector<tactics*> origin_of_tactics;
typedef map<float, origin_of_tactics, CompareFloat>::iterator iter_type;
bool Complex::operator <(const iter_type &other);
Complex(iter_type value) : it1(value)
{};
bool operator <(const Complex &other);
private:
iter_type it1;
};
bool Complex::operator <(const iter_type &other)
{
if ((it1->first) < (other->first))
{
return TRUE;
}
else
{
return FALSE;
}
}
怎么做?以及如何为任何类型的 MAP 迭代器
【问题讨论】:
-
1) 您的地图有
float键。 2)你传递一个比较函数给它。所以你的类中不需要任何比较运算符。 -
I want to do a for loop on **values** of a std::map- 也许地图以外的数据类型更适合 -
@djf
std::map是一个排序容器,元素总是使用给定的比较运算符按索引排序。您可以简单地使用迭代器begin()和end()来迭代(排序的)元素。你有什么问题? -
次要:“TRUE”和“FALSE”不是布尔值,请改用“true”和“false”。
-
Major:
iter_type it;在类实例中存储迭代器很可能会让您在这个阶段对语言的理解感到痛苦,我强烈建议您不要这样做。