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;
}
Related
I'm currently stuck on a C++ problem that asks me to sort five inputted integers from least to greatest. I've tried using if statements to do this, but it just seems way too inefficient to list out all the possible combinations. I've also experimented with the min and max functions, but these only work on the smallest and largest two integers. What is the fastest way to sort them?
#include <iostream>
using namespace std;
int main() {
cout << "Enter five integers. \n\n>";
int a, b, c, d, e;
cin >> a >> b >> c >> d >> e;
int first = min({a, b, c, d, e});
int fifth = max({a, b, c, d, e});
cout << first << fifth << "\n"; //This is where I want to output the middle three integers in order
cout << "\n";
return 0;
}
Here's my code so far. ^
The standard library has a function called std::sort, which works on any range. You can either put the numbers in an array, or you can put them in some other contain (like std::vector). In this case, arrays are simple enough given the five-item restriction. For example:
#include <iostream>
#include <algorithm>
#include <array>
#include <iterator>
int main() {
std::array<int, 5> numbers;
std::cout << "Enter five integers. \n\n>";
// Read numbers into array.
for (auto & i : numbers) {
std::cin >> i;
}
// Sort the entire array.
std::sort(std::begin(numbers), std::end(numbers));
// Display sorted numbers.
for (auto i : numbers) {
std::cout << i << '\n';
}
return 0;
}
The big mistake here is to read the values into individual variables. C++ has many different containers that can hold multiple values: an array, std::vector, std::array. But there's one that has a magic property, it keeps all the items in sorted order at all times: std::multiset.
cout << "Enter five integers. \n\n>";
std::multiset<int> a;
for (int i = 0; i < 5; ++i)
{
int v;
cin >> v;
a.insert(v);
}
for (auto it = a.begin(); it != a.end(); ++it)
cout << *it;
cout << "\n";
You can use a std::vector to store the input then use std::sort to sort the elements.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
vector <int> nums(5);
for(int i = 0; i < 5; ++i){
cin >> nums[i];
}
sort(nums.begin(), nums.end());
}
Alternative to std::sort, you could use std::multiset to sort your elements:
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
using namespace std;
int main(){
multiset <int> nums;
int input;
for(int i = 0; i < 5; ++i){
cin >> input;
nums.insert(input);
}
}
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';
}
}
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);
Like for example:
#include <iostream>
using namespace std;
int main()
{
for (int n=10; n>0; n--){
cout<< n <<", ";}
}
This will output the numbers 10,9,8,7,6,5,4,3,2,1
So is there a new way so I just get the last instance of the loop, the 1?
I new at this and google isn't giving me any answers.
There is no direct way to detect whether the current iteration of a for loop is the last one. But if the behavior of the loop is predictable, you can usually write code that can detect when you're on the last iteration.
In this case, you could do something like:
if (n == 1) {
cout << n << "\n";
}
in the body of the loop. (Of course it would be simpler in this case to replace the entire loop with cout << "1\n";, but I presume this is an example of something more complex.)
In more complicated cases, you can save whatever information you need in the body of the loop:
int value_to_print:
for ( ... ) {
value_to_print = i;
}
std::cout << value_to_print << "\n";
On each iteration, value_to_print is replaced by the current value of i. The final value is the value of i on the last iteration.
You could create a variable (outside the loop) to hold the "current" value of n; whatever happens to the loop (exit condition reached, break, an exception is thrown...) the value will stay there:
int last_n;
for (int n=10; n>0; n--) {
last_n = n;
cout<< n <<", ";
if (something) {
break; // works in this case
} else if (something else) {
throw some_random_error; // works in this case too
}
}
cout << "The last value of 'n' was " << last_n << endl;
You can use a simple if statement for that.
int main()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
if( n == 1 ) {
return n;
}
}
}
The simplest way to accomplish this is: -
#include <iostream>
using namespace std;
int main()
{
int x;
for (int n = 10; n > 0; n--){
x = n;
}
cout << x;
return 0;
}
I'm new to programming too and was trying to figure out something which will allow me to get the last instance of my loop as output.
I tried something and got the output, see if it can help you (if there's a mistake please let me know).
Here user input string is being replaced by "*" and instead of giving output of every instance i have made so only last instance is given as output.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int string_length;//string length
cout<<"Enter your Email-ID: ";
cin>>str;
string_length = str.length(); //to give the length of input string and use it for the loop
cout<<"lentgh of the string: "<<string_length <<endl;
for(int x = 0; x <= string_length; x++){
str[x] = '*';
while(x==string_length) //string_length is the last instance of the loop
{
cout<<"Here's your Encrypted Email-ID: " <<str<<endl;
break;
}
}
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.