【问题标题】:How to add elements of an array to a set如何将数组的元素添加到集合中
【发布时间】:2012-01-24 04:27:03
【问题描述】:

我已经定义了“Outcome”和“Bin”类。 我正在尝试将 Outcome 类型的数组传递给 Bin 构造函数,以便将该数组的每个元素添加到作为 Bin 类的成员属性的一组“Outcome”中。

//Bin.h
class Bin {
private:
    std::set<Outcome> outcomeset;
public:
    Bin();
    Bin(Outcome Outcs[], int numberofelements);
    Bin(std::set<Outcome> Outcs);
    void add(Outcome Outc);
    std::string read();

};

//In Bin.cpp

Bin::Bin(Outcome outcs[], int numberofelements) {
    int i;
    for (i=0;i<(numberofelements-1);i++) {
        outcomeset.insert(outcs[i]); //When this LIne is commented out, no compile errors!
    }
}

这会在 VS2010 中导致链接回库文件的一大堆错误。我一直无法在网上或我的“The Big C++”教科书中找到任何东西。这是对这种功能的完全错误的实现吗?还是我错过了一些相当基本的东西?

出于好奇,我将此作为免费教科书http://www.itmaybeahack.com/homepage/books/oodesign.html中的“轮盘赌”问题的一部分@

感谢您的帮助!

编辑:我已将(相当冗长的)错误文本添加到 pastebin,此处:http://pastebin.com/cqe0KF3K

EDIT2:我已经为结果类实现了 == != 和

//Outcome.cpp
bool Outcome::operator==(Outcome compoutc) {
    if (mEqual(compoutc) == true) {
    return true;
}
else {
    return false;
}
}

bool Outcome::operator!=(Outcome compoutc) {
if (mEqual(compoutc) == false) {
    return true;
}
else {
    return false;
}
}

bool Outcome::operator<(Outcome compoutc) {
if (odds < compoutc.odds) {
    return true;
}
else {
    return false;
}
}

EDIT3:使用取消引用的参数和 const 标签实现了比较运算符,现在它可以编译了!

【问题讨论】:

  • 您的课程Outcome 不提供比较运算符。
  • i&lt;(numberofelements-1) 看起来很可疑,就像一个错误的错误。如果列表中有 3 个元素,i 将是 [0, 1],你会错过索引 2。
  • 我现在已经为 Outcome 类实现了 == != 运算符,上面的 Bin 构造函数仍然无法编译。 :( 感谢您的回复。@Thanatos,漂亮的眼睛,我删除了它,但它对编译错误没有影响。我将发布我在原始帖子中遇到的错误的简介。感谢您的回复!
  • @SamCoulter:这就是 Kerrek SB 的观点:std::set 要求您实现比较(&lt;,即小于)运算符。
  • @Thanatos 啊,我明白了。 operator

标签: c++ arrays oop set


【解决方案1】:

您需要为要插入集合中的类定义一个operator&lt;。

还请注意,您最好使用一对“迭代器”(在本例中为指针)并实际初始化集合,而不是显式循环:

#include <set>
#include <string>

class Outcome { 
    int val;
public:
    bool operator<(Outcome const &other) const { 
        return val < other.val;
    }
    Outcome(int v = 0) : val(v) {}
};

class Bin {
private:
    std::set<Outcome> outcomeset;
public:
    Bin();

    // Actually initialize the set:
    Bin(Outcome Outcs[], int n) : outcomeset(Outcs, Outcs+n) {}
    Bin(std::set<Outcome> Outcs);
    void add(Outcome Outc);
    std::string read();

};

int main() { 
    // Create an array of Outcomes
    Outcome outcomes[] = {Outcome(0), Outcome(1) };

    // use them to initialize the bin:
    Bin b((outcomes),2);

    return 0;
}

【讨论】:

  • 谢谢!我将阅读使用 const 关键字和取消引用参数作为运算符重载的一部分,老实说,我不知道为什么该版本解决了问题而我的(参见原始帖子编辑)没有!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-05
  • 2020-10-19
  • 2017-02-05
相关资源
最近更新 更多