c++ hashmap ; update adding new keys and not updating - c++

I have this code where I take a hashmap, take a key and update the value. However, the loop is never ending as the code is adding new keys to the hashmap rather than updation. Please let me know if you can help :-
typedef indri::utility::HashTable< Gram*, double, Gram::hash,Gram::string_comparator > HGramScore;
HGramScore _gramScores;
HGramScore::iterator iter_score;
cout << "Sizeee " << _gramScores.size() << endl;
int count = 0;
for (iter_score = _gramScores.begin(); iter_score != _gramScores.end() ; iter_score++)
{
count++;
cout << "Sizeee " << _gramScores.size() << endl;
_gramScores.insert(*iter_score->first , *iter_score->second / total_score_count);
cout << count << endl;
}

Related

Confused about behavior when reading stdin c++

I am attempting to solve a problem to improve my C++ skills. I have come across some unusual behavior and I am not sure why it is happening.
I initially parsed the stdin and sorted it into a map with a key and a matching element (value). I then want to read a list of keys and output the element (value). However, for some of the key names it returns the correct value but for others it does not, but, if I hard code the intended key it works.
I know I am parsing correctly since the correct key and value are in the map as shown at the end of my output.
I assume it is an issue with reading stdin since the boolean str.compare("tag1.tag2~name") == 0 never evaluates to 0.
The code is as follows:
//'it' is the name of my map
//q = 3
for (int i = 0; i < q; i++)
{
getline(cin, str);
if (str.compare("tag1.tag2~name") == 0)
{
cout << "key is found" << endl;
}
else
{
cout << "'" << str << "'" << endl;
}
if (it.count(str) == 0)
{
cout << "Not Found!" << endl;
}
else
{
cout << it[str] << endl;
}
}
map<string, string>::iterator ptr;
cout << "\nThe map it is : \n";
cout << "\tKEY\tELEMENT\n";
for (ptr = it.begin(); ptr != it.end(); ++ptr) {
cout << '\t' << ptr->first
<<"\t" + ptr->second << "\n";
}
return 0;
The output is:
'tag1.tag2~name
Not Found!
'tag1~name
Not Found!
'tag1~value'
HelloWorld
The map it is :
KEY ELEMENT
tag1.tag2~name Name1
tag1~value HelloWorld
The input is :
tag1.tag2~name
tag1~name
tag1~value
Thank you! I have been struggling with this for a while.

c++: How can I print vector elements' indexes every time I print the vector?

So, I have a vector of boats. I need to access these boats and modify them (i.e. delete them) regularly, so it would be really nice if I could print their index along with all their other information, but I can't seem to figure out how.
The closest I got to it was with a simple for loop, but that eventually prints the current index along with the previous ones, as the vector size grows (since my i was < vector.size())
vector <Boat> berths_reg;
//print vector elements info
void Boat::print_info()
{
cout << endl;
for(int i = 0; i < berths_reg.size(); i++)
{
cout << "Index : " << i << endl;
}
cout << "Boat type : " << type << endl;
cout << "Boat length : " << length << endl;
cout << "Draft depth : " << draft << endl;
cout << endl;
}
//iterate through vector to print all elements
void print_vector()
{
vector <Boat> ::iterator it;
for (it = berths_reg.begin(); it != berths_reg.end(); ++it)
{
it->print_info();
}
}
//Storing boats (objects data) inside vector
void add_boat(Boat* b, string type, int length, int draft)
{
b->get_type(type);
b->get_length(length);
b->get_draft(draft);
berths_reg.push_back(*b);
}
Simply print both the index and the info within the same loop:
void print_vector()
{
for(int i = 0; i < berths_reg.size(); ++i)
{
cout << "Index : " << i << endl;
berths_reg[i].print_info();
}
}

Field values for nested structs not getting set in protobuf

I am using google protobuffer for data deserialization, but my issue is that the field values for the nested structures are not getting set. I checked the bin file in a hex editor and the values look fine. However, since the first field in my nested struct is a float and if I try to get the corresponding number of bytes and decode it into a float, the value seems fine.
Can someone advice what else I can do to check this or what perhaps is happening? I have tried using ParseFromIstream as well.
the proto file is :
syntax = "proto3";
package generatedata;
message DataSample {
DataSample_Safe DataSafe = 1;
uint32 PassReSts = 2;
uint32 Dir = 3;
}
message DataSample_Safe {
float ALast = 1;
uint32 ALastQf = 2;
}
message DataSampleMultiple
{
repeated DataSample finaldata = 1;
}
The C++ code is
fstream in("test.bin", ios::in | ios::binary);
generatedata::DataSample test_data;
while(in.read((char *) &test_data,sizeof(test_data)))
{
const generatedata::DataSample_Safe& veh = test_data.datasafe();
cout << "safe" << veh.alast() << endl;
cout << "First " << test_data.passrests() << endl;
cout << "Second " << test_data.dir() << endl;
}
Using ParseFromIstream, the code is
generatedata::DataSampleMultiple test_data;
test_data.ParseFromIstream(&in);
for(int i = 0 ; i < test_data.finaldata_size(); i ++)
{
const generatedata::DataSample& veh = test_data.finaldata(i);
const generatedata::DataSample_Safe& check = veh.datasafe();
cout << "safe" << check.alast() << endl;
cout << "First " << veh.passrests() << endl;
cout << "Second " << veh.dir() << endl;
}
in the above case using ParseFromIstream, the final data size is 0
The first cout gives segmentation fault as the value of safe has not been set. However, the second and third couts are output correctly when using istream::read

Where am I wrong? SetDataBuffer for DATE

I want to do array fetch for DATE in oracle with following code. It compiles alright and export all other data types correctly, except for the DATE type. The program says "ora-32146 cannot peform operation on a null date".
Any one can see where I am wrong?
Statement *stmt = conn->createStatement("SELECT AGE,CASH2, BIRTHDATE from myTable2"); /*, CASH1, CASH2, BIRTHDATE*/
//stmt->setMaxParamSize(1,sizeof(Number));
ResultSet *rs=stmt->executeQuery();
string myName[400];
int myAge[400];
double myCash1[400];
double myCash2[400];
oracle::occi::Date myBirthDate[400];
//rs->setDataBuffer(1,myName,OCCI_SQLT_STR,sizeof(string));
rs->setDataBuffer(1,myAge,OCCIINT,sizeof(int));
rs->setDataBuffer(2, myCash2, OCCIBDOUBLE, sizeof(double),NULL);
rs->setDataBuffer(3, myBirthDate,OCCI_SQLT_DATE, sizeof(oracle::occi::Date),NULL);
while (rs->next(200)==ResultSet::DATA_AVAILABLE)
{
//cout << "Exporting batch..." << endl;
for(size_t i=0;i<rs->getNumArrayRows();i++)
{
//cout << myName[i] << endl;
cout << myAge[i] << endl;
//cout << myCash1[i] << endl;
cout << myCash2[i] << endl;
int y;
unsigned int m,d,h,mm,s;
myBirthDate[i].getDate(y,m,d,h,mm,s);
cout << y <<"-"<<m<<"-"<<s << endl;
}
}
Figured it out.
using rs->setDataBuffer(3, myBirthDate,OCCI_SQLT_DAT, 7,NULL);
works out all right.
No good document on OCCI...

final project, Dynamic Programming. Need second set of eyes

I feel really stupid coming to ask this question here today after bugging everyone yesteday on understanding the algorithm. But I am not looking at this thing straight anymore. Anyways, it is a knapsack probled, solved with memoization and dynamic progrmming. The problem is that the printout of my answers is not matching the requierements.
All I want is a second look at it and if someone can point me where I am wrong at.
Appreciated for all the help.
This is the ProfitHeader.h file
#ifndef PROFITHEADER_H_
#define PROFITHEADER_H_
#include <string>
#include <map>
#include <vector>
using namespace std;
namespace kproblem{
typedef int Money;
typedef int Labor;
struct Resources{
Money liquidity;
Labor officeWork;
Labor programmingWork;
Resources(Money li, Labor of, Labor pro) : liquidity(li), officeWork(of), programmingWork(pro){}
//operator -=
Resources & operator -=( const Resources &rhs ){
liquidity -=rhs.liquidity;
officeWork -=rhs.officeWork;
programmingWork -=rhs.programmingWork;
return *this;
}
//operator< Used to make sure that key elements Match. will not modify (this)
bool operator<(const Resources & rhs) const{
if(this->liquidity < rhs.liquidity)
return true;
else if(this->liquidity > rhs.liquidity)
return false;
else if(this->officeWork < rhs.officeWork)
return true;
else if(this->officeWork > rhs.officeWork)
return false;
//this is the iff conditional
else if(this->programmingWork < rhs.programmingWork)
return true;
else
return false;
}
};
//Global Operator-. This will not modify (this).
Resources operator-( const Resources & lhs, const Resources & rhs ){
return Resources(lhs.liquidity - rhs.liquidity,
lhs.officeWork - rhs.officeWork, lhs.programmingWork - rhs.programmingWork);
}
//This is the Project Struct. It should contain the resources and data from the file.
struct Project{
string name;
Resources resources;
Money profit;
Project(string n, Resources re, Money p) : name(n), resources(re), profit(p) {}
};
//Definition of the ValueMap
typedef map<pair<Resources, vector<Project>::size_type>, pair<Money, bool>> ValueMap;
}
#endif
This is my main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <exception>
#include "ProfitHeader.h"
using namespace std;
using namespace kproblem;
//The following was provided to us on the program
class IO_Exception : public runtime_error
{
public:
IO_Exception(const string & message) : runtime_error(message) { }
};
void readProjects(vector<Project> & projects, const string & fileName)
{
ifstream infile(fileName.c_str());
if (!infile)
throw IO_Exception("Could not open " + fileName);
string oneLine;
unsigned int lineNum = 0;
while (getline(infile, oneLine))
{
istringstream st(oneLine);
lineNum++;
string name;
Money liquidity;
Labor officeWork;
Labor programmingWork;
Money profit;
st >> name;
st >> liquidity;
st >> officeWork;
st >> programmingWork;
st >> profit;
if (st.fail())
{
cerr << "Skipping line number " << lineNum << ": "
<< oneLine << endl;
continue;
}
string junk;
if (st >> junk)
{
cerr << "Skipping line number " << lineNum << ": "
<< oneLine << endl;
continue;
}
projects.push_back(Project(name, Resources(liquidity, officeWork, programmingWork), profit));
}
if (!infile.eof())
throw IO_Exception("Error reading from " + fileName);
}
//Class Best Profit.
//This class will calculate the best possible profit we can get.
Money bestProfit(const vector<Project> & projects, Resources res, ValueMap & valMap,int n){
//initialize the best 2 possible solutions.
Money best1;
Money best2;
Money map; // the map where ou answers are stored
// First check if we are not at the end of the projects
if(n == 0){
return 0;
}
//now we are going to check the best project possible.
//Check the subinstance if it was solved.
if(valMap.find(make_pair(res, n-1)) != valMap.end()){
map = valMap.find(make_pair(res, n-1))->second.first;
return map;
}//check if the subinstance is solved. if it is return the value.
best1 = bestProfit(projects, res, valMap, n-1);//first best possible solution
//check the resources for the last project only. Fopr the second best possible solution.
if(res.liquidity >= projects.at(n-1).resources.liquidity
&& res.officeWork >= projects.at(n-1).resources.officeWork
&& res.programmingWork >= projects.at(n-1).resources.programmingWork){// feasability Check.
//all the above are requiered as it is necessary to check for all of them when doing the calculations.
best2 = bestProfit(projects, res - projects[n-1].resources, valMap, n-1) + projects[n-1].profit;
}
else{
best2 = 0;
}
//after the whole check compare the results and store the best possible result in the map.
if(best1 >= best2){
valMap.insert(make_pair(make_pair(res, n), make_pair(best1,false)));
return best1;
}
else{
valMap.insert(make_pair(make_pair(res, n), make_pair(best2,true)));
return best2;
}
}
//reportBestProfit. This will call Best profit and help us print the final results.
void reportBestProfit(vector<Project> projects, Resources resources){
ValueMap valueMap;
//Variables for the total resources used.
Money liq = 0;
Money ow = 0;
Money pw = 0;
int n = 1000; //number of projects, put here for fast testing
Money bestP = bestProfit(projects, resources, valueMap, n);
//Iterate the valuemap and print the best projects available to us.
cout << "Selected Projects -" << endl;
for(int i= 1; i <= 1000; i++){
//if(valueMap.find(make_pair(resources, i-1)) == valueMap.end()){
if(valueMap.find(make_pair(resources, i))->second.second == true){
//if(valueMap.find(make_pair(resources, i))->second.first != valueMap.find(make_pair(resources, i-1))->second.first){
//cout << valueMap.find(make_pair(resources, i))->second.first; //money
//cout <<" "<< valueMap.find(make_pair(resources, i))->second.second; //boolean
cout << " " << projects.at(i-1).name << " " << projects.at(i-1).resources.liquidity <<" ";//projects
cout << projects.at(i-1).resources.officeWork << " " << projects.at(i-1).resources.programmingWork;
cout << " " << projects.at(i-1).profit << endl;//profit
//}
}
}
cout << "Total Resources Used -" << endl;
//Print the resources consumed.
for(int i= 1; i <= 1000; i++){
if(valueMap.find(make_pair(resources, i))->second.second == true){
liq += projects.at(i-1).resources.liquidity;
ow += projects.at(i-1).resources.officeWork;
pw += projects.at(i-1).resources.programmingWork;
}
}
cout << " " << "Liquidity: " << liq <<endl;
cout << " " << "Office Work: " << ow <<endl;
cout << " " << "Programming Work: " << pw <<endl;
//Print the total Profit.
cout << "Profit: " << bestP << endl;
system("PAUSE");
}
int main()
{
vector<Project> projects;
try
{
readProjects(projects, "Proj5Data.txt");
}
catch (const IO_Exception & ex)
{
cerr << "IO error from: " << ex.what() << endl;
return 1;
}
//these values can be changed for different analysis on projects.
Money liquidity = 200;
Labor officeWork = 450;
Labor programmingWork = 1000;
cout << "Available resources - " << endl
<< " Liquidity: " << liquidity << endl
<< " Office Work: " << officeWork << endl
<< " Programming Work: " << programmingWork << endl;
reportBestProfit(projects, Resources(liquidity, officeWork, programmingWork));
return 0;
}
The project file that contains the projects can be downloaded temporarily here:
https://rapidshare.com/files/459861869/Proj5Data.txt
my guess is the problem is on the valmap find, but I have tried all kinds of combinations and it does not work at all.
Finally this is the final printout I should be getting from this:
But instead I am getting all these other results, including some of the ones I need:
Again thank you for the one that can slap me in the head and say, you FOO, you shouldn't be doing this anymore :).
removing this would get rid of the leading numbers on the second part of the output
cout << valueMap.find(make_pair(resources, i))->second.first; //money
cout <<" "<< valueMap.find(make_pair(resources, i))->second.second; //boolean
cout << " "
the values you print at this point haven't been filtered by and ordered by which is why i think your printing these values
but you don't have code to print "The total resources used -" part
OK, so yes I do have an answer. Is now complete (after edit)
void reportBestProfit(vector<Project> projects, Resources resources){
ValueMap valueMap;
//Variables for the total resources used.
Money liq = 0;
Money ow = 0;
Money pw = 0;
vector<Project> result;
int n = 1000; //number of projects, put here for fast testing
Money bestP = bestProfit(projects, resources, valueMap, n);
//Iterate the valuemap and print the best projects available to us.
cout << "Selected Projects -" << endl;
// this loop just iterates through the values, it does not check the initial resources.
for(int i= 999; i > 0; i--){
//if(valueMap.find(make_pair(resources, i-1)) == valueMap.end()){
//check first If I still have resources available
if(resources.liquidity >=0 && resources.officeWork >= 0 && resources.programmingWork >= 0){
if(valueMap.find(make_pair(resources, i))->second.second == true){
//when I find the first true, I need to substract the resources of it from the base resources,
//to ask the question again.
resources.liquidity -= projects.at(i-1).resources.liquidity;
resources.officeWork -= projects.at(i-1).resources.officeWork;
resources.programmingWork -= projects.at(i-1).resources.programmingWork;
//Push the results into a vector for the printout
result.push_back(Project(projects.at(i-1).name,
Resources(projects.at(i-1).resources.liquidity,
projects.at(i-1).resources.officeWork,
projects.at(i-1).resources.programmingWork),
projects.at(i-1).profit));
//Also in one shot add together the resources used
liq += projects.at(i-1).resources.liquidity;
ow += projects.at(i-1).resources.officeWork;
pw += projects.at(i-1).resources.programmingWork;
}
}
}
//Print the saved vector in reverse order
for(int size = result.size(); size != 0; size--){
cout << " " << result.at(size -1).name;
cout << " " << result.at(size -1).resources.liquidity;
cout << " " << result.at(size -1).resources.officeWork;
cout << " " << result.at(size -1).resources.programmingWork;
cout << " " << result.at(size -1).profit << endl;
}
cout << "Total Resources Used -" << endl;
////Print the resources consumed.
cout << " " << "Liquidity: " << liq <<endl;
cout << " " << "Office Work: " << ow <<endl;
cout << " " << "Programming Work: " << pw <<endl;
//Print the total Profit.
cout << "Profit: " << bestP << endl;
system("PAUSE");
}
Basically I was not substracting the resources, so I was always having over resources, but once I did that viola! it works. Thank you guys for looking at it, I guess I just needed inspiration this morning.