The following code never places anything into the two integer arrays, seqs and seq_sizes but all other variables do contain expected contents when I pause and debug during runtime.
Why would these arrays remain empty despite the calls to place ints into them?
#include <iostream>
using namespace std;
int main(){
int n,q;
cout << "n q:" << endl;
cin>>n>>q;
int m = 1000000;
int seqs[m];
int seq_sizes[n];
cout << "seqs:" << endl;
for (auto i=0;i<n;++i){
cout << i << ":" << endl;
int take;
cin>>take;
seq_sizes[i]=take;
for (auto j=0;j<seq_sizes[i];++j){
int take2;
cin>>take2;
seqs[i+j]=take2;
}
}
cout << "queries:" << endl;
for (auto i=0;i<q;++i){
int seq,index;
cin>>seq>>index;
int tally=0;
for (auto j=0;j<seq;++j){
tally+=seq_sizes[j];
}
cout<<seqs[tally+index]<<endl;
}
return 0;
}
Sample input:
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
for (auto i=0;i<n;++i){
cout << i << ":" << endl;
int take;
cin>>take;
seq_sizes[i]=take;
for (auto j=0;j<seq_sizes[i];++j){
int take2;
cin>>take2;
seqs[i+j]=take2;
}
}
check the functioning of this loop(considering your input)
it sets seq_sizes[0] = 3 once and then it is reinitialized to 1.
Same happens again and again which is causing the error.
Consider changing i+j in line seqs[i+j]=take2;
Related
i tried to separate even and odd numbers using vectors from a array ==>
so i made a function that returns true is number is even and false for if number is odd
then i used an if else statement where if the function returns true then it pushbacks the value in a vector and if the function returns false then it pushbacks the value in another vector , finally i printed all the elements in the vector but the output does not show any element except it shows one in the odd vector.
#include <iostream>
#include <vector>
using namespace std;
bool sort(int arr[] , int i){
if(arr[i] %2 == 0){
return true;
}
return false;
}
int main(){
int n;
cin >> n;
int *arr = new int[n];
for(int i=1 ; i<=n ; i++){
arr[i-1] = i;
}
vector <int> even , odd;
int i=0 ;
if(sort(arr , i)){
even.push_back(arr[i]);
sort(arr , i+1);
}else{
odd.push_back(arr[i]);
sort(arr,i+1);
}
cout << "the even numbers are : " << endl;
for(auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for(auto element:odd){
cout << element << " ";
}
}
As #TonyDelroy said, you have to make for loop around call to sort(arr, i). Also first loop should go up to i <= n instead of i < n.
Your fixed working code below (see also std::partition_copy variant afterwards):
Try it online!
#include <iostream>
#include <vector>
using namespace std;
bool sort(int arr[] , int i){
if(arr[i] %2 == 0){
return true;
}
return false;
}
int main(){
int n;
cin >> n;
int *arr = new int[n];
for(int i=1 ; i<=n ; i++){
arr[i-1] = i;
}
vector <int> even , odd;
for (int i = 0; i < n; ++i)
if (sort(arr, i))
even.push_back(arr[i]);
else
odd.push_back(arr[i]);
cout << "the even numbers are : " << endl;
for(auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for(auto element:odd){
cout << element << " ";
}
}
Input:
10
Output:
the even numbers are :
2 4 6 8 10
the odd numbers are :
1 3 5 7 9
As #chris said you can also use std::partition_copy to implement your algorithm:
Try it online!
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
int n = 0;
std::cin >> n;
std::vector<int> arr(n), odd, even;
for (int i = 1; i <= n; ++i)
arr[i - 1] = i;
std::partition_copy(arr.cbegin(), arr.cend(),
std::back_insert_iterator(odd), std::back_insert_iterator(even),
[](auto const & x){ return (x & 1) == 1; });
std::cout << "the even numbers are : " << std::endl;
for (auto element: even)
std::cout << element << " ";
std::cout << std::endl << "the odd numbers are : " << std::endl;
for (auto element: odd)
std::cout << element << " ";
}
Input:
10
Output:
the even numbers are :
2 4 6 8 10
the odd numbers are :
1 3 5 7 9
You only push one element - the first.
Your partitioning code is equivalent to
if(sort(arr , 0)){
even.push_back(arr[0]);
sort(arr , 1);
}else{
odd.push_back(arr[0]);
sort(arr,1);
}
You need to loop over all the input numbers.
You can also simplify matters with a more generally useful evenness function that doesn't depend on an array:
bool is_even(int x) { return x % 2 == 0; }
and then there is no need to store all the inputs before processing them:
int main(){
vector <int> even , odd;
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
if (is_even(x)) {
even.push_back(x);
}
else {
odd.push_back(x);
}
}
cout << "the even numbers are : " << endl;
for (auto element:even){
cout << element << " ";
}
cout << endl;
cout << "the odd numbers are : " << endl;
for (auto element:odd){
cout << element << " ";
}
}
I have a program that allows the user to enter integers into a vector. Once the user is done with the first vector the program prints the contents of the vector and how big it is, the problem arises after the first vector when the user is suppose to be able to input integers into a second vector. My program just skips over that and doesn't let the user input anything. Code below.
#include <iostream>
#include <vector>
using namespace std;
void print1(vector <int> const& vector1) {
std::cout << "\nThe elements of Vector 1 are: ";
for (int v1{ 0 }; v1 < vector1.size(); ++v1) {
cout << vector1.at(v1) << ' ';
}
std::cout << "\nThe size of Vector 1 is: " << vector1.size();
}
void print2(vector <int> const& vector2) {
std::cout << "\nThe elements of Vector 2 are: ";
for (int v2{ 0 }; v2 < vector2.size(); ++v2) {
cout << vector2.at(v2) << ' ';
}
std::cout << "\nThe size of Vector 2 is: " << vector2.size();
}
int main() {
vector <int> vector1(0);
vector <int> vector2(0);
int data1{ 0 };
std::cout << "Enter data for Vector 1: ";
while (cin >> data1) {
vector1.push_back(data1);
}
print1(vector1);
int data2{ 0 };
std::cout << "\n\nEnter data for Vector 2: ";
while (cin >> data2) {
vector2.push_back(data2);
}
print2(vector2);
return 0;
}
EDIT********
Thanks to Nathan in the comments all I ended up having to do was add cin.clear(); right above the code for the second vector.
In your implementation the first loop is not exiting.
Here is a working and little improved implementation for the same. In this we are terminating the loop with any non-number input like a terminating '.':
#include <iostream>
#include <vector>
using namespace std;
void print_vector(vector <int> const& vector1) {
for (int v1{ 0 }; v1 < vector1.size(); ++v1) {
cout << vector1.at(v1) << ' ';
}
}
void read_vector(vector <int>& vector1) {
int data1{ 0 };
while (cin >> data1) {
vector1.push_back(data1);
}
cin.clear();
string term;
cin >> term;
}
int main() {
vector <int> vector1(0);
vector <int> vector2(0);
std::cout << "Enter data for Vector 1: ";
read_vector(vector1);
std::cout << "\nThe elements of Vector 1 are: ";
print_vector(vector1);
std::cout << "\nThe size of Vector 1 is: " << vector1.size() << endl;
std::cout << "Enter data for Vector 2: ";
read_vector(vector2);
std::cout << "\nThe elements of Vector 2 are: ";
print_vector(vector2);
std::cout << "\nThe size of Vector 2 is: " << vector1.size() << endl;
return 0;
}
Here is the output:
Enter data for Vector 1: 1 2 3.
The elements of Vector 1 are: 1 2 3
The size of Vector 1 is: 3
Enter data for Vector 2: 4 5 6.
The elements of Vector 2 are: 4 5 6
The size of Vector 2 is: 3
#include <iostream>
using std::cout;
using std::cin;
void printArray(int A[], int size) {
for(int i = 0; i < size; i++) {
cout << A[i] << "\t";
}
cout << "\n";
}
struct Array {
int *A;
int size;
int length;
};
void display(Array *arr) {
for(int i = 0; i < arr->length; i++) {
cout << arr->A[i] << "\t";
}
cout << "\n";
}
void fillArray(Array *arr) {
for(int i = 0; i < arr->length; i++) {
cin >> arr->A[i];
}
}
void add(Array *arr, int x) {
if(arr->length < arr->size) {
arr->A[++arr->length] = x;
}
}
int main() {
Array arr;
cout << "arr.size before initializing: " << arr.size << "\n"; // gives a garbage value
cout << "Enter the size of the array: ";
cin >> arr.size;
cout << "Output of arr variable &arr: " << &arr << "\n";
arr.A = new int[arr.size];
cout << "arr.length before initializing: " << arr.length << "\n"; // gives garbage value
cout << "How many elements do you want to enter: ";
cin >> arr.length;
fillArray(&arr); //This is not pass by value but pass by reference because
display(&arr); // this function displays the values of arr
add(&arr, 15);
cout << "The length of the array after adding: " << arr.length << "\n";
display(&arr);
printArray(arr.A, arr.length);
}
The output of this program is like this:
$ ./array_adt
arr.size before initializing: -140717888
Enter the size of the array: 10
Output of arr variable &arr: 0x7ffe4e0ec040
arr.length before initializing: 21932
How many elements do you want to enter: 5
4 6 7 3 2
4 6 7 3 2
The length of the array after adding: 6
4 6 7 3 2 0
4 6 7 3 2 0
I am highly confused why the element 15 isn't added to the array of the struct (which is actually a pointer which is initialised to an array in the heap). If someone can throw light on this it would be great for a many people as well as for understanding c++ concepts in depth.
Thanks a lot.
arr->A[++arr->length] = x;
should be
arr->A[arr->length++] = x;
Array indexes start at zero in C++, so the first element past the end of an array arr of size N is arr[N]. In other words 15 did get added to the array, just not in the right place.
Also your code leaks memory because the array allocated in main is never deleted. Correctly allocating dynamic memory is a big (and very important) topic. Consult your favourite C++ book, in particular you should research the rule of three
I am trying to understand sorting algorithms, so based on googled examples/explanations I wrote the below code. Code works 80% of the time. Every once in a while it doesn't sort properly and I can not see why.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void setArray( int *, const int & );
void selectionSorting( int *, const int & );
int main()
{
int numOfElem;
cout << "Num of array elements: ";
cin >> numOfElem;
cout << '\n';
int array[numOfElem];
setArray(array, numOfElem);
selectionSorting(array, numOfElem);
cout << '\n';
return 0;
}
void setArray( int *array, const int & numOfElem ){
srand(time(0));
cout << "Original array: " << '\n';
for (int i=0; i<numOfElem; i++){
array[i] = rand()%30;
cout << array[i] << ' ';
}
cout << '\n';
}
void selectionSorting( int *array, const int &numOfElem ){
int eff_size, swap;
int maxpos = 0;
for (eff_size = numOfElem; eff_size>1; eff_size--){
// loop searching for a position of largest number in the array
for (int i=0; i<eff_size; i++){
maxpos = array[i] > array[maxpos] ? i : maxpos;
}
swap = array[maxpos];
array[maxpos] = array[eff_size-1];
array[eff_size-1] = swap;
}
cout << "Selection Sorting: " << '\n';
for (int i=0; i<numOfElem; i++){
cout << array[i] << ' ';
}
}
Example output:
Num of array elements: 5
Original array:
7 17 1 12 25
Selection Sorting:
1 7 17 25 12
I can't see any pattern to the sorting failing - it fails in different places, weather there are repeated numbers, regardless of how many numbers I provide etc...
On each iteration of the outer loop(over eff_size) you should re-set maxpos to 0. Otherwise you have the chance that maxpos goes out of the effective portion being sorted(this happens if the maximum element is last in the effective portion i.e. if maxpos==effsize).
Question: why does it print out the correct values inside the while loop (while reading / inputting the file) but not outside the while loop? I don't understand.
Thank you very much for any help.
input file:
1
2
3
4
5
#include <iostream>
#include <string>
#include <fstream>
#include <string>
using namespace std;
int sumNumbers(int sum, int* numbers, int numElements, int count)
{
if (count == numElements) return sum;
sumNumbers(sum + numbers[count], numbers, numElements, count + 1);
return 0;
}
int main(int argc, char* argv[])
{
int* numbers;
int numElements = 0;;
int sum = 0;
string fileName = argv[2];
ifstream ifile(fileName);
if( ifile.fail() ) {
cout << "The file could not be opened. The program is terminated." << endl;
return 0;
}
while ( !ifile.eof() ) {
numbers = new int[++numElements];
ifile >> numbers[numElements - 1];
cout << "Position " << numElements - 1 << ": " << numbers[numElements - 1] << endl;
}
cout << numbers[0] << endl;
cout << numbers[1] << endl;
cout << numbers[2] << endl;
cout << numbers[3] << endl;
cout << numbers[4] << endl;
cout << "--------------\n";
for(int i = 0; i < numElements; i++) {
cout << "Position " << i << ": " << numbers[i] << endl;
}
sumNumbers(sum, numbers, numElements, 0);
cout << "The sum of the numbers in the file is: " << sum << endl;
return 0;
}
output:
Position 0: 1
Position 1: 2
Position 2: 3
Position 3: 4
Position 4: 5
0
-805306368
0
-805306368
5
--------------
Position 0: 0
Position 1: -805306368
Position 2: 0
Position 3: -805306368
Position 4: 5
The sum of the numbers in the file is: 0
You are instantiating (and leaking) a new array in each loop iteration. And you only fill one element of that array. After the loop ends, you are left with the final array, with only the last element set.
There are many questions on SO that deal with the problem of reading numbers from a file into an array or container. Here, numbers are read into an std::vector.
#include <fstream>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
int main()
{
std::vector<int> numbers;
ifstream ifile(fileName);
std::istream_iterator<int> eof;
std::istream_iterator<int> it(ifile);
std::copy(it, eof, std::back_inserter(numbers));
for(int i = 0; i < numbers.size(); ++i)
{
cout << "Position " << i << ": " << numbers[i] << endl;
}
}
Alternatively, you can replace the istream_iterators and the call to std::copy by a while loop:
int n=0;
while (ifile >> n) {
numbers.push_back(n);
}
This part:
while ( !ifile.eof() ) {
numbers = new int[++numElements];
// ...
repeatedly allocates memory for numbers. At each new, previous values are lost, and the memory from the previous allocation is leaking. You can print the value correctly before the next call to new so it seems to work within the loop.
It is better to use a vector:
int new_number;
while ( ifile >> new_number) {
numbers.push_back(new_number);
// ...
and don't use file.eof() in the while condition.