简体   繁体   中英

how to not print a chosen element/elements from a vector c++

I need to print out a dozen text files with words and there frequency(how many times the 'word' shows up) but its not meant to print out words that only appear once. How can I not print those words out. I want to know how to basically be able to do things with the value of the 2nd value of my vector.

#include <iostream>
#include <map>
#include <fstream>
#include <string>
#include<bits/stdc++.h>
#include <iterator>

using namespace std;

template <class KTy, class Ty>

void PrintMap(map<KTy, Ty> map)
{
    typedef typename  std::map<KTy, Ty>::iterator iterator;

    std::vector<std::pair<std::string,int>> vector( map.begin(), map.end() );

    std::sort( vector.begin(), vector.end(),
               []( const auto & lhs, const auto  rhs )
               { return lhs.second > rhs.second;} );

    for ( const auto & item : vector )
        if (item.second == 1)
            ::cout << item.first << ": " << item.second << std::endl;
}

int main(void)
{
    vector <string> File;
    File.push_back("data.txt");
    File.push_back("data_1.txt");
    File.push_back("data_2.txt");
    File.push_back("data_3.txt");
    File.push_back("data_4.txt");
    File.push_back("data_5.txt");
    File.push_back("data_6.txt");
    File.push_back("data_7.txt");
    File.push_back("data_8.txt");
    File.push_back("data_9.txt");

    map<string, unsigned int> wordsCount;

    for (int i=0; i < File.size(); i++)
    {
        ifstream fileStream(File[i]);

        if (fileStream.is_open())
            while (fileStream.good())
            {
                string word;
                fileStream >> word;

                if (wordsCount.find(word) == wordsCount.end())
                    wordsCount[word] = 1;
                else
                    wordsCount[word]++;
            }
            else
            {
                cerr << "ERROR." << endl;
                return EXIT_FAILURE;
            }
    }
    PrintMap(wordsCount);
    return EXIT_SUCCESS;
}

If you don't want to print words that occur only once, change:

if (item.second == 1) 

to:

if (item.second != 1) 

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