如果您只想使用std::pair 和std::vector,那么您可以使用以下程序作为起点(参考):
版本 1:产品名称会重复
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
int main()
{
std::ifstream inputFile("input.txt"); //open the file
std::string line;
std::vector<std::pair<std::string, double>> vec;
std::string name;
double price, count;
if(inputFile)
{ std::getline(inputFile, line, '\n');//read the first line and discard it
while(std::getline(inputFile, line, '\n'))//read the remaining lines
{
std::istringstream ss(line);
ss >> name; //read the name of the product into variable name
ss >> count;//read the count of the product into variable count
ss >> price;//read the price of the product into variable price
vec.push_back(std::make_pair(name, count * price));
}
}
else
{
std::cout<<"File cannot be opened"<<std::endl;
}
inputFile.close();
//lets print out the details
for(const std::pair<std::string, double> &elem: vec)
{
std::cout<< elem.first<< ": "<< elem.second<<std::endl;
}
return 0;
}
您可以/应该使用class 或struct 而不是使用std::pair。
上面程序的输出可以看到here。输入文件也附在上面的链接中。以上版本1的输出为:
bread: 12
butter: 21
bread: 6.5
oil: 66
butter: 6.2
bread: 3.3
正如您在版本 1 的输出中看到的那样,产品的名称是重复的。如果您不想要重复的名称并且想要总结与重复键相对应的值,请查看下面给出的版本 2:
第 2 版:产品名称不重复
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
int findKey(const std::vector<std::pair<std::string, double>> &vec, const std::string &key)
{ int index = 0;
for(const std::pair<std::string, double> &myPair: vec)
{
if(myPair.first == key)
{
return index;
}
++index;
}
return -1;//this return value means the key was not already in the vector
}
int main()
{
std::ifstream inputFile("input.txt");
std::string line;
std::vector<std::pair<std::string, double>> vec;
std::string name;
double price, count;
if(inputFile)
{ std::getline(inputFile, line, '\n');
while(std::getline(inputFile, line, '\n'))
{
std::istringstream ss(line);
ss >> name;
ss >> count;
ss >> price;
int index = findKey(vec, name);
if(index == -1)
{
vec.push_back(std::make_pair(name, count * price));
}
else
{
vec.at(index).second += (count *price);
}
}
}
else
{
std::cout<<"File cannot be opened"<<std::endl;
}
inputFile.close();
//lets print out the details
for(const std::pair<std::string, double> &elem: vec)
{
std::cout<< elem.first<< ": "<< elem.second<<std::endl;
}
return 0;
}
版本2的输出是
bread: 21.8
butter: 27.2
oil: 66
可以看到here。