I need to make a program, that counts every integer, that belongs to the same string.
For example, in my data file this is written:
5
town park 50
riverside 20
riverside 30
riverside 40
town park 45
And the answer should be:
town park 95
riverside 90
I have put every single one of those in the data file into a structure Pathway
1 2 3 4
{
String name;
int time;
};
and after that I have put every single one in an array. The array works fine, but I can't seem to add the same strings without skipping a few. Here's my code
1 2 3 4 5 6 7 8 9 10 11 12 13
void Sort(int n, Pathway A[])
{
for(int i=0;i<n;i++)
{
for(int j=1;j<n;j++)
{
if (A[i].name==A[j].name)
{
A[i].time=A[i].time+A[j].time;
n--;
}
}
}
I would be very grateful, if someone would tell me the proper way to add them.
Depending where you are at in your c++ learning career a <map> might be useful. Stay with the struct and use name as the map key and the time as cumulative time using the <map> key functionality to determine whether a name already exists or whether a new entry is created.
# include <iostream>
# include <string>
# include <vector>
# include <map>
# include <sstream> //std::istringstream
# include <fstream> //std::ifstream
# include <utility> //std::pair
# include <functional> //std::ref
struct Pathway
{
std::string m_name;
int m_time;
Pathway(const std::string& name, constint time)
: m_name(name), m_time(time){}
};
std::ostream& operator << (std::ostream& os, const Pathway& p)
{
os << p.m_name << " " << p.m_time << "\n";
return os;
}
int main()
{
std::ifstream inFile{"C:\\test.txt"};
std::map<std::string, int> pathMap{};
std::vector<Pathway> allPaths{};
if(inFile)
{
std::string dummy{};
getline(inFile, dummy);
//first line has number of entries, read it into dummy
std::string line{};
while (getline(inFile, line))
{
auto last_index = line.find_last_not_of("0123456789");
auto name = line.substr(0, last_index);
auto timeString = line.substr(last_index + 1);
std::istringstream stream{timeString};
int time{};
stream >> time;
//convert string to int
if (inFile)
{
auto itr = pathMap.find(name);
if(itr == pathMap.end())
//i.e. name doesn't exist in the map
{
pathMap.insert((std::make_pair(std::ref(name), time)));
}
else
{
itr -> second += time;
//increase the value by time
}
}
}
}
for (constauto& elem : pathMap)
{
allPaths.emplace_back(Pathway(elem.first, elem.second));
//construct Pathway objects in situ
}
for (constauto& elem : allPaths)std::cout << elem;
}