【问题标题】:Performing calculations on elements, and retrieving index the index of an element in a vector对元素执行计算,并检索向量中元素的索引
【发布时间】:2021-12-10 15:27:30
【问题描述】:

在这里,我试图对向量中的元素执行计算和比较,找到平均值、较低值、较高值和差异。我在打印向量中元素的索引时也遇到了问题。

#include <iostream>
#include <string>
#include <vector>

enum class OrderBookType{bid, ask};

class OrderBookEntry{
public:
    double price;
    double amount;
    std::string timestamp;
    std::string product;
    OrderBookType orderType;
    
    double computeAveragePrice(std::vector<OrderBookEntry>& entries);
    
    OrderBookEntry(double _price,
                   double _amount,
                   std::string _timestamp,
                   std::string _product,
                   OrderBookType _orderType):
    price(_price),
    amount(_amount),
    timestamp(_timestamp),
    product(_product),
    orderType(_orderType) {
    }
        
//*    Other kinds of functions I hope to implement for this program. */
//    double computeLowPrice(std::vector<OrderBookEntry>& entries);
//    double computeHighPrice(std::vector<OrderBookEntry>& entries);
//    double computePriceSpread(std::vector<OrderBookEntry>& entries);

};

double OrderBookEntry::computeAveragePrice(std::vector<OrderBookEntry> &entries) {
        return 5.5; // Just trying to test a for an output here
}

int main() {
    // Declaring vector entries
    std::vector<OrderBookEntry> entries;
        
    // Adding entries into entries
    entries.push_back(OrderBookEntry{
        10000,
        0.001,
        "2020/03/17 17:01:24.88492",
        "BTC/USDT",
        OrderBookType::bid
    });
    entries.push_back(OrderBookEntry{
        20000,
        0.002,
        "2020/03/17 17:01:24.88492",
        "BTC/USDT",
        OrderBookType::bid
    });

    // Prints prices of all entries
    for (OrderBookEntry& entry : entries) {
        std::cout << "The price entry " << &entry << " is " << entry.price << std::endl;
    }
    
    std::cout << "The lower price is " << entries.computeAveragePrice() << std::endl;
        
    return 0;
}

我在这里遇到三个问题。

首先,我无法调用 computeAveragePrice() 函数来获取它返回的值——在这种情况下,只有 5.5 的值用于测试。

上图是下面这行代码的错误信息。

std::cout << "The lower price is " << entries.computeAveragePrice() << std::endl;

其次,当我尝试打印向量中元素的索引时,我得到了一个奇怪的值。

以上是我得到的输出。我期待得到元素的相应索引,但得到了这个。这是我用来遍历向量的代码。

for (OrderBookEntry& entry : entries) {
    std::cout << "The price entry " << &entry << " is " << entry.price << std::endl;
}

最后,我可以参考任何文章,这些文章教我如何对向量中的值执行算术运算,例如平均值、比较和查找差异。

提前谢谢你!

【问题讨论】:

  • computeAveragePriceOrderBookEntry 中的成员函数,但entriesstd::vector&lt;OrderBookEntry&gt;,而不是OrderBookEntry
  • 感谢您的回复!所以我要做的是有一行将OrderBookEntry 包含到主函数中?我刚刚尝试将OrderBookEntry orderBookObjects 包含到我的主函数中,并得到一个错误,指出OderBookEntry 的初始化没有匹配的构造函数。我以此为参考,link
  • 在 cmets 中很难解释,所以我做了一个答案。
  • 与其拥有一个知道如何计算向量中 OrderBookEntriy 平均价格的 OrderBookEntry,不如拥有一个包含 vector&lt;OrderBookEntry&gt;OrderBook,并且知道如何计算它包含的条目。

标签: c++ loops class vector constructor


【解决方案1】:

computeAveragePriceOrderBookEntry 中的成员函数,但条目是std::vector&lt;OrderBookEntry&gt;,而不是OrderBookEntry,因此它没有这样的成员函数。

我建议您将computeAveragePrice 移出OrderBookEntry 类,该类仅包含有关单个OrderBookEntry 的信息。您可以创建另一个类来保存OrderBookEntry 的集合并将其放在那里。这个类可以是 std::vector&lt;OrderBookEntry&gt; 的简单包装器:

例子:

class OrderBook {   // A class to store a collection of OrderBookEntry:s
public:
    // A function to add an `OrderBookEntry`. You'll have to make this in
    // in the way you want. This is just an example:

    template<class... Args>
    decltype(auto) add(Args&&... args) {
        return entries.emplace_back(std::forward<Args>(args)...);
    }
    
    double computeAveragePrice() const;              // move it here

    // some member functions that just call the vector's member functions:
    size_t size() const { return entries.size(); }

    OrderBookEntry& operator[](size_t idx) { return entries[idx]; }
    const OrderBookEntry& operator[](size_t idx) const { return entries[idx]; }

    auto cbegin() const { return entries.cbegin(); }
    auto cend() const { return entries.cend(); }
    auto begin() const { return entries.cbegin(); }
    auto end() const { return entries.cend(); }    
    auto begin() { return entries.begin(); }
    auto end() { return entries.end(); }

private:
    std::vector<OrderBookEntry> entries;    // put the vector in here
};

double OrderBook::computeAveragePrice() const {
    // you need to #include <numeric> to use the accumulate function:
    if(entries.empty()) return NAN;   // not-a-number
    return std::accumulate(entries.begin(), entries.end(), 0.,
                           [](double tot, const OrderBookEntry& e ) {
                               return tot + e.price;
                           }) / entries.size();
}

这样,您的main 将如下所示:

int main() {
    OrderBook entries;            // use the new collection class
        
    // Adding entries into entries
    entries.add(                  // using the add() member function
        10000,
        0.001,
        "2020/03/17 17:01:24.88492",
        "BTC/USDT",
        OrderBookType::bid
    );

    entries.add(
        20000,
        0.002,
        "2020/03/17 17:01:24.88492",
        "BTC/USDT",
        OrderBookType::bid
    );

    // Prints prices of all entries
    for (OrderBookEntry& entry : entries) {
        std::cout << "The price entry " << &entry << " is " << entry.price << '\n';
    }
    
    std::cout << "The average price is " << entries.computeAveragePrice() << '\n';
        
    return 0;
}

请注意,虽然打印&amp;entry 将打印OrderBookEntry 的地址。如果你想打印一些有意义的东西,你需要为operator&lt;&lt; 添加一个重载,它接受一个OrderBookEntry 作为输入。

例子:

std::ostream& operator<<(std::ostream& os, const OrderBookEntry& e) {
    return os << e.product;
}

然后您可以打印该条目,但不能通过获取其地址:

for (const auto& entry : entries) {
    std::cout << "The price entry " << entry << " is " << entry.price << '\n';
    //                                 ^^^^^
}

【讨论】:

    猜你喜欢
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多