Marzdor
Marzdor

Reputation: 79

Issue reading data into a map

I can't figure out why my pull_data function crashes when it is call I narrowed it down to the "myMap[word]++" lines. However if I understand it correctly it should work. Like if the element with key "word" doesn't exist, the element will be created and value initialized.

My first variation would pull 2 different files and save the data to the 2 different maps with this.

if (file.is_open()) {
        while (file >> word) {
            myMap[word]++;
        }
        file.close();
    }
    else {
        cout << "Unable to open file.";
    }

But instead of pulling from 2 different files I am trying to make it read one that has all the data I need separated with a | to indicate if i am reading from the on side or the off side.

#include <iostream>
#include <fstream>
#include <map>
#include <string>

using namespace std;

void pull_data(map<string, float>& myMap1, map<string, float>& myMap2);
void push_data(map<string, float> myMap1, map<string, float> myMap2);
void sync_data(map<string, float>& myMap1, map<string, float>& myMap2);

int main()
{
    map<string, float> offData;
    map<string, float> onData;

    pull_data(offData, onData);

    sync_data(offData, onData);

    push_data(offData, onData);

    system ("PAUSE");

    return 0;
}

void pull_data(map<string, float>& myMap1, map<string, float>& myMap2) {

    string word;
    bool onOff = false;
    ifstream file("Data.txt");

    if (file.is_open()) {
        while (file >> word) {

            if(word == "|" && onOff){
                onOff = false;
            }else if(word == "|"){
                onOff = true;
            }

            if(onOff){
                myMap2[word]++;
            }else{
                myMap1[word]++;
            }

        }
        file.close();
    }
    else {
        cout << "Unable to open file.";
    }
}

void push_data(map<string, float> myMap1, map<string, float> myMap2){}

void sync_data(map<string, float>& myMap1, map<string, float>& myMap2){}

Data.txt example

362 364 |   112 304 122 124 |
364 304 901 116 |   351 303 112 |
362 364 311 |   351 612 400 484 303 326 |

Upvotes: 2

Views: 54

Answers (1)

Jorge Omar Medra
Jorge Omar Medra

Reputation: 988

It is because you are using a mapped data type that doesn't meet the requirements to be CopyConstructible and DefaultConstructible, float is a primitive data type.

That is the reason that you have a Zero reference and it crashed when you are use the operator "++".

Check it:

http://en.cppreference.com/w/cpp/container/map/operator_at

http://en.cppreference.com/w/cpp/concept/CopyConstructible

Upvotes: 2

Related Questions