c++ - 遍历数组以存储重复的字符串并将相同字符串的值相加 C++

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

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

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

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

关于c++ - 遍历数组以存储重复的字符串并将相同字符串的值相加 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40103350/

相关文章:

jquery - 在Jquery中以交替顺序合并两个数组

python - 一个一个地遍历 ndarray 的所有元素

c++ - 如果我为多个编写器使用额外的互斥锁,我可以在 SQLite3 中使用 WAL 模式吗?

c++ - ruby 如何像 C++ 一样以 scanf 风格读取用户输入

arrays - 比较缺少元素的两个 slice

jquery - 循环遍历 div 内的某些元素

r - 使用 for 循环仅获取选定变量的相关性

c++ - C为多个项目创建一个构建目录

c++ - fstream文件读取失败

c - 读取字符串中的数字序列