Vector still contains 0s after filling it [duplicate] - c++

This question already has answers here:
What's the difference between passing by reference vs. passing by value?
(18 answers)
c++ void function not changing value of string [duplicate]
(2 answers)
Closed 1 year ago.
I fill vector with random numbers without repeating ones, but when I try to output them, the vector contains only 0s. I tried to clear it before the filling with func .clear() but then the program can't access particular elements in it. When I run the program with debugger it shows that vector contains some numbers, but when it run the func printing() it prints only 0s. I attached screenshots of my tries after code listing.
#include <iostream>
#include <vector>
void filling(std::vector<int> array, int size);
void printing(std::vector<int> array, int size);
int main()
{
srand(time(0));
int sizeA;
printf("Enter size of vector A: ");
std::cin >> sizeA;
std::vector<int> A (sizeA);
filling(A, sizeA);
printf("Vector A: \n\t");
printing(A, sizeA);
}
void filling(std::vector<int> vector, int size)
{
//filling vector without repeating numbers
int temp;
bool flag;
vector[0] = rand() % 31;
for (int i = 1; i < size; )
{
temp = rand() % 31;
flag = true;
for (int j = 0; j < size; j++)
{
if (vector[j] == temp)
{
flag = false;
break;
}
else
{
continue;
}
}
if (flag)
{
vector[i] = temp;
i++;
}
}
}
void printing(std::vector<int> vector, int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", vector[i]);
}
}
This is the result I get but it's not what I expect:
Elements that debugger shows in vector after filling in the func:
Elements that shows after executing the func filling()

Related

Reading integers from an input file, storing only the unique integers in the array C++

I've been stuck on this homework question for a couple of days now. I did some research and I got to this:
#include<iostream>
#include<fstream>
#include<string>
#include<array>
using namespace std;
const int MAX_SIZE = 100;
bool RepeatCheck(int storage[], int size, int checker);
int main()
{
ifstream input("input.txt");
if (!input) // if input file can't be opened
{
cout << "Can't open the input file successfuly." << endl;
return 1;
}
int storage[MAX_SIZE];
int inputCount;
int checker;
while (!input.eof())
{
for (int i = 0; i <= MAX_SIZE; i++)
{
input >> checker;
if (!RepeatCheck(storage, MAX_SIZE, checker))
{
input >> storage[i];
}
}
}
// print array
for (int i = 0; i < 100; i++)
{
cout << storage[i] << " ";
}
return 0;
}
bool RepeatCheck(int storage[], int size, int checker)
{
for (int i = 0; i <= MAX_SIZE; i++)
{
if (storage[i] == checker)
{
return false;
}
}
}
My input file needs to be filled with integers separated by white space or on new lines:
1 2 2 3 5 6 5
4 3 20 34 5 7
5 2 4
6 3 3 4 5
7 6 7 8
I need to read the integers from the file and store them in the storage[] array only if they aren't already in the array.
It's not doing what I need it to do. Please take a look at my code and tell me where the logic error is. Much appreciated.
If std::set is allowed, use it instead of doing your own duplication check.
For your code, the problem happens here:
while (!input.eof())
{
//for loop not needed
for (int i = 0; i <= MAX_SIZE; i++) //increment regardless whether input is successful or not?
{
input >> checker; //take in a number
//if the number is not repeated
if (!RepeatCheck(storage, MAX_SIZE, checker))
{
input >> storage[i]; //read in another number to put it?
}
}
}
Also here
bool RepeatCheck(int storage[], int size, int checker)
{
for (int i = 0; i <= MAX_SIZE; i++)
//check all values in the array regardless whether it has been used or not?
//should just check until the end of used space, which is what size is meant for
{
if (storage[i] == checker)
{
return false;
}
}
//there should be a return true here right?
}
Have a look at this link to see why while (!iostream.eof()) is considered wrong.
The first part should look like this:
int i = 0;
while (input >> checker)
{
if (!RepeatCheck(storage, i, checker))
{
storage[i] = checker;
++i;
}
}
For second part, use size instead of max size

Error while Compiling "|75|error: cannot convert 'std::vector<int>' to 'int'" while implementing bfs

I am implementing bfs (Breadth First Search ) for the graph , but I am getting an error while I pass the starting value of the vector to an integer, for the dfs function to perform, as in the dfs function I have passed the source of the vector, i.e the first element of the vector.
error is on the line where start is declared to v[i]
Here is the complete code
#include <iostream>
#include <vector>
#include <queue>
#include <stdio.h>
using namespace std;
vector<int> v[10];
bool visited[10];
int level[10];
int a = 0;
int arr[10];
void dfs(int s) //function should run only one time
{
queue<int> q;
q.push(s);
visited[s] = true;
level[s] = 0;
while (!q.empty())
{
int p = q.front();
arr[a] = p;
a++;
q.pop();
for (int i = 0; i < v[p].size(); i++)
{
if (visited[v[p][i]] == false) {
level[v[p][i]] = level[p] + 1;
q.push(v[p][i]);
visited[v[p][i]] = true;
}
}
}
}
int main()
{
char c;
int start; // starting element of the vector
int i = 0; // for keeping track of the parent
int countt = 0; // keep track of the no of parents
bool check;
printf("Child or Parent ?");
scanf("%c", &c);
while (countt <= 10) {
if (c == 'c') {
check = true;
int j = 0;
while (check) {
// to keep the track of the child;
scanf("%d", &v[i][j]);
j++;
}
}
if (c == 'p')
{
scanf("%d", &v[i]);
if (i == 0)
{
start = v[i];
}
i++;
countt++;
}
}
printf(" Vector input completed");
dfs(start);
printf("DFS completed, printing the dfs now ");
for (int g = 0; g <= 10; g++)
{
printf("%d", &arr[g]);
}
}
In your current code, v is an array of size 10 containing vector's. However, start is an int, so there is nothing strange in getting an error when trying to assign one to another.
I believe that you wanted v to be either an array of ints or vector of ints. In such a case you just have to declare v properly: int v[10] or vector<int> v(10).
This is general syntax: if you want to declare a vector with known size then you have to put it in (), not in []. Note that you can also fill the vector with some initial values (say zeroes) by writing vector<int> v(10, 0).
In case got you wrong and you wanted to store a graph as vector of vectors, then you can write vector<vector<int>> v(10).

Equal elements in an unsorted array

I am making a program to identify whether a 5 card ( user input ) array is a certain hand value. Pair, two pair, three of a kind, straight, full house, four of a kind ( all card values are ranked 2-9, no face cards, no suit ). I am trying to do this without sorting the array. I am currently using this to look through the array and identify if two elements are equal to each other
bool pair(const int array[])
{
for (int i = 0; i < array; i++)
{
if (array[i]==aray[i+1])
{
return true;
}
else
return false;
}
Does this section of code only evaluate whether the first two elements are the same, or will it return true if any two elements are the same? I.E if the hand entered were 2,3,2,4,5 would this return false, where 2,2,3,4,5 would return true? If so, how do I see if any two elements are equal, regardless of order, without sorting the array?
edit: please forgive the typos, I'm leaving the original post intact, so as not to create confusion.
I was not trying to compile the code, for the record.
It will do neither:
i < array will not work, array is an array not an int. You need something like int arraySize as a second argument to the function.
Even if you fix that then this; array[i]==aray[i+1] will cause undefined behaviour because you will access 1 past the end of the array. Use the for loop condition i < arraySize - 1.
If you fix both of those things then what you are checking is if 2 consecutive cards are equal which will only work if the array is sorted.
If you really cant sort the array (which would be so easy with std::sort) then you can do this:
const int NumCards = 9; // If this is a constant, this definition should occur somewhere.
bool hasPair(const int array[], const int arraySize) {
int possibleCards[NumCards] = {0}; // Initialize an array to represent the cards. Set
// the array elements to 0.
// Iterate over all of the cards in your hand.
for (int i = 0; i < arraySize; i++) {
int myCurrentCard = array[i]; // Get the current card number.
// Increment it in the array.
possibleCards[myCurrentCard] = possibleCards[myCurrentCard] + 1;
// Or the equivalent to the above in a single line.
possibleCards[array[i]]++; // Increment the card so that you
// count how many of each card is in your hand.
}
for (int i = 0; i < NumCards; ++i) {
// If you want to check for a pair or above.
if (possibleCards[i] >= 2) { return true; }
// If you want to check for exactly a pair.
if (possibleCards[i] == 2) { return true; }
}
return false;
}
This algorithm is actually called the Bucket Sort and is really still sorting the array, its just not doing it in place.
do you know the meaning of return keyword? return means reaching the end of function, so in your code if two adjacent values are equal it immediately exits the function; if you want to continue checking for other equality possibilities then don't use return but you can store indexes of equal values in an array
#include <iostream>
using namespace std;
int* CheckForPairs(int[], int, int&);
int main()
{
int array[ ]= {2, 5, 5, 7, 7};
int nPairsFound = 0;
int* ptrPairs = CheckForPairs(array, 5, nPairsFound);
for(int i(0); i < nPairsFound; i++)
{
cout << ptrPairs[i] << endl;
}
if(ptrPairs)
{
delete[] ptrPairs;
ptrPairs = NULL;
}
return 0;
}
int* CheckForPairs(int array[] , int size, int& nPairsFound)
{
int *temp = NULL;
nPairsFound = 0;
int j = 0;
for(int i(0); i < size; i++)
{
if(array[i] == array[i + 1])
nPairsFound++;
}
temp = new int[nPairsFound];
for(int i(0); i < size; i++)
{
if(array[i] == array[i + 1])
{
temp[j] = i;
j++;
}
}
return temp;
}
You could use a std::unordered_set for a O(n) solution:
#include <unordered_set>
using namespace std;
bool hasMatchingElements(const int array[], int arraySize) {
unordered_set<int> seen;
for (int i = 0; i < arraySize; i++) {
int t = array[i];
if (seen.count(t)) {
return true;
} else {
seen.insert(t);
}
}
return false;
}
for (int i = 0; i < array; i++)
{
if (array[i]==aray[i+1])
{
return true;
}
else
return false;
This loop will only compare two adjacent values so the loop will return false for array[] = {2,3,2,4,5}.
You need a nested for loop:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int unsortedArray[] = {2,3,2,4,5};
int size = 5;
for(int i=0;i<size-1;i++)
{ for(int j=i+1;j<size;j++)
{ if(unsortedArray[i]==unsortedArray[j])
{ printf("matching cards found\n");
return 0;
}
}
}
printf("matching cards not found\n");
return 0;
}
----EDIT------
Like Ben said, I should mention the function above will only find the first instance of 2 matching cards but it can't count how many cards match or if there are different cards matching. You could do something like below to count all the number of matching cards in the unsortedArray and save those values into a separate array. It's messier than the implementation above:
#include <iostream>
#include <stdio.h>
#include <stdbool.h>
#defin NUM_CARDS 52;
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int N,i,j;
cin>>N;
int unsortedArray[N];
for(int i=0;i<N;i++)
cin>>unsortedArray[i];
int count[NUM_CARDS]={0};
int cnt = 0;
for( i=0;i<N-1;i++)
{
for( j=i+1;j<N;j++)
{ if(unsortedArray[i]==-1)
break;
if(unsortedArray[i]==unsortedArray[j])
{
unsortedArray[j]=-1;
cnt++;
}
}
if(unsortedArray[i]!=-1)
{
count[unsortedArray[i]]=cnt; //in case you need to store the number of each cards to
// determine the poker hand.
if(cnt==1)
cout<<" 2 matching cards of "<<unsortedArray[i]<<" was found"<<endl;
else if(cnt>=2)
cout<<" more than 2 matching cards of "<<unsortedArray[i]<<" was found"<<endl;
else
cout<<" no matching cards of "<<unsortedArray[i]<<" was found"<<endl;
cnt = 0;
}
}

Splitting an array at a given value

Hello I am trying to split an array any time there is a negative value (excluding the negative value) and am a bit stuck at the moment. I tried an approach as seen in my code but I am not getting the desired output.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
string line;
string filename;
int n,length;
std::vector<int>arr1;
fstream file("t1.txt");
if(file.is_open())
{
while(file >> n)
arr1.push_back(n);
for(int i =0; i < (int)arr1.size(); i++)
cout << arr1.at(i);
}
cout << endl;
int* arr2 = &arr1[0];
int arr3[arr1.size()/2];
int arr4[arr1.size()/2];
for(int i = 0; i < arr1.size(); i++)
{
cout << arr2[i];
}
for (int i =0; i < arr1.size(); i++)
{
if(i == -1)
break;
else
arr3[i] = arr2[i];
}
return 0;
}
The main problem is here:
int arr3[arr1.size()/2];
int arr4[arr1.size()/2];
This doesn't compile, and can be replaced with
std::vector<int> arr3; arr3.reserve(arr1.size() / 2);
std::vector<int> arr4; arr4.reserve(arr1.size() / 2);
I've added the "reserve" function so that the program doesn't have to allocate memory over and over in the loop.
Next, you are checking i in your loop, and your i loops from 0 to arr1.size() (which is unsigned so can't be negative) therefore i will never be negative.
What you really wanna check is what is in the arr1 vector at "i" position, and you can do so with the [] operator like
for (int i =0; i < arr1.size(); i++)
{
if (arr1[i] >= 0) //if the value is positive, we push it inside our arr3 vector
arr3.push_back(arr1[i]);
else
{
i++; //skip negative value
//
while (i < arr1.size())
{
if (arr1[i] > 0)
arr4.push_back(arr1[i]);
i++;
}
//
//or
//insert all the elemenents we haven't processed yet in the arr4 vector
//this code assumes those elements are positive values
//arr4.insert(arr4.begin(), arr1.begin() + i, arr1.end());
//break;
}
}
Of course this could be done in a different way, like instead of creating 2 vectors, you could just use the one you have generated already.
Hope this helps.
There are several problems in your code
you should not access the vector's data this way unless you really need to
you prepare arrays with predefined size without knowing where to expect the negative values
you do not assign anything to your array 4
you check the index for being negative, not the value
according to your text there could be several negative values leading to multiple result-arrays. You seem to be prepared for only two.
Here is some code that actually splits when encountering negative values:
std::vector<vector<int> > splitted;
for (int i = 0; i < arr1.size(); ++i)
{
if (i ==0 or arr1[i] < 0)
splitted.push_back(std::vector<int>());
if (arr1[i] >= 0)
splitted.back().push_back(arr1[i]);
}
Testing it:
for (int i = 0; i < splitted.size(); ++i)
{
for (int k = 0; k < splitted[i].size(); ++k)
{
std::cout << splitted[i][k];
}
if (splitted[i].empty())
std::cout << "(emtpy)";
std::cout << '\n';
}
Using the following test input
1 2 3 -1 1 -1 -1
You get the following output:
123
1
(emtpy)
(emtpy)

Return an array of compared char pointers in C++ [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I'm at college and we're learning pointers. Our job was to input a char, compare it to an array and return a pointer to the first reference of that char in the array. But, as I don't like easy things, I've asked my teacher what about having that char more than once in the array.
That's where my headache begins.
So I have this code. The idea is: create a function that compares the input char to the entire array, get the pointers of the references and save them in an array and return that array.
Unfortunately it's not working as I wish :(
What can be wrong?
#include<iostream>
#include<cstdlib>
using namespace std;
char list [10];
int main()
{
initialize();
show();
cout<<search('1');
}
void initialize()
{
int i;
for(i=0; i<10;i++)
{
list[i]='1';
}
}
void show()
{
int i;
for(i=0; i<10;i++)
{
cout<<list[i];
}
}
int* search(char* input)
{
int* result[10];
int i;
char *temp;
for (i=0; i<10; i++)
{
*temp=list[i];
if(strcmp(temp, input) != NULL)
{
result[i]=i;
}
}
return result[];
}
I'm on a mobile device so I can't go into huge detail unfortunately, but you are returning a pointer to an array that you create in the function which goes out of scope at the end of the function.
My massive edit:
As everyone has already stated, a C++ array is actually only a pointer to the first element in the array. As a result, if you return a pointer to an array created in the scope of the function, you are returning a pointer to garbage. If I were doing this I would use a vector, but if I were to be forced into using an array, I would use something like the code below. Hope this helps!
#include <iostream>
#include <cstdlib>
void initialize(char* list) {
for(int i = 0; i < 10; ++i) {
if(i < 4) {
list[i] = '2';
} else {
list[i] = '1';
}
}
}
void show(char *list) {
for(int i = 0; i < 10; ++i) {
std::cout << list[i] << ' ';
}
std::cout << std::endl;
}
// Note the function requires an additional argument that is a pointer
// this is how you can avoid returning a pointer
int search(char input, char* list, char* result) {
int j = 0;
for(int i = 0; i < 10; ++i) {
// comparing characters can be done via ==
if(input == list[i]) {
*(result + j) = list[i];
// You could use result[j], but I used this to show that
// result really is just a pointer to the first element
// of the array. As a result saying result[j] is the same
// as saying I want to deference j elements past the first
// element or *(result + j)
++j; // increment j
}
}
// return how many elements matched
return(j);
}
int main(int argc, char *argv[]) {
char list[10];
char temp[10];
initialize(list);
show(list);
int size = search('1', list, temp);
// create a dynamically sized array containing space for each match
// because we don't know the size at compile time we must use
// a library type or a dynamically sized array
char *result = new char[size];
for(int i = 0; i < size; ++i) {
result[i] = temp[i];
// again you could use result[i]
std::cout << *(result + i) << std::endl;
}
delete[] result; // otherwise you'll get a memory leak
return(0);
}