Max In a C++ Array - c++

I am trying to find the 'biggest' element in a user made array ,by using the max function from the algorithm library/header.
I have done some research on the cplusplus reference site but there I only saw how to compare two elements using the max function. Instead I am trying to display the maximum number using a function 'max' ,without having to make a 'for' loop to find it.
For example:
Array: array[]={0,1,2,3,5000,5,6,7,8,9}
Highest value: 5000
I have made this code but it gives me a bunch of errors, which can be the issue?
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int array[11];
int n = 10;
for (int i = 0; i < n; i++) {
array[i] = i;
}
array[5] = 5000;
max(array , array + n);
for (int i = 0; i < n; i++)
cout << array[i] << " ";
return 0;
}

max_element is the function you need. It returns an iterator to the max element in given range. You can use it like this:
cout << " max element is: " << *max_element(array , array + n) << endl;
Here you can find more information about this function: http://en.cppreference.com/w/cpp/algorithm/max_element

Here is a modification of your program that does what you want:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int array[11];
int n = 11;
for (int i = 0; i < n; i++) {
array[i] = i;
}
array[5] = 5000;
cout << *std::max_element(array, array + n) << "\n";
return 0;
}
Note that you had a bug in your program, you did not initialize the last element in your array. This would cause your array to contain junk value in the last element. I've fixed that by increasing n to 11. Note that this is OK because the condition in the for loop is i < n, which means that i can be at most 10, which is what you want.

You can also use std::array by #include<array>
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main()
{
array<int,10> arr;
int n = 10;
for (int i = 0; i < n; i++) {
arr[i] = i;
}
arr[5] = 5000;
cout<<"Max: "<< *max_element(arr.begin(),arr.end())<<endl;
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
More info on std::array

Related

How do I print out a simple array with numbers 0-99 on the console

I'm new to CS and I'm stuck on a practice problem in arrays where I have to print out an array with numbers 0-99 onto the console. My code right now seems to just create the numbers and print them but not actually put them in the array. I'm just curious how to actually set the elements to the array and then print them because that's the only thing holding me back from finishing the rest of the problem.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int num[100];
for (int i = 0; i < 100; i++)
num[i] = 0;
cout << num << endl;
}
Looks like you are very close! You just need to assign the value of 'i' into your array slot. Hope this helps!
EDIT:
To print the contents of the array you need to iterate back over the array and print each array element.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int num[100];
for (int i = 0; i < 100; i++)
num[i] = i; //assign value of 'i' to array slot
//print array elements
for (int i = 0; i < 100; i++)
cout << num[i]<< endl;
}
read the correct carefully:
#include <iostream>
#include <cstdio> // its C++ equivalent
using namespace std;
int main() {
int num[100];
for (int i = 0; i < 100; ++i)
num[i] = i;
for (int i = 0; i < 100; ++i)
cout << "num[" << i << "]" << num[i] << endl;
}

Filling an 1D array in C++

I have an integer array:
int listint[10] = {1,2,2,2,4,4,5,5,7,7,};
What I want to do is to create another array in terms of the multiplicity. So I define another array by:
int multi[7]={0};
the first index of the multi array multi[0] will tell us the number of multiplicity of the array listint that has zero. We can easily see that, there is no zero in the array listint, therefore the first member would be 0. Second would be 1 spice there are only 1 member in the array. Similarly multi[2] position is the multiplicity of 2 in the listint, which would be 3, since there are three 2 in the listint.
I want to use an for loop to do this thing.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int j;
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[7] = { 0 };
for (int i = 0; i < 9; i++)
{
if (i == listint[i])
count++;
j = count;
multi[j] = 1;
}
cout << "multi hit \n" << multi[1] << endl;
return 0;
}
After running this code, I thought that I would want the multiplicity of the each element of the array of listint. So i tried to work with 2D array.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int i, j;
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[7][10] = { 0 };
for (int i = 0; i < 9; i++)
{
if (i == listint[i])
count++;
j = count;
for (j = 0; j < count; j++) {
multi[j][i] = 1;
}
}
cout << "multi hit \n" << multi[4][i] << endl;
return 0;
}
The first code block is something that I wanted to print out the multiplicity. But later I found that, I want in a array that multiplicity of each elements. SO isn't the 2D array would be good idea?
I was not successful running the code using 2D array.
Another question. When I assign j = count, I mean that that's the multiplicity. so if the value of count is 2; I would think that is a multiplicity of two of any element in the array listint.
A 2d array is unnecessary if you're just trying to get the count of each element in a list.
#include <iostream>
int main() {
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[8] = { 0 };
for (int i : listint)
++multi[i];
for (int i = 0; i < 8; ++i)
std::cout << i << ": " << multi[i] << '\n';
return 0;
}
There's also a simpler and better way of doing so using the standard collection std::map. Notably, this doesn't require you to know what the largest element in the array is beforehand:
#include <map>
#include <iostream>
int main() {
int listint[10] = {1,2,2,2,4,4,5,5,7,7,};
std::map<int, int> multi;
for (int i : listint)
multi[i]++;
for (auto [k,v] : multi)
std::cout << k << ": " << v << '\n';
}
Try this incase maps won't work for you since you're a beginner, simple:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int j;
int listint[10] = {1,2,2,2,4,4,5,5,7,7};
int multi[8]={0};
for(int i=0; i<10; i++)
{
multi[listint[i]]++; // using listint arrays elements as index of multi to increase count.
}
for( int i=1; i<8; i++)
{
cout << "multi hit of "<<i<<" : "<< multi[i]<<endl;
}
return 0;
}
OR if numbers could get large and are unknown but sorted
#include <iostream>:
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count = 0;
int index = 0; // used to fill elements in below arrays
int Numbers[10] = {0}; // storing unique numbers like 1,2,4,5,7...
int Count[10] = {0}; // storing their counts like 1,3,2,2,2...
int listint[10] = {1, 2, 2, 2, 4, 4, 5, 5, 7, 7};
for(int i = 0; i < sizeof(listint) / sizeof(listint[0]); i++)
{
count++;
if (listint[i] != listint[i+1]) {
Numbers[index] = listint[i];
Count[index] = count;
count=0;
index++;
}
}
for(int i=0; i<index; i++)
{
cout << "multi hit of "<<Numbers[i]<<" is " << Count[i]<<endl;
}
return 0;
}

C++ Array of Pointers not assignable

I need to create 2 arrays, each with 4 elements. One array contains four int values gotten from the user, and the other array contains pointers to the elements of the first array. I keep getting the following error:
array type 'int *[4]' is not assignable
on this line:
my_ptrs = &my_ints;
Here is my code:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int my_ints[4];
int *my_ptrs[4];
float temp;
int num;
for (int x=0; x< 4; x++)
{
cout << "Enter Integer:" << endl;
cin >> num;
my_ints[x] = num;
}
my_ptrs = &my_ints;
for(int k=0; k<=3; k++)
{
for(int j=k+1; j<=3; j++)
{
if(my_ptrs[k]>my_ptrs[j])
{
temp=*my_ptrs[k];
my_ptrs[k]=my_ptrs[j];
*my_ptrs[j]=temp;
}
}
cout << my_ptrs[k] << " ";
}
return 0;
}
Your apparent intent is to have each pointer in my_ptrs to point to the corresponding value in my_ints.
I'm afraid there are no shortcuts here, using a single assignment. You have to do it the hard way:
for (int i=0; i<4; ++i)
my_ptrs[i]=&my_ints[i];
You cannot assign a pointer-to-an-array to an array variable, like you are trying to do. But what you can do instead is either:
initialize the second array in its declaration directly:
int my_ints[4];
int* my_ptrs[4] = {&my_ints[0], &my_ints[1], &my_ints[2], &my_ints[3]};
populate the array in a separate loop:
int my_ints[4];
int* my_ptrs[4];
for (int i = 0; i < 4; ++i)
my_ptrs[i] = &my_ints[i];
That being said, based on what you are trying to do ("i want to print the my_ptrs array in ascending order"), you could just get rid of the second array altogether and use the std::sort() algorithm instead:
Sorts the elements in the range [first, last) in ascending order.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int my_ints[4];
for (int x = 0; x < 4; ++x)
{
cout << "Enter Integer:" << endl;
cin >> my_ints[x];
}
std::sort(my_ints, my_ints+4);
for(int k = 0; k < 4; ++k)
cout << my_ints[k] << " ";
return 0;
}

Size of a vector of pairs

I am filling up an adjacency list of vector with pairs given by :
vector<pair<int, int>> adj[1000];
I am doing a depth first search on the list but experiencing some weird behaviour. The first print statement prints some value which means I have some items in adj[s][0], adj[s][1], adj[s][2] and so on. However when I calculate the size of adj[s] in the next line it prints out to be zero. Am I missing something here?. Is my definition for vector of pairs correct?. The adjacency list is correctly filled because when I ran cout << adj[s][0].first << endl; in dfs, it was correctly showing me the neighbors of each and every node.
Complete code
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <utility>
#include <climits>
#include <algorithm>
using namespace std;
vector<pair<int, int>> adj[1000];
bool visited[1000];
int nodeweight[1000];
void initialize()
{
for(int i = 0; i < 1000; i++)
visited[i] = false;
for(int i=0; i < 1000; i++)
adj[i].clear();
for(int i = 0; i <1000; i++)
nodeweight[i] = INT_MAX;
}
void dfs(int s)
{
visited[s] = true;
cout << adj[s][1].first << endl;
int minimum = INT_MAX, tovisit = 0;
for(int i = 0; i < adj[s].size(); i++)
{
cout << adj[s][i].second;
if(!visited[adj[s][i].first] && adj[s][i].second < minimum)
{
minimum = adj[s][i].second;
tovisit = adj[s][i].first;
}
}
nodeweight[tovisit] = minimum;
//dfs(tovisit);
}
int main() {
int N, E;
cin >> N >> E;
while(E--)
{
int i, j, w;
cin >> i >> j >> w;
adj[i].push_back(make_pair(j,w));
adj[j].push_back(make_pair(i,w));
}
initialize();
for(int i = 1; i <= N; i++)
{
dfs(i);
}
return 0;
}
You are clearing adj again after filling in initialize().
First you fill adj in the while loop in main. Then you call initialize() which includes this loop clearing all vectors in it:
for(int i=0; i < 1000; i++)
adj[i].clear();
Then you have cout << adj[s][1].first << endl; in dfs which is undefined behavior because there are no elements in adj[s]. The fact that you seem to get the correct results is just coincidental undefined behavior (although practical it is because the memory holding the vector data was not cleared.)
adj[s].size() is correctly reported as 0.

Displaying 2 iterated arrays in one for loop

I am working on creating a simulation of a test that will
1. randomize multiple choice answers
2. display the choices from a) b) c) d)
I have both codes done separately however can I use on for-loop to go about displaying this? Is this the best way to do this? All help is appreciated thank you!
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (){
const int TEST_SIZE = 13;
srand(time(0));
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };
for (int i = 0; i < TEST_SIZE; i++){
//generate random index number (0,1,2,3,4,5...)
int index = rand() % FACE_SIZE;
//swap animals[i] with animals[index]
string temp = animals[i];
animals[i] = animals[index];
animals[index] = temp;
}
//loop through array and print values
for (int i = 0; i < 7; i++){
cout << animals[i] << " ";
}
}
//separate code for part 2: choices from a-g
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int CHOICE_SIZE = 7;
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
for (int i = 0; i < CHOICE_SIZE; i++) {
cout << choices[i] << " ";
}
}
You can iterate over both arrays and stop when smaller will ends
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (){
const int TEST_SIZE = 13;
srand(time(0));
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };
for (int i = 0; i < TEST_SIZE; i++){
//generate random index number (0,1,2,3,4,5...)
int index = rand() % FACE_SIZE; // maybe here should be TEST_SIZE?
//swap animals[i] with animals[index]
string temp = animals[i];
animals[i] = animals[index];
animals[index] = temp;
}
//loop through array and print values
for (int i = 0; i < 7; i++){
cout << animals[i] << " ";
}
const int CHOICE_SIZE = 7;
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
for (int i = 0; i < CHOICE_SIZE && i < TEST_SIZE; i++) {
cout << choices[i] << " " << animals[i] << ", ";
}
}
Also, consider that if you want to use fixed-size array, you can use std::array:
#include <array>
std::array<string, TEST_SIZE> animals = {...};
And for shuffling you can use std::shuffle from 'algorithm' header .