Hello all,
So I am teaching myself a little bit off C++, and I am trying to do an exercise in which it takes in a user's inputs of strings, and for every distinct string, state how many times it has occurred.
Example:
User Input: A B C A BOB
OUTPUT: A 2
B 1
C 1
BOB 1
So from what I've coded I have been able to put into a vector all the words that have occurred with no duplicates. I think my way of counting the words work, but the problem is how to increment my vector of int. I have looked at the functions that vectors have, and it doesn't seem like vectors have something for me to replace the element contained in it? With arrays, usually i would just do A[i] = A[i]++. It does not seem to work though with C++ when dealing with vectors...
Here is my code.
Thanks all!Code:#include <algorithm> #include <iomanip> #include <ios> #include <iostream> #include <string> #include <vector> #include <conio.h> using std::cin; using std::sort; using std::cout; using std::streamsize; using std::endl; using std::string; using std::setprecision; using std::vector; int main(){ // ask for set of words cout << "Enter all words, " "followed by end-of-file: "; vector<string> word_set; string x; // invariant: word_set contains all the words entered so far while (cin >> x) word_set.push_back(x); // check that the user entered some words typedef vector<string>::size_type vec_sz; vec_sz size = word_set.size(); if (size == 0) { cout << endl << "You must enter some words. " "Please try again." << endl; cout << "Press any key to continue... "; _getch(); return 1; } vector<string> words; vector<int> occurs; //adds new words to the the words vector for(int i = 0; i != word_set.size(); i++){ bool listed = false; for(int i2 = 0; i2 != words.size(); i2++){ if(words[i2] == word_set[i]){ listed = true; } } if(listed == false){ words.push_back(word_set[i]); } } //initializes occurs vectors with the same size as words //each element is set to 0 for(int i = 0; i != words.size(); i++){ occurs.push_back(0); } //records occurences of words for(int i = 0; i != words.size(); i++){ for(int i2 = 0; i2 != word_set.size(); i2++){ if(word_set[i2] == words[i]){ //PROBLEM HERE..... occurs[i] = occurs[i]++; } } } //writes out the words cout << "Your words for the dataset are: " << endl; for(int i = 0; i != words.size(); i++){ cout << words[i] << " " << occurs[i] << endl; } //for the purpose of not quitting out the cmd //due to my compiler cout << "Press any key to continue... "; _getch(); return 0; }