【问题标题】:Looping through array to store duplicate string and add up values of the same string C++循环遍历数组以存储重复的字符串并将相同字符串的值相加 C++
【发布时间】:2016-10-18 08:34:03
【问题描述】:

对 C++ 比较陌生,以下是我的代码:

void displaydailyreport()
{
    std::string myline;

    string date[100]; // array for dates
    int dailyprice =0;
    ifstream myfile("stockdatabase.txt"); // open textfile

    int i,j;
    for(i=0;std::getline(myfile,myline);i++) // looping thru the number of lines in the textfile
    {
        date[i] = stockpile[i].datepurchased; // stockpile.datepurchased give the date,already seperated by :
        cout<<date[i]<<endl; // prints out date

        for(j=i+1;std::getline(myfile,myline);j++)
        {
            if(date[i] == date[j])  // REFER TO //PROBLEM// BELOW
                dailyprice += stockpile[i].unitprice;  // trying to add the total price of the same dates and print the
                           //  datepurchased(datepurchased should be the same) of the total price
                           // means the total price purchased for  9oct16
        }
    }
    cout<<endl; 
}

一切都已经被检索和分隔:从我写的方法中

stockpile[i].unitprice会打印出价格

stockpile[i].itemdesc会打印出物品描述

问题

我试图总结相同日期的单价。并显示总单价+日期 你可以看到我的文本文件,

如果我执行date[i] == date[j] 的上述 if 语句,但它不起作用,因为如果其他地方还有另一个 9oct 怎么办?

我的文本文件是:

itemid:itemdesc:unitprice:datepurchased

22:blueberries:3:9oct16    
 11:okok:8:9oct16    
16:melon:9:10sep16    
44:po:9:9oct16    
63:juicy:11:11oct16   
67:milk:123:12oct16    
68:pineapple:43:10oct16
69:oranges:32:9oct16 <--

C++ 是否有数组对象,我可以这样做:

testArray['9oct16'] 

//EDIT// 尝试 Ayak973 的答案后,用 g++ -std=c++11 Main.cpp 编译

Main.cpp: In function ‘void displaydailyreport()’:
Main.cpp:980:26: error: ‘struct std::__detail::_Node_iterator<std::pair<const std::basic_string<char>, int>, false, true>’ has no member named ‘second’
              mapIterator.second += stockpile[i].unitprice;

【问题讨论】:

    标签: c++ arrays for-loop g++ text-files


    【解决方案1】:

    借助 c++11 支持,您可以使用 std::unordered_map 来存储键/值对:

    #include <string>
    #include <unordered_map>
    
    std::unordered_map<std::string, int> totalMap;
    
    //...
    
    for(i=0;std::getline(myfile,myline);i++) { 
        auto mapIterator = totalMap.find(stockpile[i].datepurchased); //find if we have a key
        if (mapIterator == totalMap.end()) {  //element not found in map, add it with date as key, unitPrice as value
            totalMap.insert(std::make_pair(stockpile[i].datepurchased, stockpile[i].unitprice));
        }
        else { //element found in map, just sum up values
             mapIterator->second += stockpile[i].unitprice;
        }
    }
    

    之后,您得到一张地图,其中日期为键,单价总和为值。要获取值,您可以使用基于范围的 for 循环:

    for (auto& iterator : totalMap) {
        std::cout << "Key: " << iterator.first << " Value: " << iterator.second;
    }
    

    【讨论】:

    • 我必须执行 g++ -std=c++11 Main.cpp 才能编译,它给了我编译错误,请参阅我的编辑@Ayak973
    • @user2601570 :我的错,我没有测试代码,我已经编辑了我的帖子,只需使用mapIterator-&gt;second
    • 谢谢,但它会从文本文件的最后一行打印出来。它应该以这种方式工作吗?
    • 是否可以有 2 个键?例如 itemdesc 和 datepurchased @Ayak973 我试过 makepair((itemdesc,datepurchased),unitprice) ,似乎不起作用。
    • @user2601570 :如果你想要两个键,你可以使用std::pair 或自定义struct,但是你需要提供一个散列函数对象和一个谓词来比较你的键的相等性。你可以阅读this来帮助你
    【解决方案2】:

    您可以使用以下链接中实现的哈希表 https://gist.github.com/tonious/1377667 或者您可以轻松定义具有哈希键和值的类,并定义类的数组。

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 2012-07-02
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 2015-10-22
      • 2015-01-17
      相关资源
      最近更新 更多