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.
Related
I'm learning c++ and I'm trying to ask the user to input 4 numbers in a function, and then simply print the array.
int getFourNums();
int main(int argc, char** argv){
int getNums;
getNums = getFourNums();
cout << "The array is: " getNums << endl;
}
int getFourNums(){
int i;
int myArray[4];
cout << "Enter 4 nums: ";
for(i = 0; i < 4; i++){
cin >> myArray[i];
}
return myArray[i];
As of now, it's letting me get the four numbers, but the result that's printing is "The array is: 0." I'm not quite sure why the array is seemingly not populating.
Your fundamental problem is that int getFourNums() can only return a single integer, not an array of them. The next problem is that functions cannot return raw arrays for historical reasons. Your choices are to return a std::array, a struct containing the array, pass the array by reference into the function, or return a std::vector. My preference for this application is a std::vector - it is flexible, and although not quite as efficient as std::array, you should probably default to std::vector unless you have a good reason otherwise. Your getNums code would then look like:
std::vector<int> getFourNums() {
std::vector<int> result;
cout << "Enter 4 nums: ";
for(int i = 0; i < 4; i++){
int v;
cin >> v;
result.push_back(v);
}
return result;
}
To print the vector, see this question. My personal preference would be a range-based for loop over the vector; your tastes may vary.
One issue in your code is that a loop like
for(i = 0; i < 4; i++){
cin >> myArray[i];
}
will end up with i==4. Hence, return myArray[i] will exceed array bounds and/or access an uninitialised value then and yield undefined behaviour.
The main issue, however, is that in C++ you'll follow a very different approach and use collection types like std::vector instead of plain arrays. See the following code illustrating this. Hope it helps.
#include <vector>
#include <iostream>
std::vector<int> getFourNums(){
int val;
std::vector<int> result;
cout << "Enter 4 nums: ";
for(int i = 0; i < 4; i++){
cin >> val;
result.push_back(val);
}
return result;
}
int main(int argc, char** argv){
std::vector<int> fourNums = getFourNums();
for (auto i : fourNums) {
cout << i << endl;
}
}
int getFourNums() will only let you return one int, not the whole array and return myArray[i]; is out of bounds since i == 4. You can only use the range [0,3] as indices for your array. Here's a reworked version with comments in the code.
#include <iostream>
#include <vector>
// don't do "using namespace std;" since it includes
// a lot of stuff you don't need.
// Here's a function that will return a vector of int's
// It'll behave much like a C style array
// but can have variable length and you can use
// a lot of standard functions on it.
std::vector<int> getNums(size_t count) {
// The "array" we'll return with "count" number of
// default constructed int:s (they will all be 0):
std::vector<int> myArray(count);
std::cout << "Enter " << count << " nums: ";
// A range based for loop that will go through
// all int:s in "myArray". "num" will be
// a reference to each int in the vector which
// means that if you change the value of "num",
// you'll actually change the value in the vector.
for(int& num : myArray) {
// read values into the int currently
// referenced by num
std::cin >> num;
}
// return the vector by value
return myArray;
}
// Put main() last so you don't have to forward declare the functions
// it uses
int main() {
// call getNums with the value 4 to read 4 int:s
std::vector<int> Nums = getNums(4);
std::cout << "The array is:";
// print each int in the vector. There's no need to use
// a reference to the int:s here since we won't be changing
// the value in the vector and copying an int is cheap.
for(int num : Nums) {
std::cout << " " << num;
}
// std::endl is rarely good when you only want to output a newline.
// It'll flush the buffer with is costly.
// Make a habit of using "\n" in most cases.
std::cout << "\n";
}
I see that you want to return entire array but just look at your return type:
int getFourNums()
You're returning an integer right? In this situation the returned integer is always myArray[4]. Be aware that it's an integer value, you're returning something that doesn't belong to you actually!
So what to do? I suggest you to pass your array to function like this:
void getFourNums(int myArray[]){
int i;
cout << "Enter 4 nums: ";
for(i = 0; i < SIZE; i++){
cin >> myArray[i];
}
}
Now you filled your array. How to print your array then? We can't simply give our array name and tell cout to print it like you did (you couldn't actually!). Nothing magical here. We're going to print your array's element one by one:
void printFourNumbers(int array[])
{
for(int i = 0 ; i < SIZE ; ++i)
{
cout << array[i] << endl;
}
}
Finally whole code looks like this:
#include <iostream>
using namespace std;
const int SIZE = 4;
void getFourNums(int myArray[]);
void printFourNumbers(int array[]);
int main(int argc, char** argv){
int myArray[SIZE];
getFourNums(myArray);
printFourNumbers(myArray);
}
void getFourNums(int myArray[]){
int i;
cout << "Enter 4 nums: ";
for(i = 0; i < SIZE; i++){
cin >> myArray[i];
}
}
void printFourNumbers(int array[])
{
for(int i = 0 ; i < SIZE ; ++i)
{
cout << array[i] << endl;
}
}
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 tried the code below to return an array with all string ids, but it didn't work.
The output just returns a number. How can I return an array with ids?
#include <iostream>
#include <string>
using namespace std;
string* getArray()
{
int nanim;
cout << "Enter the number of animals: ";
cin >> nanim;
string *id = new string[nanim];
for ( size_t i=0; i < nanim; i++ )
{
cout<< "\nEnter id anim "<< i+1 << ": ";
cin >> id[i];
}
for ( size_t i = 0; i < nanim; i++ )
{
cout << id[i] << endl;
}
return id;
}
int main()
{
int n;
cin>>n;
string* anim[n]=getArray();
cout<<anim;
return 0;
}
You are returning a pointer to the first element in the array.
To access array elements just having called string* arr = getArray(); you can use arr[0], arr[1], arr[2] etc. to access the strings.
Don't forget to delete the memory you allocated in the function though; at the moment you have a big memory leak.
Generally this is not good programming though since the function caller doesn't know how many elements there are in the returned array. It would be better to get the number of animals in the caller and pass that into your function.
Better still, rebuild your code to use std::vector as I see you're already using stl. Then you don't need to worry (explicitly) about memory allocation and deallocation.
You do not need to read the number of elements twice, and the type of the anim should be string*, not string* []. Unfortunately, this wouldn't tell you the number of items in the array, so you need to get it from the getArray, for example, like this:
string* getArray(int& nanim) {
// Remove the declaration of nanim, and keep the rest of the code unchanged
...
}
int main()
{
int n;
string* anim = getArray(n);
for (int i=0; i != n; i++) {
cout << anim[i] << endl;
}
delete[] anim;
return 0;
}
This is not an optimal C++ solution, though: you would be much better off using std::vector instead of an array, because the vector grows dynamically, and its size is returned along with the container itself. There would be no need to delete[] the result either, which would significantly simplify your code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> getVector()
{
int nanim;
cout << "Enter the number of animals: ";
cin >> nanim;
vector<string> res;
for ( size_t i=0; i < nanim; i++ )
{
cout<< "\nEnter id anim "<< i+1 << ": ";
string tmp;
cin >> tmp;
res.push_back(tmp);
}
return res;
}
int main()
{
vector<string> anim = getVector();
for ( size_t i = 0; i < anim.size(); i++ )
{
cout << anim[i] << endl;
}
return 0;
}
Below is the program I wrote to find sum of a subarray from given array, however somehow I am not getting how can I get rid of the sentinel value (-32767 in this case)? and how can I optimise it?
and how can I keep track of range of max subarray?
#define EVALUE -32767
using namespace std;
int findMaxSubArray(vector<int>,int low,int high);
int findMaxSubArray_Mid(vector<int>,int low,int high);
int main()
{
vector<int> v;
int j=0;
cout << "Enter array values(-32767 to end): ";
while(1)
{
cin >> j;
if (EVALUE==j)
break;
v.push_back(j);
}
if(v.size()!=0)
cout << "Max sum is: " << findMaxSubArray(v,0,v.size()-1) << "\n";
else
cout << "No array elements entered, exiting...\n";
system("pause");
return 0;
}
int findMaxSubArray(vector<int> v, int low, int high)
{
if(low==high) return v[low];
int max_mid_sum=findMaxSubArray_Mid(v,low,high);
int max_left_sum=findMaxSubArray(v,low,(low+high)/2);
int max_right_sum=findMaxSubArray(v,(low+high)/2+1,high);
if (max_mid_sum>max_left_sum) return (max_mid_sum>max_right_sum?max_mid_sum:max_right_sum);
else return(max_left_sum>max_right_sum?max_left_sum:max_right_sum);
}
int findMaxSubArray_Mid(vector<int> v,int low,int high)
{
int mid=high/2;
int max_left_sum=0;
int max_right_sum=0;
int sum=0;
for(int i=mid;i>=low;--i)
{
sum+=v[i];
if(sum>max_left_sum)
{
max_left_sum=sum;
}
}
sum=0;
for(int i=mid+1;i<=high;++i)
{
sum+=v[i];
if(sum>max_right_sum)
{
max_right_sum=sum;
}
}
return (max_right_sum+max_left_sum);
}
When reading from a textfile, the last character that cin will get is the "EOF" character, or end of file character. You can send this character to your program in the command line with control+d. You're going to want to check for this rather than -32767.
This is a basic program that should identify a simple fix for your problem:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> v;
int j;
cout << "Enter array values (Control+D (EOF) to end): ";
cin >> j;
while(cin.good())
{
v.push_back(j);
cin >> j;
}
return 0;
}
If you want to get really smart you can use the below and it will directly insert the contents of the memory at cin (from the beginning until EOF) into your vector. As far as running time goes, this will probably be faster than your solution and the above solution.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<int> v;
cout << "Enter array values (Control+D (EOF) to end): ";
istream_iterator<int> in(cin);
istream_iterator<int> eof;
copy(in, eof, back_inserter(v));
ostream_iterator<int> out(cout, "\n");
copy(v.begin(), v.end(), out);
return 0;
}
About the sentinel, IIRC with Control+D you close standard input(may depend of OS). That will cause the << to fail (I am not sure how, probably you'll have to catch an exception).
Anyway, the rest of the code is just a recursive (binomial) adding of the vector. You can sustitute all of it with a simple for
for(int i = 0; i < v.size(); i++) {
total += v[i]
}
The question about range of max subarray is already managed by the class Vector