In my C++ code, I acquire a user-defined number of input strings. Next the user enters a user-defined number of query strings. For each query string, I want to output the number of its instances, in the collection of strings originally input by the user.
Here is my code:
#include<iostream>
#include<vector>
#include<string>
#include<conio.h>
using namespace std;
int main(int argc, char ** argv) {
int N, Q;
cout << "Enter number of strings : ";
cin >> N;
vector <string> strInp(N);
string sbuf;
// Storing the strings in the vector
cout << "Enter the strings:" << endl;
for (int i = 0; i < N; i++) {
cin >> sbuf;
strInp.push_back(sbuf);
}
// Storing the queries
cout << "Enter the number of queries : ";
cin >> Q;
vector <string> query(Q);
string qbuf;
cout<<" Enter the query strings"<< endl;
for (int i = 0; i < Q; i++) {
cin >> qbuf;
query.push_back(qbuf);
}
// Counting the instances of the query strings
// Initializing the instances vector
vector <int> instances;
string s1, s2;
int flag = 0;
vector <string> ::iterator start1 = query.begin();
vector <string> ::iterator end1 = query.end();
vector <string> ::iterator start2 = strInp.begin();
vector <string> ::iterator end2 = strInp.end();
for (auto i = start1; i < end1; i++) {
int count = 0;
s1 = *i;
for (auto j = start2; j < end2; j++) {
s2 = *j;
if (s1 == s2) {
count++;
}
}
instances.push_back(count);
}
cout << "The number of instances of each query are : " << endl;
for (unsigned int i = 0; i < instances.size(); i++) {
cout << instances[i] << endl;
}
return 0;
_getch();
}
On running the code, I have the following output
Enter the number of inputs : 5
Enter the strings:
apple
apple
apple
ball
cat
Enter the number of queries: 3
Enter the query strings:
apple
ball
cat
The number of instances of each query are :
5
5
5
3
1
1
The expected output is actually :
The number of instances of each query are :
3
1
1
I would really appreciate it if someone can point out what I am doing wrong?
Thank You
When you are creating a std::vector with the constructor that takes a count, then you already fill in that amount of elements.
So for your example that means strInp is {"","","","","","apple","apple","apple","ball","cat"}
and query is {"","","","apple","ball","cat"}
So you need to either write to those elements or create an empty vector and use push_back.
So it's
vector <string> strInp(N); and vector <string> query(Q);
with
strInp[i]=sbuf; and query[i]=qbuf;
or it's
vector <string> strInp; and vector <string> query;
with
strInp.push_back(sbuf); and query.push_back(qbuf);
Related
I have an array and I want to subtract each of the elements consecutively, ex: {1,2,3,4,5}, and it will result to -13 which is by 1-2-3-4-5.
But I don't declare or make those numbers fixed as they're taken from the input (user). I only make it like, int array[100] to declare the size.
Then, to get the inputs, I use the for loop and insert them to the array. Let's say first input is 10, then array[0] must be 10 and so on.
The problem is, how do I subtract them? I have two options:
The first element of the array (array[0]) will subtract the next element (array[1]) right after the user input the second element, and the result (let's say it's int x) will subtract the next element (array[2]) after the user input it and so on.
I'll have the user input all the numbers first, then subtract them one by one automatically using a loop (or any idea?) *These elements thing refer to the numbers the user input.
Question: How do you solve this problem?
(This program will let the user input for as much as they want until they type count. Frankly speaking, yeah I know it's quite absurd to see one typing words in the middle of inputting numbers, but in this case, just how can you do it?)
Thanks.
Let's see my code below of how I insert the user input into the array.
string input[100];
int arrayInput[100];
int x = 0;
for (int i = 0; i >= 0; i++) //which this will run until the user input 'count'
{
cout << "Number " << i+1 << ": ";
cin >> input[i];
arrayInput[i] = atoi(input[i].c_str());
...
//code to subtract them, and final answer will be in int x
...
if (input[i] == "count")
{
cout << "Result: " << x << endl;
}
}
You can/should use a dynamic sized container like std::vector as shown below:
#include <iostream>
#include <vector>
int main()
{
int n = 0;
//ask user how many input he/she wants to give
std::cout << "How many elements do you want to enter: ";
std::cin >> n;
std::vector<int> vec(n); //create a vector of size n
int resultOfSubtraction = 0;
//take input from user
for(int i = 0 ; i < n ; ++i)
{
std::cin >> vec.at(i);
if(i != 0)
{
resultOfSubtraction-= vec.at(i);
}
else
{
resultOfSubtraction = vec.at(i);
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}
Execute the program here.
If you want a string to end the loop then you can use:
#include <iostream>
#include <vector>
#include <sstream>
int main()
{
std::vector<int> vec;
int resultOfSubtraction = 0, i = 0;
std::string endLoopString = "count";
std::string inputString;
int number = 0;
//take input from user
while((std::getline(std::cin, inputString)) && (inputString!=endLoopString))
{
std::istringstream ss(inputString);
if(ss >> number)
{
vec.push_back(number);
if(i == 0)
{
resultOfSubtraction = number;
}
else
{
resultOfSubtraction-= number;
}
++i;
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}
I am able to count the number of characters in my string using length() function.
But i want to calculate the number of different characters in my string.
i.e. say string is "Hello world"
So here number of different strings are H,e,l,o, ,w,r,d.
so 8 different characters.
The best way to do is a method called frequency checking. Basically create a vector of size 128. Go through the string and for every character, increment the frequency that matches its ASCII value. Finally, iterate over the freq vector and count how many non zero entries you have. Code should look like this:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
string s = "Hello World";
vector<int>freq(128);
for(int i = 0; i < s.length(); i++)
freq[s[i]]++;
int counter = 0;
for(int i = 0; i < 128; i++)
if(freq[i] > 0)
counter++;
cout << counter << "\n";
}
Vector of size 128 works fine because ASCII codes only go from 0 to 127.
Another way is to initialize a std::set and insert every character of the string into that one at a time. Finally, output the size of the set. This works because set doesn't allow duplicate entries. The code for this looks like:
#include<iostream>
#include<set>
#include<string>
using namespace std;
int main()
{
string s = "Hello World";
set<char>x;
for(int i = 0; i < s.length(); i++)
x.insert(s[i]);
cout << x.size() << "\n";
}
To count the number of unique characters, you can use sd::sort followed by std::unique. It will reshuffle the contents and return an iterator to the last unique character in your string. Subtract begin() and you have the result.
I think that an unordered_map is the best way to achieve that.
Here is the code if you want the total number of char in a string, grouped by unique chars.
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
string s="test string";
unordered_map<char,int> map;
for (const char &c: s) { //for each char in string
map[c]++;
}
for (auto &e: map) //for each unique char in map
cout<<"char: "<<e.first<<" number: "<<e.second<<endl;
return 0;
}
Output
char: n number: 1
char: e number: 1
char: i number: 1
char: t number: 3
char: s number: 2
char: number: 1
char: g number: 1
char: r number: 1
But if you want only the total number of unique chars
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
string s="test string";
unordered_map<char,int> map;
for (const char &c: s) {
map[c]++;
}
int count =0;
for (auto &e: map)
count++;
cout<<"Unique chars: "<<count<<endl;
}
Output
Unique chars: 8
Well you can write your own functions to deal with that like this
#include <iostream>
using namespace std;
string uniqueChars(string str) {
string newStr = "";
bool arr[128];
for(int i = 0;i < 128; i++) {
arr[i] = false;
}
char c;
for(int i = 0, n = str.length();i < n; i++) {
c = str[i];
if(c < 0 || c > 127) {
continue;
}
if(!arr[c]) {
arr[c] = true;
newStr += c;
}
}
return newStr;
}
int main(void) {
string a = "Hello It's a wonderful world";
string b = uniqueChars(a);
cout << a << " => " << a.length() << "\n" <<
b << " => " << b.length();
return 0;
}
Output:
Hello It's a wonderful world => 28
Helo It'sawndrfu => 16
My question is pretty specific, I think. My program is supposed to store 10 names, and their corresponding phone numbers into an array. I want to sort the names/numbers by phone numbers, ascending order, and then output the array in the sorted order. Thanks for the help! Any and all help is appreciated.
What I have so far:
using namespace std;
main()
{
string name[10][2];
int x;
cout << "Please input 10 names";
for(int i = 0; i < 10; i++){
cin >> name[i][x];
}
int i = 0;
cout << "Please input their corresponding numbers";
for(x = 0; x < 10; x++){
cin >> name[i][x];
}
}
EDIT: Would it be possible(not as hassling) to instead do this but with a parallel array storing a string(name) and an int(number) and sort it by the int?(Of course, while keeping the names by their corresponding number) If so, how could I change it from a two-dimensional to a parallel array?(Or just pointing me in the right direction would be greatly appreciated) :)
You will want to use a vector of pairs. This is in this case more convenient than a map because you want to sort by value rather than by key. There are also methods to sort a map by value (see question Sorting std::map using value), but for this purpose a vector of pairs seems appropriate.
If you want to have a constant memory array instead of a dynamic memory array (std::vector) then use std::array<std::pair<std::string,int>, N>, where N is the number of elements.
Needs C++14 because of the template lambda.
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
int main()
{
std::vector<std::pair<std::string,int>> phonebook;
phonebook.reserve(10);
std::cout << "Please input a name and a number\n";
for (int i = 0; i < 10; ++i) {
std::cout << "Name: ";
std::string name;
std::cin >> name;
std::cout << "Number: ";
int number;
std::cin >> number;
phonebook.push_back({name, number});
}
std::sort( std::begin(phonebook),
std::end(phonebook),
[] (auto a, auto b) { return a.second < b.second; });
for (auto const& entry : phonebook)
{
std::cout << entry.first << ' ' << entry.second << '\n';
}
}
I'm trying to write a map that takes in an integer as the key and then an x amount of int values that are given to it via standard input. This is my first time working with maps so I'm running into several issues and was wondering if someone could help understand better what I am doing incorrectly. Normally with a vector/array the following would work fine:
int standardInput;
for (int i = 1; i<=n; i++){
cin standardInput;
array[i] = standardInput;
}
I can't get that to work similarly when using a map:
int numberToCompare = 4;
map<int numberToCompare, int>myMap;
int standardInput;
cout << "Enter numbers: " << endl;
for (int i = 1; i <= n; i++){
cin standardInput;
myMap.insert(standardInput);
}
I'm still trying to understand about the key and values. The way I understood when reading about maps was that with a map the key is unique unlike multi maps. What I don't know how to do is allow user input to fill the rest of the map. I saw lots of examples online where inside the code people manually entered all of the input doing the following (this goes against what I want to accomplish).
portMap_.insert(pair<string,int>("fourth", 4444));
portMap_.insert(pair<string,int>("fifth", 5555));
EDIT: To clarify in case I caused some confusion, I'm trying to fill a map with numbers that are given via standard input.
I would recommend you browse the documentation for std::map found here. Then take a look at the examples provided in the insert() method documentation here.
The declare a map object, you need to specify the type for the key and the type for the value by providing the type name as template parameters:
#include <map>
using namespace std;
map<int,int> myMap;
If you then want to insert a key/value pair:
int myKey = 10;
int myVal = 100;
myMap.insert(pair<int,int>(myKey, myVal));
The above can be made a bit more terse with some typedefs:
typedef map<int,int> IntMap;
typedef pair<int,int> IntPair;
IntMap myMap;
myMap.insert(IntPair(10, 100));
If you want the key/value pairs to be provided by user input, just write a simple loop that accepts the values from standard input and insert the values into your map.
There are plenty of resources here for reading values from standard input. Something like the below would do the trick:
// pseudo-code
while (did the user quit?)
{
int key = 0;
int value = 0;
cin >> key >> value;
// maybe if the user enters -1, then you quit, otherwise:
myMap.insert(pair<int,int>(key, value));
}
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
scanf("%d", &n);
map<int, string> m;
for(int i = 1; i <= n; i++) {
string s = "abracadabra";
m.insert(pair<int, string>(i, s));
}
for(auto it = m.begin(); it != m.end(); it++) {
cout << it->first << " " << it->second <<"\n";
}
}
This works fine.
Problem:write a map that takes in an integer as the key and then an x amount of int values that are given to it via standard input
Solution Here i provided the code which will take the std input and store it to the MAP,
enter code here
`#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
#include <string>
using namespace std;
int main()
{
int n;
int key;
long x;
cin >> n;//std input for number of entries in to MAP
map <int, long> map_book;
for (int i = 0; i < n; i++) {
cin >> x;//std input for VALUE
cin >> key;//std input for KEY
map_book[key] = x;
}
//here am searching the x and pinting if it is there in MAP or Else priniting it is not found
while(cin >> x) {
if (map_book.find(x) != map_book.end()) {
cout << x << "=" << map_book.find(x)->second << endl;
} else {
cout << "Not found" << endl;
}
}
return 0;
}`
This can be helpful.
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<char,int>mp;
char a;
int b,n;
cin>>n;
for(int i = 0; i<n; i++){
cin>>a>>b;
mp.insert(pair<char,int>(a,b));
}
cout<<endl;
for(auto&x:mp)
{
cout<<x.first<<" "<<x.second<<endl;
}
return 0;
}
output:
3
a 1
b 2
c 3
a 1
b 2
c 3
#include <iostream>
#include <map>
int main ()
{
std::map<char,int> first;
first['x']=8;
first['y']=16;
first['z']=32;
for(map<char,int>::iterator it = first.begin(); it != first.end(); ++it) {
cout << it->first <<" "<< it->second<<endl;
}
return 0;
}
I'm new to C++ and I need some help creating this program:
I need to ask for the size of the list, then take the list containing integers and then ask the size of the second list and take those integers.
So far I have this:
#include <iostream>
using namespace std;
int main()
{
long int ARR[10];
int i,n;
printf("List 1 size: ");
scanf("%d",&n);
printf("List 1 data: ");
for(i=0;i<n;i++)
{
scanf("%ld",&ARR[i]);
}
So that will take the input for the first list. Now I will repeat this for the second list.
But the key point is I now need to compare the two lists. If list1 is in list2 then I say yay, or if not then nay.
How do I go about comparing these two lists? And I am I on the right track with the input?
Thanks,
EmptyPeace
I think that's what you expected.
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
using namespace std;
bool mypredicate (int i, int j) {
return (i==j);
}
int main(){
int size_list = 0;
vector<int> list1, list2;
cin >> size_list;
list1.resize(size_list);
list2.resize(size_list);
cout << list1.size() << endl;
for (int i = 0; i < size_list; i++)
cin >> list1[i];
for (int i = 0; i < size_list; i++)
cin >> list2[i];
pair<vector<int>::iterator,vector<int>::iterator> mypair;
mypair = mismatch (list1.begin(), list1.end(), list2.begin(), mypredicate);
if( mypair.first == list1.end() && mypair.second == list2.end() )
cout << "are equals" << endl;
else{
cout << "aren't " << endl;
cout << *mypair.first << ", " << *mypair.second << endl;
}
system("pause");
return 0;
}
I think you should use either dynamic array or stl's vector to store data.
for example, dyn. array:
int size;
scanf("%d", size);
int *tab = new int[size];
...
delete[] tab;
or vector way:
#include <vector>
...
int size;
scanf("%d", size);
vector <int> tab(size);
// to insert an element, use tab.push_back( number );
// and getting an element goes array-way, for example tab[0];
And some words from me- if you are writing in c++, use cin and cout for input/output, unless you need extra speed or specific format. And remember, that list is something different than array/vector.