dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 23

Thread: help needed with the c++ program

  1. #1
    Join Date
    May 2015
    Posts
    141

    help needed with the c++ program

    I have a file with the period, value1 and value2.

    Now want to write a program to read them and sort them based
    - period, then value1 , and then value2
    - value1, period and value2

    Any ideas for this (using the boost)

    period, value1 , value2, 8m, 15, 30, 2y6m1w2d,10,120, 2d4m, 10, 20, 1d5m, 11, 120
    Last edited by pdk5; March 15th, 2019 at 07:41 AM.

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,696

    Re: help needed with the c++ program

    Sorry can't advise re boost.

    However, reading each structure of period, value1, value2 from a file is quite straightforward. How many values of this structure are there? The simple way to produce the sorted output is to have a set for each sort criteria and define the operator< as required for each of these sets so that the set insertion keeps them in the required sorted order. A simple iteration of the set then gives the data in the required sort order.

    The slightly tricky issue is to convert the text period into a value. What would be the smallest period specified - second, milli-second? What are you considering as a month - 30 days? and for a year - 365 days?

    If you attach a small sample text file of a few lines, I'll be able to knock up some sample code.
    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++17 Compiler: Microsoft VS2019 (16.1.3)

  3. #3
    Join Date
    May 2015
    Posts
    141

    Re: help needed with the c++ program

    Thankyou very much Kaud for reply and hints. very helpful

    smallest period is day. and i guess, we can assume
    month 30 days. year - 365 days.

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,696

    Re: help needed with the c++ program

    so

    2d4m

    means 4 months 2 days - and not 2 days 4 minutes?

    So you have
    y - years
    m - months
    w - weeks
    d - days


    OK. If you attach a sample file I'll knock up some sample code.
    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++17 Compiler: Microsoft VS2019 (16.1.3)

  5. #5
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,696

    Re: help needed with the c++ program

    re your PM. I take it that this program is homework? if so, we don't provide programs for homework but will be able to offer guidance and advice on any code provided.

    PS re the time span. I would be looking to first parse this into a struct for year, month, week, day (which means you can output in the form ymwd as required) then convert this into a value of days and then sort on this value. It's not that difficult.

    Cheers!
    Last edited by 2kaud; March 15th, 2019 at 09:38 AM.
    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++17 Compiler: Microsoft VS2019 (16.1.3)

  6. #6
    Join Date
    May 2015
    Posts
    141

    Re: help needed with the c++ program

    period, value1 and value2. is changed to period, parameter, value
    Attached Files Attached Files

  7. #7
    Join Date
    May 2015
    Posts
    141

    Re: help needed with the c++ program

    It is not homework, i come from c background . Moved to c++. But not worked on algorithms. Basically used more from c perspective.

    Now into kind of systems engg role. Not much coding,

    Want to get back to c++, but into different domain. So practicing..I need to write codility test soon

  8. #8
    Join Date
    May 2015
    Posts
    141

    Re: help needed with the c++ program

    @tubular, laserlight , could you help me please.
    You have helped me in issues when i was working on c++ projects

  9. #9
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,696

    Re: help needed with the c++ program

    Re your PM. This is an interview question - so the general guidance is as for homework. Post your code first and then we'll provide advice and guidance.

    I've coded up a quick working solution. But for you to get the best benefit, try it yourself first. If you're really stuck, then ask and I'll post my solution but really you'll get more benefit from first trying yourself.

    Cheers!
    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++17 Compiler: Microsoft VS2019 (16.1.3)

  10. #10
    Join Date
    Feb 2017
    Posts
    434

    Re: help needed with the c++ program

    Quote Originally Posted by pdk5 View Post
    i come from c background . Moved to c++. But not worked on algorithms. Basically used more from c perspective.
    If you figure you can come up with a working solution in C then I suggest you do that. Then you can come back here and show what you did and ask how people would do it in C++. Could be an interesting discussion.

    Note that even though C is part of C++ there's a huge step from C to C++. It's not a question on putting in a few hours, we're rather talking years.

  11. #11
    Join Date
    May 2015
    Posts
    141

    Re: help needed with the c++ program

    Hi Kaud and Wolle. Thankyou for your suggestions. To tell the story, I come from electronics background, started basic c coding on early days of mobile tech. Moved to nw side, started to cut paste c++ code. But i worked in a very small company ( just 4ppl). There was no time for study, but just directly jump to c++ and there are not proper tools to test. But Now i am in a entirely different kind of area, where its just req gathering. So I have forgotten my coding skills. But in the nw side company, ppl where writting huge amounts of code, with no single comment, no document of any sort. That made me learn a lot, but in hard way. But i am used to now seeing lots of code. As in that company people were writting huge code, except me .
    I have been busy work as i need to travel a lot for my new work, and it was busy last few weeks. I have not been able to start my code.

    But finally today got some time to kick start. I have come up with the base code: Hopefully i should soon be trying to add more into it.
    Code:
    typedef std::multimap<int, int> MyValuePair;
    typedef std::multimap<int, MyValuePair> MyFinalStore;
    
    MyFinalStore mySortedStore;
    
    int main() {
    
    	std::string timespan = "3y1m1w1d";
        std::string temp;
        int num;
    
        int total =0;
    
    
    	std::size_t  pos = timespan.find("y", 0);
    
    	if (pos != std::string::npos)
    	{
    		temp = timespan.substr(0, pos);
    	}
    
    	timespan.erase(0, pos + 1);
    
    
    	if (temp.size() != 0) {
    	    num =std::atoi(temp.c_str());
    	}
    
    	cout << num;
    
    	total = total + num*365;
    
    	cout << "\n" << total;
    
    	cout << "\n" << timespan;
    
    
    	pos = timespan.find("m", 0);
    
    	if (pos != std::string::npos)
    	{
    		temp = timespan.substr(0, pos);
    	}
    
    	timespan.erase(0, pos + 1);
    
    
    	if (temp.size() != 0) {
    	    num =std::atoi(temp.c_str());
    	}
    
    	cout << num*30;
    
    	total = total + num*30;
    
    	cout << "\n" << total;
    
        cout << "\n Timespan is : " << timespan;
    
    	pos = timespan.find("w", 0);
    
    	if (pos != std::string::npos)
    	{
    		temp = timespan.substr(0, pos);
    	}
    
    	timespan.erase(0, pos + 1);
    
    
    	if (temp.size() != 0) {
    	    num =std::atoi(temp.c_str());
    	}
    
    	cout << num*7;
    
    	total = total + num*7;
    
    	cout << "\n" << total;
    
        cout << "\n Timespan is : " << timespan;
    
    	pos = timespan.find("d", 0);
    
    	if (pos != std::string::npos)
    	{
    		temp = timespan.substr(0, pos);
    	}
    
    	timespan.erase(0, pos + 1);
    
    
    	if (temp.size() != 0) {
    	    num =std::atoi(temp.c_str());
    	}
    
    	cout << num;
    
    	total = total + num;
    
    	cout << "\n" << total;
    
        cout << "\n Timespan is : " << timespan;
    
    
        MyValuePair tempValuePair;
    
        tempValuePair.insert (std::make_pair(0,0));
    
        mySortedStore.insert(std::make_pair(total, tempValuePair));

  12. #12
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,696

    Re: help needed with the c++ program

    This code is flawed as it assumes that the ordering is ymwd - which from the original question (and test data) from the PM can't be assumed. In any case, there is a much 'simpler' way of doing this using string streams. Also, you should generalise this. The code for each type is almost the same - except for the char to find and the multiplication factor. My whole code for this part is about 10 lines - including variable definitions.

    Also a couple of points. If you use .emplace() rather than .insert() then you don't need to use make_pair().

    Instead of typedef, the preferred c++way is using.

    Code:
    using MyValuePair =  std::multimap<int, int>;
    using MyFinalStore = std::multimap<int, MyValuePair>;
    Code:
    num =std::atoi(temp.c_str());
    would become
    Code:
    num = stoi(temp);
    I suggest you have another think. If you really want to see my code, I'll post it if you ask.
    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++17 Compiler: Microsoft VS2019 (16.1.3)

  13. #13
    Join Date
    May 2015
    Posts
    141

    Re: help needed with the c++ program

    Thankyou very much Kaud. Your clues helped me a lot (as always). I have some more time to finish this exercise. So I will try best from my side and finally. I can check with yours.

    It took sometime to kick start, now i setup my eclipse and finally ready dig further.

  14. #14
    Join Date
    May 2015
    Posts
    141

    Re: help needed with the c++ program

    Some more updates.
    @kaud : I have updated as per your comments. Thankyou

    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 <fstream>
    #include <iomanip>
    
    using namespace std;
    
    #define YEAR_NUM_DAYS 365
    #define MONTH_NUM_DAYS 30
    #define WEEK_NUM_DAYS 7
    #define DAY_NUM_DAYS  1
    
    static std::map<string,int> myMap = {
    	    {"y", YEAR_NUM_DAYS},
    	    {"m", MONTH_NUM_DAYS},
    	    {"w", WEEK_NUM_DAYS},
    	    {"d", DAY_NUM_DAYS}
    };
    
    
    using MyValuePair = std::multimap<int, int>;
    using MyKeyPair = std::multimap<string, MyValuePair>;
    using MyFinalStore = std::multimap<int, MyKeyPair>;
    
    MyFinalStore mySortedStore;
    
    vector<string> split(string data, string token)
    {
        vector<string> output;
        size_t pos = string::npos; // size_t to avoid improbable overflow
        do
        {
            pos = data.find(token);
            output.push_back(data.substr(0, pos));
            if (string::npos != pos)
                data = data.substr(pos + token.size());
        } while (string::npos != pos);
        return output;
    }
    
    
    void processline(std::string input)
    {
    	std::vector<std::string> inputaftertokenising;
    	std::vector<std::string>::iterator it;
    
    	inputaftertokenising= split(input, ",");
    
    	std::string timespan = inputaftertokenising[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);
    
    	}
    
    	MyValuePair tempValuePair;
    
    	int value1 = std::stoi(inputaftertokenising[1]);
    	int value2 = std::stoi(inputaftertokenising[2]);
    
    	tempValuePair.emplace (value1, value2);
    
    	MyKeyPair tempkeyPair;
    
    	tempkeyPair.emplace (timespan, tempValuePair);
    
    	mySortedStore.emplace(total, tempkeyPair);
    }
    
    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);
    		}
    
    
    		std::cout << " \n Sorted Input is : \n";
    
    		for (auto itr = mySortedStore.begin(); itr != mySortedStore.end(); itr++)
    		{
    			MyKeyPair keyMap = itr->second;
    
    			for ( auto keyitr = keyMap.begin(); keyitr != keyMap.end(); keyitr++)
    			{
    				cout << keyitr->first;
    
    				MyValuePair valueMap = keyitr->second;
    
    				for ( auto valitr = valueMap.begin(); valitr != valueMap.end(); valitr++)
    				{
    				cout <<" " << valitr->first << " " << valitr->second;
    				}
    			}
    
    			std::cout << "\n";
    		}
    	}
    	else
    	{
    		std::cout << "fin failed";
    	}
    
    
    }
    Last edited by pdk5; March 17th, 2019 at 08:03 AM.

  15. #15
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,696

    Re: help needed with the c++ program

    Some further comments

    Whilst using #define is common in c programs, in c++ programs good practice is to use const int (or const unsigned etc etc). Note that in c++, unlike in c, an array bound can be specified using a const int var

    Why has myMap been defined as static?

    When passing types to functions that aren't simple type, it is usual to pass by const ref /ref rather than by value (unless a copy is needed). This avoids the need for a copy which is what happens if passed by value.

    Your data structures seem overly complicated for the requirement - myFinalStore is a map of a map of a map! ??

    As I mentioned in post #12, parsing the input is much simpler if you use string streams. Your input parsing is much more complicated than it needs. This code also only sorts by timespan. How are you going to also sort by value1? How are you going to output a timespan in order (eg 1d3m should be output as 3m1d but this code outputs as 1d3m)?

    This code is very c++98'sh. I strongly suggest you get up to speed on c++17 which is probably a requirement for any c++ job now.

    For example:

    Code:
    for (auto itr = mySortedStore.begin(); itr != mySortedStore.end(); itr++)
    {
    	MyKeyPair keyMap = itr->second;
    	for ( auto keyitr = keyMap.begin(); keyitr != keyMap.end(); keyitr++)
    	{
    		cout << keyitr->first;
    
    		MyValuePair valueMap = keyitr->second;
    
    		for ( auto valitr = valueMap.begin(); valitr != valueMap.end(); valitr++)
    		{
    			cout <<" " << valitr->first << " " << valitr->second;
    		}
    	}
    
    	std::cout << "\n";
    }
    consider the same as c++17 code:

    Code:
    for (const auto& [key1, keyMap1] : mySortedStore) {
    	for (const auto& [key2, keyMap2] : keyMap1) {
    		cout << key2;
    		for (const auto& [val1, val2] : keyMap2)
    			cout << ' ' << val1 << ' ' << val2;
    	}
    	cout << '\n';
    }
    with key1, key2 etc replaced by meaningful variable names.
    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++17 Compiler: Microsoft VS2019 (16.1.3)

Page 1 of 2 12 LastLast

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
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)