【问题标题】:How to add values in STL:: List container?如何在 STL:: List 容器中添加值?
【发布时间】:2015-03-28 00:23:52
【问题描述】:

我正在编写一个程序来在 stl::list 容器中添加货币价值。我如何解析并将这些值加在一起?谢谢。

我要使用的代码如下 - 我在底部添加了累积。

void readFile()
{
    string line, nuMoney, money, cents;
    unsigned long dollarSign, period;

    ifstream myfile("MONEY.txt");

    int numLines = countLines("MONEY.txt");
    //cout << "NUMLINES: " << numLines << endl;

    if (!myfile.is_open())
    {
        cout << "ERROR: File could not be opened." << endl;
    }

    for (int i=0; i < numLines-1; i++)
    {
        getline(myfile, line, '\n');
        dollarSign = line.find('$');
        period = line.find('.');

        // remove commas.
        line.erase (remove(line.begin(), line.end(), ','), line.end()); 

        money = line.substr(dollarSign+1);
        //cout << money << endl;

        double MONEYS = atof(money.c_str());
        //cout << fixed << setprecision(2) << MONEYS << '\n';

        list<double> acct;
        acct.push_back(MONEYS);
    }

    int sum = accumulate(acct.begin(), acct.end(), 0);
    cout << "SUM: " << sum << endl;
}

【问题讨论】:

  • 有人已经为你写好了算法:std::accumulate
  • @WhozCraig 它不起作用。
  • 举例说明你想做什么。
  • @JohnnyTran 为我工作:ideone.com/eqmPHd
  • 在@Atomic_alarm 上面发布的代码中使用它

标签: c++ list templates stl std


【解决方案1】:

这显示了如何对列表的内容求和

#include <list>
#include <algorithm>
#include <numeric>

int main()
{
    std::list<int> myList;
    myList.push_back(1);
    myList.push_back(2);
    myList.push_back(3);
    myList.push_back(4);
    int result = std::accumulate(std::begin(myList), std::end(myList), 0);
    std::cout << result; // Prints 10 on screen
}

【讨论】:

    猜你喜欢
    • 2013-12-14
    • 1970-01-01
    • 2013-04-20
    • 2016-09-20
    • 1970-01-01
    • 2021-09-15
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多