std::generate - 访问向量中的前一个元素

问题描述 投票:0回答:1

我正在使用 std::generate 构造一个结构并推入一个向量。为了构造该结构,我需要引用序列中的前一个结构。有没有办法在 c++20 中做到这一点?我宁愿不使用 boost 或第三方库。 谢谢!

#include <iostream>
#include <vector>
#include <algorithm>

struct CashFlow {

    double begin_balance;
    double payment;
    double interest;
    double prin_repayment;
    double end_balance;
    size_t month;

    friend std::ostream& operator<<(std::ostream& os, const CashFlow& cf);
};

std::vector<CashFlow> cashflows(n);   

//this is i = 0 struct
CashFlow c;
c.month = 0;
c.begin_balance = initial_prin;
c.end_balance = initial_prin;

cashflows.push_back(c);

std::generate(begin(cashflows) + 1, end(cashflows), [&, i = 1]() 
mutable {
    CashFlow c;
    c.month = i;
    //here I need end_balance member of the previous struct in the vector
    c.begin_balance = std::prev(cashflows.end()).end_balance; // this does not work
    c.payment = payment;
    c.end_balance = initial_prin * ((100 - pow(1 + 0.08, i)) / (100 - 1));
    c.interest = 0.08 * c.begin_balance;
    c.prin_repayment = 80 - c.interest;
    return c;
});
c++20
1个回答
0
投票

使用

std::transform

std::transform(
    std::begin(cashflows),
    std::end(cashflows) - 1,
    std::begin(cashflows) + 1,
    [i = 1] (const auto &prev) mutable {
      ...

如果您

reserve
容量并使用
std::back_inserter
:

,您还可以避免默认初始化向量元素
std::vector<CashFlow> cashflows;
cashflows.reserve(n);
...
cashflows.push_back(c);

std::transform(
    std::begin(cashflows),
    std::begin(cashflows) + n - 1,
    std::back_inserter(cashflows),
    [i = 1] (const auto &prev) mutable {
      ...
© www.soinside.com 2019 - 2024. All rights reserved.