printing a specific item from a list c++ - c++

im trying to print a number from a list in c++
`
#include <algorithm>
#include <iostream>
#include <list>
#include <random>
int main() {
int lenght, number;
lenght = 0;
std::list<int> list = {1,2,3,4,5,6,7,8,9};
int index = rand() % lenght; // pick a random index
int value = list[index]; // a random value taken from that list
for (int i : list){
lenght + 1;
}
return 0;
}
this line of code`
int value = list[index]; // a random value taken from that list
is giving me this error
operand types are: std::__cxx11::list<int, std::allocator<int>> [ int ]

Related

(C++) Making a random sequence of a set of numbers 1-3

I need my program to make a random sequence from 1-3 each time, but I don't understand how I'd use rand() to make the sequence of numbers 1 to 3 in a different order each program. It can't be the same number again, so I don't know what I'd do to prevent that. An example run would be
123 the first, 231 the second, 321 and so fourth
What would you use to make a sequence that doesn't repeat numbers
The simplest way to generate your sequence would be to use std::shuffle to re-order a vector containing your desired values:
#include <vector>
#include <algorithm>
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 g(rd());
std::vector<int> elements = { 1, 2, 3 };
std::shuffle(elements.begin(), elements.end(), g);
for (int i : elements)
{
std::cout << i << "\n";
}
}
If you really must use rand() (its not generally a very good random number generator) you can just about squeeze it into shuffle too:
#include <vector>
#include <algorithm>
#include <ctime>
#include <iostream>
struct RandDevice
{
using result_type = uint32_t;
static result_type max() { return static_cast<result_type>(RAND_MAX); };
static result_type min() { return 0; };
result_type operator()() {
return static_cast<result_type>(rand());
}
};
int main()
{
std::vector<int> elements = { 1, 2, 3 };
srand(time(0));
std::shuffle(elements.begin(), elements.end(), RandDevice());
for (int i : elements)
{
std::cout << i << "\n";
}
}
You can use std::next_permutation
Example here : https://en.cppreference.com/w/cpp/algorithm/next_permutation
it's pretty easy to do.. just compare the number you with every occupied element in the array. if it is not in the array, add to array. else, try again.
I have done similar code check this out
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void displayArray(int randNum[], int elements);
void randomNum(int randNums[], int elements);
int main ()
{
//declare array
int numbers[999] = {0};
//random number generator
srand(static_cast<int>(time(0)));
randomNum(numbers, 999);
displayArray(numbers, 999);
system("pause");
return 0;
}
void randomNum(int randNums[], int elements)
{
for (int i = 0; i < elements; i++)
{
bool same;
do
{
same = false;
randNums[i] = rand() % 999 + 100;
// Check if the newly generated number is a duplicate:
for (int check = 0; check < i; check++)
{
if (randNums[i] == randNums[check])
{
same = true;
break;
}
}
} while (same);
}
}
void displayArray(int randNum[], int elements)
{
for (int sub = 0; sub < elements; sub ++)
{
cout << "Unique Numbers: " << randNum[sub] << endl;
}
}

Counting the frequency of an elements in an array

Hello I am currently stuck on a homework problem as I have no idea how exactly to approach the problem.
Write a program that reads in a list of integers into an array with base type
int. Provide the facility to either read this array from the keyboard or
from a file, at the user’s option. If the user chooses file input, the program
should request a file name. You may assume that there are fewer than 50
entries in the array. Your program determines how many entries there are.
The output is to be a two-column list. The first column is a list of the distinct
array elements; the second column is the count of the number of
occurrences of each element. The list should be sorted on entries in the
first column, largest to smallest.
So I were to enter: 1, 2, 1, 10, 15, 12, 2, 10, 10
The program should output something like:
List Frequency
1-----2
2-----2
10----3
15----1
I am able to sort the numbers but don't know how I would go about comparing the numbers in the array.
#include <iostream>//Input/Output Library
#include <cstdlib>
#include <iomanip>
using namespace std;//Namespace of the System Libraries
//Global Constants
const int MAX = 10;
//Function Prototypes
void input(int array[], int size);
void sort(int array[],int size);
int main(int argc, char** argv){
//Declare Variable
int array[MAX];
int size = MAX;
//Input Data
input(array, size);
sort(array, size);
cout<<"\nSort Frequency\n";
for(int i = 0; i<size; i++){
cout<<array[i]<<endl;
}
return 0;
}
void input(int a[], int size){
cout<<"Enter "<<size<<" numbers for the array: \n";
for(int i=0; i<size; i++){
cin>>a[i];
}
}
void sort(int a[],int n){
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(a[i]>a[j]){
a[i]=a[i]^a[j];
a[j]=a[i]^a[j];
a[i]=a[i]^a[j];
}
}
}
}
In addition to #stryku's answer since you only want to print frequencies, you don't even need to create the v vector:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <map>
int main() {
std::map<int, size_t> counts;
std::for_each(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), [&counts](int k) {
++counts[k];
});
for(const auto &pair : counts)
std::cout<<pair.first <<" "<< pair.second<<"\n";
return 0;
}
Here you go (:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <map>
int main() {
std::vector<int> v;
std::map<int, size_t> counts;
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(v));
for(const auto &number : v)
++counts[number];
for(const auto &pair : counts)
std::cout<<pair.first <<" "<< pair.second<<"\n";
return 0;
}
I think your teacher will be surprised if you would explain it to him

C++ reading char values gives different letters sometimes

I have to write a short routine that will write out only upper case letters in reversed order. I managed to muster up code that somehow works, but whenever I test out my code with one specific input:
7 ENTER a b C d E f G
Instead of getting G E C I get
G (special) r E
I can't see what causes the problem, especially because it works for so many other cases. Here's the code:
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
char stringa[n];
int length = 0;
for (int i = 0; i <= n-1; i++) {
char letter;
cin >> letter;
if (isupper (letter)) {
stringa[((n-i) - 1)] = letter;
length = length +1;
} } for ( int i =0; i<=length-1; i++) {
cout << ciag[i]
The main problem is that you are not populating your array correctly.
You are not initializing the content of the array before filling it, so it contains random garbage. Then you are filling specific elements of the array using indexes that are the directly related to each uppercase character's original position in the input, rather than the position they should appear in the output.
Since you are not initializing the array, and the input has mixed lower/upper casing, your array is going to have gaps containing random data:
stringa[0] = G
stringa[1] = <random>
stringa[2] = <random>
stringa[3] = <random>
stringa[4] = E
stringa[5] = <random>
stringa[6] = <random>
stringa[7] = <random>
stringa[8] = C
stringa[9] = <random>
stringa[10] = <random>
stringa[11] = <random>
stringa[12] = <random>
stringa[13] = <random>
stringa[14] = R
stringa[15] = E
stringa[16] = T
stringa[17] = N
stringa[18] = E
stringa[19] = <random>
stringa[20] = <random>
That is what you are seeing appear in your garbled output.
Try something more like this instead:
#include <iostream>
#include <vector>
#include <cctype>
int main()
{
int n;
std::cin >> n;
std::vector<char> stringa(n); // 'char stringa[n];' is not standard!
int length = 0;
for (int i = 0; i < n; ++i)
{
char letter;
std::cin >> letter;
if (std::isupper (letter))
{
stringa[length] = letter;
++length;
}
}
for (int i = length-1; i >= 0; --i)
{
std::cout << stringa[i];
}
return 0;
}
Or:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cctype>
int main()
{
int n;
std::cin >> n;
std::vector<char> stringa(n); // 'char stringa[n];' is not standard!
int length = 0;
for (int i = 0; i < n; ++i)
{
char letter;
std::cin >> letter;
if (std::isupper (letter))
{
stringa[length] = letter;
++length;
}
}
std::reverse(stringa.begin(), stringa.begin()+length);
for (int i = 0; i < length; ++i)
{
std::cout << stringa[i];
}
return 0;
}
Both approaches produces the following array content during the first loop, and then simply output it in reverse order in the second loop:
stringa[0] = E
stringa[1] = N
stringa[2] = T
stringa[3] = E
stringa[4] = R
stringa[5] = C
stringa[6] = E
stringa[7] = G
Alternatively, I would suggest using std::getline() instead of a reading loop to obtain the user's input, and then simply manipulate the resulting std::string as needed:
#include <iostream>
#include <string>
#include <algorithm>
bool IsNotUpper(char ch)
{
return !std::isupper(ch);
}
int main()
{
std::string stringa;
std::getline(std::cin, stringa); // returns "7 ENTER a b C d E f G"
// so std::isupper() will return false for everything not in A-Z
std::setlocale(LC_ALL, "C");
stringa.erase(
std::remove_if(stringa.begin(), stringa.end(), &IsNotUpper),
stringa.end());
// returns "ENTERCEG"
std::reverse(stringa.begin(), stringa.end());
// returns "GECRETNE"
std::cout << stringa;
return 0;
}
Or, if using C++11 and later, you can use a lambda instead of a function for the std::remove_if() predicate:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string stringa;
std::getline(std::cin, stringa);
std::setlocale(LC_ALL, "C");
stringa.erase(
std::remove_if(
stringa.begin(), stringa.end(),
[](char ch){return !std::isupper(ch);}
),
stringa.end());
std::reverse(stringa.begin(), stringa.end());
std::cout << stringa;
return 0;
}
Your algorithm just doesn't make any sense. You are expecting the characters to be in the array with no gaps but you skip an entry in the array when the input isn't a capital letter. Instead, put the capital letters in consecutive slots in the array in the forward direction and then traverse it in reverse order afterwards.

(c++) saving random value from main to a function array

so this is what i'm suppose to do but its got me kinda confused, this is what i got so far any help would be appreciated:)
Write a function that dynamically allocates an array of integers. The function should accept an integer argument indicating the number of elements to allocate and should return a pointer to the array. Then write a driver in the main function that generates a random number (something not too large), calls the function, and verifies access by saving a value to the first element and displaying the contents of that element.
edited code it runs but i feel like im not using my function at all.
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int *MyArray(int);
int main()
{
srand(time(0));
int random = rand() % 5 + 1;
const int size = 5;
int array[size];
MyArray(size);
array[0] = random;
cout << array[0] << endl;
}
int *MyArray(int numOfElements)
{
int *array;
array = new int[numOfElements];
return array;
}
edited code
int main()
{
srand(time(0));
int random = rand() % 5 + 1;
const int size = 5;
int* array = MyArray(size);
array[0] = random;
cout << array[0] << endl;
delete [] array;
}
I believe you try to do something like this:
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int *MyArray(int);
int main()
{
srand(time(0));
int random = rand() % 5 + 1;
int *array = MyArray(random); //! store the pointer of dynamically allocated memory and use it.
array[0] = random;
cout << array[0] << endl;
delete [] array; //! To avoid memory leak
}
int *MyArray(int numOfElements)
{
int *array = new int[numOfElements];
return array;
}
Note: I'm just guessing this is what you probably looking for.

garbage value is obtained

this is a sample of my code. i am getting the value for maximum height. but my minimum height is a garbage value. what am i doing wrong
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
#define MAX 20
struct DATA
{
int id;
string name;
float height;
}numarray[MAX];
int main()
{
int num = 0;
numarray[num].height = fstr3;// contains float values from a file
float minimum, maximum;
minimum = numarray[0].height;
maximum = numarray[0].height;
for(int i = 0; i < MAX; i++)
{
{
if(numarray[i].height < minimum)
{
minimum = numarray[i].height;
}
else if(numarray[i].height > maximum)
{
maximum = numarray[i].height;
}
}
cout<< minimum<< " " << maximum<< endl;
return 0;
}
}
Garbage in, garbage out. It looks like your input routine (which you didn't post) may be populating the data incorrectly. I'd look at the input data in the debugger (even if your choice of debugger is printf()).
Your code assumes that minimum is unequal to the maximum.
Solution second if should be on its own and not in else clause from first.
assuming you do initialize the array in your real code, with these modifications:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
#define MAX 20
struct DATA
{
int id;
string name;
float height;
}numarray[MAX];
int main()
{
int num = 0;
numarray[num].height = fstr3;// contains float values from a file
float minimum, maximum;
minimum = numarray[0].height;
maximum = numarray[0].height;
for(int i = 1 /* skip 0 - already read */; i < MAX; i++)
{
if(numarray[i].height < minimum)
{
minimum = numarray[i].height;
}
// remove the else here
if(numarray[i].height > maximum)
{
maximum = numarray[i].height;
}
}
// move outside the loop
cout<< minimum<< " " << maximum<< endl;
return 0;
}
this should be OK