简体   繁体   中英

C++ Reading from text file data type as struct using getline

I have a text file in form:

a 1 b 6 e 4 h 2
r 5 q 1 a 2 e 2 b 3

up to 300k line. every char follows with its value. I want to read this file line by line, and do pair between each 2 chars in the same line. the results of first line:

(a,b)
(a,e)
(a,h)
(b,e)
(b,h)
(e,h) 

I also, count the frequency for each pair. The code for that:

    using namespace std;

    std::map<std::pair< char, int>, int>  CharP;

    struct Mydata
    {
        char myString;
        float value;


         friend std::istream &operator>>(std::istream &is, Mydata  &d) {
        {
                    string line;
            std::getline(is,line);
            return is >> d.myString>> d.value;

        }
    };


    int main()
    {
        std::ifstream in("Data.txt");



            std::vector<Mydata> data{ std::istream_iterator<Mydata>(in), std::istream_iterator<Mydata>() };

            for (std::vector<Mydata> ::iterator current = data.begin(); current != data.end(); ++current)
            {
                char a = current->myString;
                for (std::vector<Mydata> ::iterator current2 = ++current; current2 != data.end(); ++current2)
                {
                    char b = current2->myString;

                    auto itt = CharP.find(std::make_pair(b, a));

                    ++CharP[(itt != CharP.end()) ? std::make_pair(b, a) : std::make_pair(a, b)];

                } 
--current;

            }





        cout << " \nPress any key to continue\n";
        system("PAUSE");
        return 0;
    }

I got this error: binary '>>' : no operator found which takes a right-hand operand of type 'Mydata' (or there is no acceptable conversion).

I have another concern, since I have large file, I'm wondering if there is another method faster than the attached code.

Without having looked at the rest of the code I think I can safely say this is the problem:

 friend std::istream& getline(std::istream &is, Mydata &d) 

Were you intending on overloading the extractor in this declaration? If so, you should know that the extractor is an operator , namely operator>>() . Replace the getline with >> :

 friend std::istream& operator>>(std::istream &is, Mydata &d); 

Also, the following is very unreadable:

 ++CharP[(itt != CharP.end()) ? std::make_pair(b, a) : std::make_pair(a, b)]; 

replace it with this:

  if (itt != CharP.end()) { auto p = std::make_pair(b, a); ++CharP[p]; } else { auto p = std::make_pair(a, b); ++CharP[p]; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM