How can I eliminate garbage value in this output? - c++

In this below program, I'm trying to marge 2 arrays into a single vector, but while returning the function I'm getting additional garbage values along with it.
Please anyone suggest me how to remove those!
#include <bits/stdc++.h>
#include <vector>
#include <string>
using namespace std;
vector <int> merge(int a[],int b[]){
vector <int> marr1;
marr1.clear();
int i=0,j=0;
while(i+j <= ((*(&a+1)-a)+(*(&b+1)-b)))
{
if ((i<= *(&a+1)-a)){
marr1.push_back(a[i]);
i++;
}
else{
marr1.push_back(b[j]);
j++;
}
}
sort(marr1.begin(),marr1.end());
return marr1;
}
int main(){
//array imlementation
int arr1[] = {5,7,4,5},arr2[] = {8,3,7,1,9};
vector <int> ans;
ans.clear();
ans = merge(arr1,arr2);
for (auto i=ans.begin();i<ans.end();++i){
cout<<*i<<"\t";
}
}
output produced:
0 0 0 0 1 3 4 5 5 7 7 8 9 32614 32766 4207952 1400400592

You want something like this:
include <iostream>
#include <vector>
#include <algorithm> // <<<< dont use #include <bits/stdc++.h>,
// but include the standard headers
using namespace std;
vector <int> mergeandsort(int a[], int lengtha, int b[], int lengthb) { // <<<< pass the lengths of the arrays
vector <int> marr1; // <<<< and use meaningful names
// marr1.clear(); <<<< not needed
for (int i = 0; i < lengtha; i++)
{
marr1.push_back(a[i]);
}
for (int i = 0; i < lengthb; i++)
{
marr1.push_back(b[i]);
}
sort(marr1.begin(), marr1.end());
return marr1;
}
int main() {
int arr1[] = { 5,7,4,5 }, arr2[] = { 8,3,7,1,9 };
vector <int> ans;
// ans.clear(); <<<< not needed
ans = mergeandsort(arr1, 4, arr2, 5);
for (auto i = ans.begin(); i < ans.end(); ++i) {
cout << *i << "\t";
}
}
Look at the <<<< comments for explanations.
There is still room for improvement:
passing the hard coded lengths of the arrays in mergeandsort(arr1, 4, arr2, 5) is bad practice, if you add/remove element from the arrays, you need to change the lengths too.
you shouldn't use raw arrays in the first place but vectors like in vector<int> arr1[] = { 5,7,4,5 };, then you don't need to care about the sizes as a vectors knows it's own size. I leave this as an exercise for you.

Since you're not passing the length of the array, there is no way inside the merge function to know about their length. Your program seems to produce undefined behavior as can be seen here. If you execute this program again and again you'll notice that the output changes which is an indication of undefined behavior.
Secondly, you're using std::vector::clear when there is no need to use it in your program. I have commented it in the code example i have given below.
You can use pass the length of the arrays as arguments to the merge function. Below is the complete working example:
#include <bits/stdc++.h>
#include <vector>
#include <string>
using namespace std;
vector<int> merge(int a[], int lengthA, int b[], int lengthB){
vector <int> marr1;
//marr1.clear();//no need for this since the vector is empty at this point
for(int i = 0; i< lengthA; ++i)
{
//std::cout<<"adding: "<<a[i]<<std::endl;
marr1.push_back(a[i]);
}
for(int i = 0; i< lengthB; ++i)
{
//std::cout<<"adding: "<<b[i]<<std::endl;
marr1.push_back(b[i]);
}
sort(marr1.begin(),marr1.end());
return marr1;
}
int main(){
//array imlementation
int arr1[] = {5,7,4,5},arr2[] = {8,3,7,1,9};
vector <int> ans;
//ans.clear();//no need for this since the vector is empty at this point
ans = merge(arr1,4, arr2, 5);
for (auto i=ans.begin();i<ans.end();++i){
cout<<*i<<"\t";
}
}

You pass two int[] which degrade to pointers. This means you cannot tell the number of elements which you attempt to do with i+j <= ((*(&a+1)-a)+(*(&b+1)-b)). Either pass in a length of each array, or even better (C++) pass in two vectors instead. Also, if you don't know the STL has a merge() function in <algorithm>.

Related

Unexpected value while placeing integers into an array

I am trying to fill an array with different integers, but it doesn't work as expected.
#include <iostream>
using namespace std;
int main(){
int i=0;
int num;
int MyArray[]={};
while (true) {
cout<<"sayi giriniz"<<endl;
cin>>num;
MyArray[i]=num;
i++;
for (int j=0; j<i; j++) {
cout<<MyArray[j]<<endl;
}
}
return 0;
}
https://imgur.com/a/tANGpSY
When I enter the 3rd value it gives an unexpected result.
int MyArray[]={};
Now, MyArray has a size of 0, so any indexes that you tried to access MyArray will cause undefined behavior.
If you want to make an array that is dynamically in size, use std::vector in the <vector> header.
Change
int MyArray[]={};
to
std::vector<int> MyArray;
This:
MyArray[i]=num;
i++;
To this:
MyArray.push_back(num); // you don't even need i
This
for (int j=0; j<i; j++) {
cout<<MyArray[j]<<endl;
}
To this:
for(const auto &i : MyArray) // range based for loop, recommend
{
std::cout << i << '\n';
}
Also, using namespace std; is bad, so don't use it.
If you want to take input and are unsure about the number of elements, you should use a vector. The array which you have made is of 0 size. It will surely give you an error.

C++ console reading uncertain number of inputs and put them in an Array?

Assume the following numbers are inputed in VC++ Console(separate with a space). N maybe 10, 20 or 100, it is uncertain.
1 2 3 4 ... N [Enter]
The number of inputs is uncertain, maybe 10, or 20. After I press the Enter key, how put these numbers into an Array?
array[0]=1; array[1]=2; ...
How to implement that with C++ code?
(The number of inputs is uncertain!)
As PeterT pointed out, If you don't know the size of the array ahead of time, you'll have to use dynamic memory allocation. Luckily, the STL has a container that does it for you.
You can use std::vector for that job.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
std::string nums; // the numbers in the format "1 2 3 4 10 -20"
std::getline(std::cin,nums);
std::stringstream stream(nums);
int n;
std::vector<int> vec;
while(stream >> n) {
vec.push_back(n);
}
return 0;
}
(code is based on Abdulla Al Sun's answer.)
This is an O(n) (linear complexity) solution.
If you want to convert it in to an actual array, you can do:
int array[vec.size()];
std::copy(vec.begin(), vec.end(), array);
Another approach is to figure out how many elements the user inputted by storing his input in a string, and counting the tokens.
Then you know how big of an array you need.
unsigned int getSize(std::string s) {
unsigned int size = 0;
std::stringstream ss(s);
int in;
while (ss >> in)
++size;
return size;
}
int main() {
std::string nums; // the numbers in the format "1 2 3 4 10 -20"
std::getline(std::cin,nums);
const unsigned int size = getSize(nums);
int array[size];
std::stringstream stream(nums);
int n;
for(unsigned int i = 0; stream >> n && i < size; ++i) {
array[i] = n;
}
return 0;
}
This is an O(2n) (linear complexity) solution.
My code assumes that the compiler allows variable array size. If it doesn't, use:
int* array = new int[size];
...
delete[] array;
To utilize RAII, wrap it in a struct like so:
struct DynArr {
int* data;
unsigned int size;
DynArr(const unsigned int size) :
size(size) {
data = new int[size];
}
~DynArr() {
delete[] data;
}
};
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int array[1000]; // your heighest input range
vector<int> numbers;
int main() {
string nums; // the numbers in the format "1 2 3 4 10 -20"
getline(cin,nums);
stringstream stream(nums);
int i = 0;
int n;
while(stream >> n){
array[i++] = n;
numbers.push_back(n);
}
// The number of integers in array is i. You can do anything with this number.
// numbers contains the input numbers.
return 0;
}
I have added vector after getting PeterT's idea. You can add vector for not setting the static size of array.
Try this code. The header of stringstream is sstream. I have compiled in in codeblocks, I think this will work on VC++ compiler too.
I'm going to steal Abdulla's code and make a couple slight modifications.
#include <iostream>
#include <string>
#include <sstream>
#include <cstring.h> // for memcpy
//using namespace std; frowned on. polutes global namespace
//the highest input range is undefined, so this isn't safe
//int array[1000]; // your heighest input range
int main() {
int max=10;
int * array = new int[max];// allow resizing of array by dynamically allocating
std::string nums; // the numbers in the format "1 2 3 4 10 -20"
std::getline(std::cin,nums);
std::stringstream stream(nums);
int i = 0;
while(stream){
if (i==max)
{
int * temp = new int[max*2];// note statistical analysis has found
//1.5 is generally a better multiplier
memcpy(temp, array, max*sizeof(array[0]));
// note do not use memcpy for copying complex data. It is too stupid.
delete array; // release memory of old array
array = temp; // replace old array with new array
max*=2;
}
int n;
stream>>n;
array[i++] = n;
}
// The number of integers in array is i. You can do anything with this number.
delete array; // all done. clean up.
return 0;
}
The really smart way is to use a std::vector. Odds are really good that this is going to be frowned on by the marker, so make your own resizable array class. With a class you can easily take advantage of RAII and automate the clean-up so it's exception safe.

Reversing an Array Results In SegFault

#include <iostream>
using namespace std;
/*
*
*/
int main() {
int k, in[k],reversea[k],i,m,n;
cin>>k;
for (i=0;i<k;i++){
cin>>in[i];
}
for (m=k-1;m>=0;m--){
for (n=0;n<k;n++){
in[m]=reversea[n];
}
}
for(i=0;i<k;i++){
cout<<reversea[i];
}
return 0;
}
I have no idea why it says segmentation fault even before i start debugging it. I compile another one on calculating the frequency of 1, 5, and 10 in an array of k numbers, and it says the same thing...
Here is the other one:
#include <iostream>
using namespace std;
int main() {
int k,i,m,n,count5,count1,count10;
int input[k];
cin>>k;
for (i=0;i<k;i++){
cin>>input[i];
}//input all the numbers
for(i=0;i<k;i++){
if (input[i]=1){
count1++;
}
if (input[i]=5){
count5++;
}
if (input[i]=10){
count10++;
}
}
cout<<count1<<"\n"<<count5<<"\n"<<count10<<"\n";
return 0;
}
Please help me. Thanks.
On this line
int k, in[k],reversea[k]
How are you supposed to initialize an array with k elements if k isn't initialized? The size of an array must be known at compile time not run time. If k isn't know until run time, use a std::vector
int k;
std::cin >> k;
std::vector<int> in(k);
std::vector<int> reversea(k);
Both your programs have two major faults.
You need to know the size of an array while creating it. In your code, k is still uninitialized and you are using this value as the size of your array. Instead, change it to
int k,i,m,n;
cin >> k;
int in[k];
int reversea[k];
While reversing the array, you should be filling reversea using values from in, and not the other way round. Also, you don't need 2 for loops, just use 1 for loop.
for (m=k-1; m>=0; m--){
reversea[m] = in[k-1-m];
}
In the second program, you again need to get the value of k before creating the array input[k].
You are testing for equality with a = instead of == . Change your code from
if (input[i]=1){
to
if (input[i] == 1) {

array concatenation of two different arrays

im doing simple genetic algorithm uniform crossover operation . for that im using two arrays as parent and mother.i want concatenate the childs for getting the offsprings(childs).
i have problem in adding the arrays .any help plssss.i did it ubuntu
#include<iostream>
#include <fstream>
#include <algorithm>
#include<vector>
using namespace std;
int main()
{
int P[ ]={3,7,6,5,2,4,1,8};
int N[ ]={8,6,7,2,5,3,4,1};
int r= (sizeof(P)/sizeof(*P)) ;
int s= (sizeof(N)/sizeof(*N));
int val=r/2 ;
int t1[val],t2[val],t3[val],t4[val],n=0,p=0;
for(int m=0;m< val;m++)
{
t1[n]=P[m];
t2[n]=N[m];
n++;
}
for(int x=val;x< r;x++)
{
t3[p]=P[x];
t4[p]=N[x];
n++;
}
int* child=new int [val+val];
copy(t1,t1+val,child);
copy(t3,t3+val,child+val);
cout << child;
}
return 0;
}
This part is wrong:
int t1[val], t2[val], t3[val], t4[val]
You can only use constant values to declare the size of arrays.
You can either use a std::vector or dynamically allocate memory for the t-arrays.
std::vector<int> t1(val);
std::vector<int> t2(val);
for(int m = 0; m < val; m++)
{
t1[n] = P[m];
t2[n] = N[m];
n++;
}
There seem to be multiple errors in your code.
Variable length arrays are at present not supported in C++.
int val=r/2 ;
int t1[val]; // Not OK
In the second for loop I guess you meant p++ instead of n++;
Instead of manually doing all the memory allocation - deallocation, you should use std::vectors
cout << child; // This outputs the address of the pointer, not the entire array.

C++ Vector Elements Count

In C++, using the vector header, how do I find the number of elements?
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
system("pause");
return 0;
primer(1000);
}
int primer(int max){
vector<int> a;
a[1]=2;
for (int i=2;i<=max;i++){
bool prime=true;
for (int ii=1;ii<=#a;ii++) {
if i/a[ii]==math.floor(i/a[ii]) {
prime=false;
}
}
if prime==true {
a[#a+1]=i;
}
}
for (i=1;i<=#a;i++) {
cout << a[i]);
}
}
}
I originally wrote the code
for lua, and this is my attempt to translate it to C++. I would appreciate specifics, for example, a specific replacement for a bad line. I tried to replace #a with a.size, but it didn't work.
Revised:
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
primer(5);
system("pause");
return 0;
}
int primer(int max){
vector<int> a;
a[1]=2;
for (int i=2;i<=max;i++){
bool prime=true;
for (int ii=0;ii<a.size();ii++) {
if (i/a[ii]==floor(i/a[ii])) {
prime=false;
}
}
if (prime==true) {
a.push_back(i);
}
}
for (int iii=0;iii<=a.size();iii++) {
cout << a[iii] << endl;
}
}
It crashes without running. For what reason is this?
a.size().
I would recommend using some sort of reference material, e.g. http://cplusplus.com/reference/stl/vector/.
To answer your immediate question:
a.size(); // use size as a function
But there are several other things wrong with your code:
vector<int> a;
a[1]=2;
Ordinarily you need to set the size of a beforehand, since C++ must allocate space for it. You can use push_back() though, which will incrementally add space as needed.
Also, C++ arrays start counting at 0:
for (int ii=1;ii<=#a;ii++) {
This should be
ii = 0
And since arrays start at 0, they end at size() - 1, not size().
for( int ii = 0; ii < a.size(); ++ii )
C and C++ array indexes start at zero and end at size-1, so you need to compare less-than, not less-than-or-equal-to. vector follows the same rule.
Another obvious problem that needs pointing out:
int main()
{
system("pause");
return 0;
primer(1000);
}
Your function is never going to be called. Your app will exit when main returns.
a[#a+1]=i;
changed to use size() becomes:
a[ a.size() + 1 ] = i;
This is syntactically correct but guaranteed wrong. It should be:
a.push_back(i);
Read the API referenced by Oli.