CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 2 FirstFirst 12
Results 16 to 23 of 23
  1. #16
    Join Date
    May 2015
    Posts
    500

    Re: help needed with the c++ program

    @kaud: Thanks a lot.

    Regarding the data structure, i wanted to use map , as it is sorted. I know it is bit complicated data structure. But it worked for just displaying the input in sorted order. But it wont work for rearranging the timeperiod.

    I want to improve this data structure, so any inputs regarding this will be helpful.

    Next step for me to rearrange the time periond and sort internally
    Last edited by pdk5; March 17th, 2019 at 11:17 AM.

  2. #17
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: help needed with the c++ program

    For the two outputs, I used two sets with a specified comparator predicate which defines the required sort order for the set. That way you get the two outputs in the required order - by iterating the sets - without ever having to do any actual sorting!
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  3. #18
    Join Date
    May 2015
    Posts
    500

    Re: help needed with the c++ program

    Quote Originally Posted by 2kaud View Post
    For the two outputs, I used two sets with a specified comparator predicate which defines the required sort order for the set. That way you get the two outputs in the required order - by iterating the sets - without ever having to do any actual sorting!
    I changed somethings, to add the predicate sorting, but the list now is not getting sorted. I will check , but today will be very busy at work due to some release. i guess, i can check this only tomorrow afternoon now.

    @ kaud, thankyou very much for your patience and willingness to help. I am sorry, I have been asking lot of questions, which i could have found the answers myself. Actually my previous company has been using c++98, so i still need to come up speed with the latest.

    Code:
    //============================================================================
    // Name        : test.cpp
    // Author      : Pdk
    // Version     :
    // Copyright   : Your copyright notice
    // Description : Hello World in C++, Ansi-style
    //============================================================================
    
    #include <iostream>
    
    #include <string>
    
    #include <vector>
    #include <map>
    #include <list>
    #include <fstream>
    #include <sstream>
    #include <iomanip>
    #include <conio.h>
    
    using namespace std;
    
    const int year = 365;
    const int month= 30;
    const int week= 7;
    const int day =  1;
    
    std::map<string,int> myMap = {
    	    {"y", year},
    	    {"m", month},
    	    {"w", week},
    	    {"d", day}
    };
    
    class Line;
    
    std::list<Line> theList;
    
    class Line
    {
    public:
        //1.1: Private Members
        string m_LineId;
        int m_LineValue;
        int m_Value1;
        int m_Value2;
    
    public:
        //1.2: Department Class Constructor
        Line(const string & input)
        {
        	m_LineId = input;
    
        	std::vector<std::string> inputTokens;
    
        	cout << "\n Input is " << input;
        	stringstream is(input);
            std::string r;
            while(std::getline(is,r,','))
            {
            	inputTokens.push_back(r);
            	cout <<"\n"<< r;
            }
    
        	std::string timespan = inputTokens[0];
    
        	std::string temp;
        	int num=0;
        	int total =0;
        	string tempstring = timespan;
    
        	while(!tempstring.empty())
        	{
        		std::string::size_type sz;   // alias of size_t
        		num = std::stoi(tempstring, &sz);
        		string type = tempstring.substr(sz,1);
        		int num_days = myMap.at(type);
        		total = total+num*num_days;
        		tempstring = tempstring.substr(sz+1);
        	}
    
        	m_LineValue = total;
    
        	m_Value1 = std::stoi(inputTokens[1]);
        	m_Value2 = std::stoi(inputTokens[2]);
    
        	cout << "\n Value1 " << m_Value1;
        	cout << "\n Value2 " << m_Value2;
        }
    
        //1.3: Getter Functions
        string GetLineId()
        {
            return m_LineId;
        }
    
        int GetLineValue()
        {
            return m_LineValue;
        }
    
        int GetLineValue1()
        {
            return m_Value1;
        }
    
        int GetLineValue2()
        {
            return m_Value2;
        }
    
        // Print Content of the Line Class
        void Print_Line()
        {
            cout << "Line - ID" << m_LineId << "  Value:"
                << m_LineValue << ", Value1 and Value2 - "
                <<  m_Value1 << "  " << m_Value2 << endl;
        }
    };
    
    
    bool Compare_time_Predicate_Asc(
        Line First, Line Next)
    {
        //First Argument Stays First (Return true)
        if (First.GetLineValue() < Next.GetLineValue())
            return true;
    
        //First Argument goes Next (Swap) (Return false)
        if (First.GetLineValue() > Next.GetLineValue())
            return true;
    
        //a==b. First Argument Stays first
        //(No need to Swap)
        return true;
    }
    
    void processline(const std::string& input)
    {
       Line theline(input);
    
       theList.push_back(theline);
    
    }
    
    int main()
    {
    	ifstream fin;
    
    	fin.open("C:\\Users\\Pdk\\eclipse-workspace\\test\\src\\data.txt");
    
    	if(!fin.fail())
    	{
    		std::cout << "fin success";
    		std::string line;
    
    		// skip the header
    		std::getline(fin, line);
    
    		// store the contents of each line
    		while (std::getline(fin, line))
    		{
    		    std::cout << line << std::endl;
    
    	        // call the function to store each line
                if(!line.empty())
    		    processline(line);
    		}
    
    
            theList.sort(Compare_time_Predicate_Asc);
    
    		std::cout << " \n Sorted Input is : \n";
    		for (std::list<Line>::iterator it=theList.begin(); it != theList.end(); ++it)
    		{
    			   cout << "\n Line Id is  " << it->m_LineId;
    			   cout << "    Line value is" << it->m_LineValue;
    		}
    	}
    	else
    	{
    		std::cout << "fin failed";
    	}
    }

  4. #19
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: help needed with the c++ program

    If you're just used to C++98 then you have a big learning curve ahead of you to get up to speed with c++17. Going from C++98 to C++11 was massive and then C++11 to C++17 was big (C++14 was really just a tidy up of C++11). C++20 is coming out next year and this again is another massive change from C++17!

    Re the comp predicate. The idea is to use a set/map (I used a set) with a specified predicate for the comparison. This means that the elements are inserted in required sort order and no further sorting is required!

    For example:

    Code:
    	multiset<Rec, PerCmp1> s1;
    Where PerComp1 is the comparator functor.

    re Input. You know the format of the input (which is fixed), so from a string stream you can do this:

    Code:
    istringstream is(input);
    string timespan;
    string coma;
    unsigned value1;
    unsigned value2;
    
    if (getline(is, timespan, ',') && (is >> value1 >> coma >> value2) {
        // Process a good line
    } else {
        // Got a bad line
    }
    You don't then need to explicitly convert a string to a number as the extraction does this. Nor do you need a vector to hold the tokens etc. timespan, value1 and value2 hold the required values if the input line is valid. All that's now needed is to convert timespan to a number.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  5. #20
    Join Date
    May 2015
    Posts
    500

    Re: help needed with the c++ program

    sorry, it was quite busy week, was not able to find time to finish my work.

    But today squeezed in sometime
    Code:
    //============================================================================
    // Name        : test.cpp
    // Author      : Pdk
    // Version     :
    // Copyright   : Your copyright notice
    // Description : Hello World in C++, Ansi-style
    //============================================================================
    
    #include <iostream>
    
    #include <string>
    
    #include <vector>
    #include <set>
    #include <map>
    #include <fstream>
    #include <sstream>
    #include <iomanip>
    #include <conio.h>
    
    using namespace std;
    
    const int year = 365;
    const int month= 30;
    const int week= 7;
    const int day =  1;
    
    std::map<string,int> myMap = {
    	    {"y", year},
    	    {"m", month},
    	    {"w", week},
    	    {"d", day}
    };
    
    class Line;
    struct comp{
    	template<typename T>
    		bool operator()(const T & l, const T & r) const
    		{
    			return(l.m_LineValue<r.m_LineValue);
    		}
    };
    
    class Line
    {
    public:
        //1.1: Private Members
        string m_LineId;
        int m_LineValue;
        int m_Value1;
        int m_Value2;
    public:
        //1.2: Department Class Constructor
        Line(const string & inputLineId, int value1, int value2)
        {
         m_LineId = inputLineId;
    
         std::string temp;
         int num=0;
         int total =0;
         string tempstring = inputLineId;
         while(!tempstring.empty())
         {
          std::string::size_type sz;   // alias of size_t
          num = std::stoi(tempstring, &sz);
          string type = tempstring.substr(sz,1);
          int num_days = myMap.at(type);
          total = total+num*num_days;
          tempstring = tempstring.substr(sz+1);
         }
         m_LineValue = total;
         m_Value1 = value1;
         m_Value2 = value2;
         cout << "\n Value1 " << m_Value1;
         cout << "\n Value2 " << m_Value2;
        }
        //1.3: Getter Functions
        string GetLineId()
        {
            return m_LineId;
        }
        int GetLineValue()
        {
            return m_LineValue;
        }
        int GetLineValue1()
        {
            return m_Value1;
        }
        int GetLineValue2()
        {
            return m_Value2;
        }
        // Print Content of the Line Class
        void Print_Line()
        {
            cout << "Line - ID" << m_LineId << "  Value:"
                << m_LineValue << ", Value1 and Value2 - "
                <<  m_Value1 << "  " << m_Value2 << endl;
        }
    };
    
    
    int main()
    {
    
    	std::set<Line, comp> s1;
    
    	ifstream fin;
    
    	fin.open("C:\\Users\\Pdk\\eclipse-workspace\\test\\src\\data.txt");
    
    	if(!fin.fail())
    	{
    		std::cout << "fin success";
    		std::string line;
    
    		  string timespan;
    		  string coma;
    		  unsigned value1;
    		  unsigned value2;
    		  while (std::getline(fin, line))
    		  {
    			  std::istringstream is(line);
    			  if (getline(is, timespan, ',') && (is >> value1 >> coma >> value2) ){
    				  // Process a good line
    				  // call the constructor
    				  Line line(timespan, value1, value2);
    				  s1.insert(line);
    
                      std::cout << timespan << "  " << value1 << "  " << value2;
    
    			  } else {
    				  // Got a bad line
    			  }
    		  }
    	}
    
    	 std::cout  << " \n After sorting  \n";
    
      for(auto const & elem : s1)
        std::cout  << elem.m_LineId << " \n";
    }
    @Kaud: the parsing with your solution doesnot work for the input: 1y6m,10,40. I need to debug this issue now

  6. #21
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: help needed with the c++ program

    Yes - you're right. My test data had space(s) after the , . I knocked up the original code in about 1/2 hour and didn't do much testing.

    To also parse when there are no spaces, consider:

    Code:
    if (getline(is, timespan, ',') && (is >> value1) && is.ignore(numeric_limits<streamsize>::max(), ',') && (is >> value2)) {
        // Process a good line
    } else {
        // Bad input
    }
    The issue with the previous code was that >> for a string extracts up to a white space char. If there is a space after the , then that's fine. However if there's not, then the >> for coma was extracting ,40 as a string and giving an error when trying to extract value2. Using ignore extracts and ignores all chars upto and including the specified char (,) so leaving 40 for the value2 extraction. Doh!
    Last edited by 2kaud; March 21st, 2019 at 12:02 PM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  7. #22
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: help needed with the c++ program

    As the OP seems to have now obtained a solution and I indicted in previous posts that I had quickly coded a solution, I offer mine for info to any future readers of this post. Note that this is one way of doing it and that there are others.

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <sstream>
    #include <set>
    #include <iterator>
    #include <tuple>
    #include <algorithm>
    #include <numeric>
    #include <utility>
    #include <optional>
    using namespace std;
    
    constexpr char delim {','};
    
    class rTim {
    public:
    	rTim(const string& tm);
    
    	friend ostream& operator<<(ostream& os, const rTim& rt);
    
    	[[nodiscard]] auto gettp() const noexcept {return tp;}
    
    private:
    	inline static constexpr pair<char, unsigned> tpt[] {{'y', 365}, {'m', 30}, {'w', 7}, {'d', 1}};
    	inline static constexpr unsigned noelm {size(tpt)};
    
    	unsigned per[noelm] {};
    	optional<unsigned> tp {0};
    };
    
    struct Rec {
    	rTim rt;
    	unsigned dat;
    	unsigned val;
    
    	Rec(const rTim& r, unsigned d, unsigned v) : rt{r}, dat{d}, val{v} {}
    };
    
    struct PerCmp1 {
    	[[nodiscard]] bool operator()(const Rec& lhs, const Rec& rhs) const noexcept {
    		if (*(lhs.rt.gettp()) < *(rhs.rt.gettp()))
    			return true;
    
    		if (*(lhs.rt.gettp()) == *(rhs.rt.gettp())) {
    			if (lhs.dat < rhs.dat)
    				return true;
    
    			if (lhs.dat == rhs.dat) {
    				if (lhs.val < rhs.val)
    					return true;
    			}
    		}
    		return false;
    	}
    };
    
    struct PerCmp2 {
    	[[nodiscard]] bool operator()(const Rec& lhs, const Rec& rhs) const noexcept {
    		if (lhs.dat < rhs.dat)
    			return true;
    
    		if (lhs.dat == rhs.dat) {
    			if (*(lhs.rt.gettp()) < *(rhs.rt.gettp()))
    				return true;
    
    			if (*(lhs.rt.gettp()) == *(rhs.rt.gettp())) {
    				if (lhs.val < rhs.val)
    					return true;
    			}
    		}
    		return false;
    	}
    };
    
    ostream& operator<<(ostream& os, const rTim& rt)
    {
    	for (unsigned i {}; i < rt.noelm; ++i)
    		if (rt.per[i])
    			os << rt.per[i] << rt.tpt[i].first;
    
    	return os;
    }
    
    ostream& operator<<(ostream& os, const Rec& rc)
    {
    	return os << left << rc.rt << setw(2) << delim << rc.dat << setw(2) << delim << rc.val;
    }
    
    rTim::rTim(const string& tm)
    {
    	for (auto [no, ch, iss] {tuple{unsigned {}, char {}, istringstream {tm}}}; tp && (iss >> no >> ch); )
    		if (const auto f = find_if(begin(tpt), end(tpt), [ch](auto x){return x.first == ch;}); f != end(tpt))
    			*tp += (per[distance(begin(tpt), f)] = no) * f->second;
    		else
    			tp = nullopt;
    }
    
    int main(int argc, char *argv[])
    {
    	if (argc != 4) {
    		cerr << "Format of command is:\n" << argv[0] << " <inputfile> <outputfile1> <outputfile2>\n\nWhere:\n";
    		cerr << "<outputfile1> is sorted by timespan and then by dataset and finally by value (ascending order)\n";
    		cerr << "<outputfile2> is sorted by dataset and then by timespan and finally by value (ascending order)\n";
    		return 1;
    	}
    
    	ifstream ifs {argv[1]};
    
    	if (!ifs.is_open())
    		return cerr << "Cannot open input file " << argv[1] << endl, 2;
    
    	ofstream ofs1 {argv[2]};
    
    	if (!ofs1.is_open())
    		return cerr << "Cannot open output file " << argv[2] << endl, 3;
    
    	ofstream ofs2 {argv[3]};
    
    	if (!ofs2.is_open())
    		return cerr << "Cannot open output file " << argv[3] << endl, 4;
    
    	multiset<Rec, PerCmp1> s1;
    	multiset<Rec, PerCmp2> s2;
    	string header;
    
    	getline(ifs, header);
    
    	for (string line; getline(ifs, line); )
    		if (line.erase(0, line.find_first_not_of(" \t")); !line.empty())
    			if (auto [data, value, per, com, iss] {tuple{unsigned{}, unsigned{}, string{}, string{}, istringstream{line}}}; isdigit(line.front()) && getline(iss, per, delim) && (iss >> data) && iss.ignore(numeric_limits<streamsize>::max(), delim) && (iss >> value)) {
    				const rTim rt {per};
    
    				if (rt.gettp()) {
    					s1.emplace(rt, data, value);
    					s2.emplace(rt, data, value);
    				} else
    					cerr << "Invalid time period: " << line << endl;
    			} else
    				cerr << "Invalid line format: " << line << endl;
    
    	ofs1 << header << '\n';
    	ofs2 << header << '\n';
    
    	copy(begin(s1), end(s1), ostream_iterator<Rec>(ofs1, "\n"));
    	copy(begin(s2), end(s2), ostream_iterator<Rec>(ofs2, "\n"));
    }
    Have fun!
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  8. #23
    Join Date
    May 2015
    Posts
    500

    Re: help needed with the c++ program

    Sorry for the delay. But Just to let you know that my code was accepted as solution and thankyou very much for Kaud, for his patience and willingness to help. Much appreciated.
    This forum is the greatest help for me. (even during my previous projects)

    Final version of the code is attached.

    I failed in codility, as expected.
    Code:
    /*
     * sorting.h
     *
     *  Created on: 23 Mar 2019
     *      Author: pdk
     */
    
    #ifndef SORTING_H_
    #define SORTING_H_
    
    #include <iostream>
    
    #include <string>
    
    #include <vector>
    #include <set>
    #include <map>
    #include <fstream>
    #include <sstream>
    #include <iomanip>
    #include <conio.h>
    #include <cassert>
    
    using namespace std;
    
    const int year = 365;
    const int month= 30;
    const int week= 7;
    const int day =  1;
    
    
    std::map<string,int> myMap = {
    	    {"y", year},
    	    {"m", month},
    	    {"w", week},
    	    {"d", day}
    };
    
    
    // Class to hold the individual elements of the Timespan
    // m_Id: Holds the individual element before tokenising
    // m_Type Holds the type of element after tokenising
    // m_Num Holds the Number of elements after tokenising
    class Timespan{
    private:
    	string m_Id;
    	string m_Type;
    	int m_Num;
    public:
    	Timespan(string id, string intype, int innum) :m_Id(id), m_Type(intype),m_Num(innum){}
    
    	// Getter functions to get the Id, type and Number of elements
        inline string GetId() const
        {
        	return m_Id;
        }
    
    	inline string GetType() const
    	{
    		return m_Type;
    	}
    
    	int GetNum() const
    	{
    		return m_Num;
    	}
    
    };
    
    // Class to hold the individual elements of the Line
    // m_Id: Holds the individual line before tokenising, and also is overwitten with the sorted timespan
    // m_LineValue : Holds the total number days that represent this line
    // m_DataSet Holds the DataSet after tokenising the line
    // m_Value Holds the Value after tokenising line
    class Line
    {
    private:
        // Private Members
        string m_LineId;
        int m_LineValue;
        int m_DataSet;
        int m_Value;
    
    public:
        // Class Constructor
        Line(const string & input);
    
        // Getter Functions
        string GetLineId() const
        {
            return m_LineId;
        }
    
        int GetLineValue() const
        {
            return m_LineValue;
        }
    
        int GetDataSet() const
        {
            return m_DataSet;
        }
    
        int GetValue() const
        {
            return m_Value;
        }
    
        // Print Content of the Line Class
        void Print_Line()
        {
            cout << "Line - ID" << m_LineId << "  Value:"
                << m_LineValue << ", DataSet and Value - "
                <<  m_DataSet << "  " << m_Value << endl;
        }
    };
    
    // Binary Predicate to sort the Timespan class
    struct tscmp {
    	bool operator() (const Timespan & l, const Timespan & r)
    	{
    		string ltype = l.GetType();
    		string rtype = r.GetType();
    		if( myMap.at(ltype) > myMap.at(rtype) )
    			return false;
    		return true;
    	}
    };
    
    //Binary predicate to sort the line class
    struct comp {
    	bool operator() (const Line & l, const Line & r)
    	{
    		if (l.GetLineValue() > r.GetLineValue())
    			return false;
    		else if (l.GetLineValue() == r.GetLineValue())
    		{
    			if(l.GetDataSet()>r.GetValue())
    				return false;
    		}
    		return true;
    	}
    };
    
    #endif /* TEMP_H_ */
    
    
    //============================================================================
    // Name        : sorting.cpp
    // Author      : pdk
    // Version     :
    // Copyright   : Your copyright notice
    // Description : Teoco test in C++, Ansi-style
    //============================================================================
    
    #include "./sorting.h"
    
    
    Line::Line(const string & input)
    {
    	m_LineId = input;
    
    	std::vector<std::string> inputTokens;
    	std::set<Timespan, tscmp> ts;
    
    	stringstream is(input);
    	std::string r;
    	while(std::getline(is,r,','))
    	{
    		inputTokens.push_back(r);
    	}
    
    	// Check for error conditions
    	assert((inputTokens.size()==3) && "Invalid input. Please try again!");
    
    	std::string timespan = inputTokens[0];
    
    	std::string temp;
    	int num=0;
    	int total =0;
    	string tempstring = timespan;
    
    
    		while(!tempstring.empty())
    		{
    			std::string::size_type sz;   // alias of size_t
    
    		    try
    		    {
    		    	num = std::stoi(tempstring, &sz);
    			}
    			catch (...)
    			{
    				cout << "Invalid Timespan input. Please try again!\n";
    			}
    
    			string type = tempstring.substr(sz,1);
    
    			std::ostringstream ss;
    			ss << num << type;
    
    			if(myMap.find(type) == myMap.end())
    				cout << "Invalid Timespan input. Please try again!";
    			assert(myMap.find(type) != myMap.end());
    
    			Timespan elem( ss.str(), type, num);
    
    			ts.emplace(elem);
    
    			int num_days = myMap.at(type);
    			total = total+num*num_days;
    			tempstring = tempstring.substr(sz+1);
    		}
    
    		for(auto elem : ts)
    		{
    			int num_days = myMap.at(elem.GetType());
    			total = total + ((elem.GetNum() ) * (num_days));
    		}
    
    		std::ostringstream ss;
    		for(auto elem : ts)
    			ss << elem.GetId();
    
    		string coma = ",";
    
    		ss << coma << inputTokens[1] << coma << inputTokens[2];
    
    		m_LineValue = total;
    
    		m_LineId = ss.str();
    
        try
        {
    
    		m_DataSet = std::stoi(inputTokens[1]);
    		m_Value = std::stoi(inputTokens[2]);
    	}
    	catch (...)
    	{
    		cout << "Invalid DataSet/Value input. Please try again!\n";
    	}
    
    }
    
    int main()
    {
    	std::multiset<Line, comp> s1;
    
    	ifstream fin;
    
    	fin.open("C:\\Users\Pdk\\eclipse-workspace\\sorting\\src\\data.txt");
    
    	if(!fin.fail())
    	{
    		std::cout << "fin success";
    		std::string line;
    
    		// skip the header
    		std::getline(fin, line);
    
    		// Get each line
    		while (std::getline(fin, line))
    		{
    			// If line is not empty
                if(!line.empty())
                {
                	// Process the line, to tokenise and extract the parameters.
                	Line theline(line);
    
                	// Place the line object in the multiset as per the comparision done in the binary predicate function
    		        s1.emplace(theline);
                }
    		}
    	}
    
    	cout << " \nSorted output is  \n";
    	for( auto elem : s1)
    		cout << elem.GetLineId() << "\n";
    
    	return 0;
    }
    Last edited by pdk5; April 15th, 2019 at 03:45 AM.

Page 2 of 2 FirstFirst 12

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured