循环遍历数组以存储重复字符串并将相同字符串的值相加

Looping through array to store duplicate string and add up values of the same string C++

本文关键字:字符串 串并 字符 数组 遍历 存储 循环      更新时间:2023-10-16

对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++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;
}

您可以使用下面链接实现的哈希表https://gist.github.com/tonious/1377667或者您可以简单地定义类,它具有散列键和值,并定义类的数组。

相关文章: