Mdjon26
Mdjon26

Reputation: 2255

How to make it so that my program accepts multiple words

I'm making a program that is a vector of lists. It's keeping track of a word, and what line number that word was found on.

example:

teddy bears are cute
so are you

so, it'll store teddy as line 1. bears as line 1. The only problem I'm coming across is when a word is repeated. it'll store are as line 1, but I want the program to also store are as line 2. I'm not sure how I can do this. Here's the code I have so far

class index_table
{

public:
    index_table() { table.resize(128);}
    vector <int> &find1(string &);

private:
    class entry
    {
        public:
        string word;
        vector <int> line;
    };

    vector< list <entry> > table;



};

void index_table :: insert( string & key, int value)
{
entry obj;
int c = key[0]; //vector for the table.
obj.word = key; //Storing word
obj.line.push_back(value); //Storing what line it was found on

table[c].push_back(obj); //Stores the word and line number.

}

How can I make it so that my program can store multiple words on different number lines? I will have to search through my table[c] for a word is the same? How can I do that correctly?

Upvotes: 0

Views: 119

Answers (1)

P0W
P0W

Reputation: 47814

This is not the solution for your problem instead, I'm answering your comment

"I've never used a map before so I'm not entirely sure how to implement it..."

#include<iostream>
#include<fstream>
#include<sstream>
#include<map>
#include<set>

int main()
{
    std::map< std::string, std::set<int> > word_count;

    std::ifstream input_file("input.txt");
    std::string single_line, single_word;
    int line_number = 0;

    while(std::getline(input_file, single_line))
    {
        ++line_number;
        std::stringstream word_reader(single_line);

        while(word_reader >> single_word)
        {
            word_count[single_word].insert(line_number);
        }
    }

    input_file.close();

    for(auto word:word_count)
    {
        std::cout << word.first << ":";

        for(auto line:word.second)
        {
            std::cout << line << " ";
        }

        std::cout << std::endl;
    }
}

The contents of Input.txt :

teddy bears are cute
so are you

Outputs :

are:1 2
bears:1
cute:1
so:2
teddy:1
you:2

Upvotes: 2

Related Questions