简体   繁体   English

为什么我的ifstream程序以错误的顺序读取单词?

[英]Why is my ifstream program reading in words in the wrong order?

I employed a map to keep count of how many times each unique word appears in the .txt file... Its working and its reading in from the file, but the output is in the wrong order. 我使用了一个映射来统计每个唯一单词出现在.txt文件中的次数...它的工作原理和从文件中的读取结果,但是输出顺序错误。

#include <map>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

typedef map<string, int> StrIntMap;

void CountWords(ifstream& myStream, StrIntMap& wordMap)
{
int wCount = 0;
string word;

while (!myStream.eof())
{
    if(myStream >> word)
    {
        wCount++;
        ++wordMap[word];
    }
    else
    {
        cout << "Not Open" << endl;
    }
}

for (StrIntMap::iterator i = wordMap.begin(); i != wordMap.end(); ++i)
{
    cout << i->first << " || " << i->second << endl;
}

cout << "Number of Words: " << wCount << endl;
}

The main file opens the ifstream and calls CountWords. 主文件打开ifstream并调用CountWords。

The file is being read in order. 正在按顺序读取文件。 The map does not store elements by the order inserted, but by a binary tree that sorts them for log(n) retrieval. 该映射不按插入顺序存储元素,而是按对它们进行排序以进行log(n)检索的二叉树存储。

To read unique words back in order, the easiest way would to be to either add a separate vector where you only insert unique words not yet in the map, or store the position as part of the struct when you insert into the map, then output them by order of position. 要按顺序读回唯一单词,最简单的方法是添加单独的矢量,在其中仅插入地图中尚未插入的唯一单词,或者在插入地图时将位置存储为结构的一部分,然后输出按位置顺序排列。

To read all words (unique or non unique) back in order, forget the map and just insert and call from a vector. 要按顺序读取所有单词(唯一或非唯一),请忘记地图,只需从向量插入并调用即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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