I have a code like this:
Forgive me Polish names for stuff, I hope it isn't a problem. I can change them if you wanna.
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
//a few unimportant functions
void zamianaNaDziesietny(int podstawa, int liczba, int reszta[])
{
vector < int > cyfra;
cout <<"\n";
for(int a = reszta.size(); a > 0; a--)
{
cyfra.push_back(reszta[a - 1] * pow(podstawa, a - 1));
}
for(int a = 1; a < cyfra.size(); a++)
{
cyfra[0] += cyfra[a];
}
cout << cyfra[0];
}
void zamianaNaDziesietny(int podstawa, int liczba, int reszta[])
{
vector < int > cyfra;
cout <<"\n";
for(int a = reszta.size(); a > 0; a--) //request for member 'size' in 'reszta', which is of non-class type 'int*'
{
cyfra.push_back(reszta[a - 1] * pow(podstawa, a - 1));
}
for(int a = 1; a < cyfra.size(); a++)
{
cyfra[0] += cyfra[a];
}
cout << cyfra[0];
}
//another unimportant part of code
int main()
{
//unimportant stuff
zamianaZDziesietnego(podstawa, liczba);
zamianaNaDziesietny(podstawa, liczba, reszta);
return 0;
}
I dunno how to use vector 'reszta' as an argument in function "zamiananaDziesietny".
What should I type to let this program compile?
I'm getting 2 errors:
One of them is:
'reszta' was not declared in this scope
It's an array... Oh well, vector is a kind of array... I think... I'm noob so I can always be wrong.
I can work on this vector in main, adding "cout << reszta[0];" (just to write on the screen an element of this vector) in main, just between inductions of those two functions worked well. But I think this problem could be solved by setting this vector in main and then it will be as an argument in zamianaZDziesietnego() function too, but...
I dunno how to use a vector as an argument in function.
The second error I'm getting is:
request for member 'size' in 'reszta', which is of non-class type 'int*'
It's in the 32nd line.
So this is my problem.
I have tried typing this argument in a few different ways.
When I tried with:
void zamianaNaDziesietny(int podstawa, int liczba, vector reszta[])
The second error changed to:
request for member 'size' in 'reszta', which is of pointer type 'std::vector*' (maybe you meant to use '->' ?)|
And also got a new error a few lines below:
no match for 'operator*' in '*(reszta + ((((sizetype)a) + -1u) * 12u)) * pow((double)podstawa, (double)(a + -1))'|
Well, I am very a big noob and I dunno how to solve this. Could anyone help?
Btw, if anyone was interested - I'm making a program that converts binear counts to decimal and vice versa.
Just declare the argument like this:
void zamianaNaDziesietny(int podstawa, int liczba, std::vector<int> reszta)
{
vector < int > cyfra;
cout <<"\n";
for(int a = reszta.size(); a > 0; a--)
{
cyfra.push_back(reszta[a - 1] * pow(podstawa, a - 1));
}
for(int a = 1; a < cyfra.size(); a++)
{
cyfra[0] += cyfra[a];
}
cout << cyfra[0];
}
Or better still, pass the vector by reference to avoid it being copied:
void zamianaNaDziesietny(int podstawa, int liczba, std::vector<int>& reszta)
{
vector < int > cyfra;
cout <<"\n";
for(int a = reszta.size(); a > 0; a--)
{
cyfra.push_back(reszta[a - 1] * pow(podstawa, a - 1));
}
for(int a = 1; a < cyfra.size(); a++)
{
cyfra[0] += cyfra[a];
}
cout << cyfra[0];
}
What you have done is use an int array (int reszta[]) as the argument rather than a vector - they are different types.
Vectors are different than arrays, as vectors are classes and can have methods called upon them (ex. .size(). Arrays are from c which are really just pointers in memory. Passing in the reference as stated would be the best way to pass in the vector, but make sure to be careful about modification.
Related
my aim is to sort an array of structures. The structure contains the index of a customer {1,..., number} and a pointer to a value of an other sturcture,
e.g,
for (int i = 1; i < no_orders+1; i++){
sorting_array[i].index_order = i;
sorting_array[i].some_vaule = &order_data[i].some_value;
}
Here, order_data is an array of structures contains all customer data which allows for directly accessing variable data a customer the index. The array sorting_array is the one to sort according to a value in order_data; therefore the pointer in DATA_TO_SORT in order to avoid copying effort since this function is called millions of times (same indices, changed values).
The actual problem appears with the sorting function. If I do not use the pointer but the real value (int some_value, including copying effort however), sorting works as it should.
Defining some_value as pointer, std::sort terminates after some seconds without any feedback the whole program. The actual question is why and what may I change.
struct DATA_TO_SORT {
int index_order;
int *some_value;
};
bool compare_by_val( DATA_TO_SORT &a, DATA_TO_SORT &b) {
return *a.some_value > *b.some_value;
}
void sort_acc_release() {
std::sort(sorting_array.begin() + 1, sorting_array.end(), compare_by_val);
}
Also tried the following from a related topic, however, the depicted error statement occurs - besides several similar error statements.
std::sort(sorting_array.begin() + 1, sorting_array.end(), [&](size_t a, size_t b) {return *sorting_array[a].some_value > *sorting_array[b].some_value; });
<lambda_0a6c4bdbc69eba5706031ee8a4b875c6>::operator ()(::size_t,::size_t) const" : Konvertierung von Argument 1 von "DATA_TO_SORT" in "::size_t" nicht möglich Algorithm ...\microsoft visual studio\2017\community\vc\tools\msvc\14.12.25827\include\xutility 1017
Minimum Example which WORKS.
#include <iostream>
#include <cstdlib> //rand
#include <algorithm> //swap etc
#include <array> //array
struct OTHER_DATA {
int other_data;
};
struct DATA_TO_SORT {
int index_order;
int *some_value;
};
bool compare_by_val(DATA_TO_SORT &a, DATA_TO_SORT &b) {
return *a.some_value > *b.some_value;
}
int main() {
const int max_no = 10;
std::array<OTHER_DATA, max_no> some_other_values;
std::array<DATA_TO_SORT, 10> sorting_array;
for (int i = 0; i < some_other_values.size(); i++)
{
some_other_values[i].other_data = i * 5;
sorting_array[i].index_order = i;
sorting_array[i].some_value = &some_other_values[i].other_data;
}
for (int i = 0; i < sorting_array.size(); i++)
{
std::cout << "\n" << sorting_array[i].index_order << "\t" << *sorting_array[i].some_value;
}
std::sort(sorting_array.begin(), sorting_array.end(), compare_by_val);
for (int i = 0; i < sorting_array.size(); i++)
{
std::cout << "\n" << sorting_array[i].index_order << "\t" << *sorting_array[i].some_value;
}
system("pause");
return 0;
}
Thank you in advance for your problem-related and well-intentioned answers!
I'm trying to import data from a text file into structs for use as i don't really want to import them into seperate arrays.
I keep getting "error: expected primary-expression before '[' token" on each getline, i'm terrible at C++ and basically using what C skills i have to try and make sense of this. What am i doing wrong?
#include <stdio.h>
#include<fstream>
#include <cstdlib>
#include <iostream>
#include "Ladybird.h"
using namespace std;
typedef struct managerImport{
int gridSizeA;
int gridSizeB;
int aphidCount;
int aphidPos;
int ladyCount;
int ladyPos;
struct managerImport *next;
};
void importData(managerImport[]){
ifstream manager;
manager.open("Manager.txt");
if (!manager.fail()){
//loops the 2d array
for (int i = 0; i < 1; i++)
{
getline(manager, managerImport[i].gridSizeA, managerImport[i].gridSizeB);
}
//loop the lady bird count
for (int i = 1; i < 2; i++)
{
getline(manager, managerImport[i].ladyCount);
}
//loops the lady bird coordinates
for (int i = 2; i < 10; i++)
{
getline(manager, managerImport[i].ladyPos);
}
for (int i = 10; i < 11; i++)
{
getline(manager, managerImport[i].aphidCount);
}
//loops the lady bird coordinates
for (int i = 11; i < 19; i++)
{
getline(manager, managerImport[i].aphidPos);
}
}
manager.close();
}
int main() {
//importing the manager text file
importData;
}
Did you name the argument in the function?
void importData(managerImport[]) just says you have a function importData that takes an array of type managerImport (your struct).
Edited for clarification:
Imagine I write this code:
int increment(int) { return int+1; }
What I've done is hand the compiler a function that takes an argument "int". Is "int" a type or the name of my argument? This obviously won't compile since the argument has to have both a type and a name (so even if I want want to name my argument "int" (not advised), I still need to supply a type which says what "int" actually is (type-wise). Is it a long, a string, an unsigned char? Assuming I meant to actually accept an int, add 1, and return the incremented value (an int), this is what I should have written:
int increment(int i) { return i+1; }
So, in your case, you have:
void importData(managerImport[]) { ... }
Obviously, you're meaning to accept an array of managerImport, but you haven't given that array a name. Try this:
void importData(managerImport foo[]) { .. }
Also, unless you really need a c-array, you might try using a vector or an C++ array (std::array).
The function getline does not translate text into integers. It simply copies text without translations.
for (int i = 0; i < 1; i++)
{
getline(manager, managerImport[i].gridSizeA, managerImport[i].gridSizeB);
}
Your getline function call translates to getline(stream, int, int);.
You will need to either use:
manager >> managerImport[i].gridSizeA >> managerImport[i].gridSizeB;
or read in as string and parse out of the string.
I'm a beginner in c++ and I'm getting two errors in my code and I don't know how to fix them...
the first one
illegal indirection
and the second one is
'=' left operand must be a I-value. (in the line: ((ArrayPtr +i)+j)=rand()%55+1 )
Does anyone have an idea how to fix them? That's my code:
#include <iostream>
#include <math.h>
#include <time.h>
#include<iomanip>
#include<array>
#include <algorithm>
using namespace std;
const int AS = 6;
void FillingRandomly(int (*)[AS]);
void printing(int (*)[AS]);
int c;
int main()
{
int funny = 0;
int timpa = 0;
int counter = 0;
int Array[AS][AS];
srand(time(0));
FillingRandomly(Array);
cout << "The unsorted array is" << endl << endl;
printing(Array);
cout << "The sorted array is" << endl << endl;
printing(Array);
system("PAUSE");
return 0;
}
void FillingRandomly(int *ArrayPtr)
{
for(int i=0;i<AS;i++)
{
for (int j=0;j<AS;j++)
{
*(*(ArrayPtr +i)+j)=rand()%55+1;
}
}
}
void printing(int *Array)
{
for(int i=0;i<AS;i++)
{
for (int j=0;j<AS*AS;j++)
{
int counter = 0;
cout<<((Array[i] +j))<<setw(5);
if ((Array[i] +j)%AS == 0)
cout << endl << endl;
}
}
}
void forsorting(int *Brray, int funny)
{
int dice = 0;
int super = 0;
int space=0;
//Sorting Array[][] which is treated like Array[]
{
for (int pass = 0; pass < AS - 1; pass++) {
for (int k = 0; k < AS - 1; k++) {
int temp;
if(*(Brray+k)==*(Brray+k+1))
{
temp=*(Brray+k);
*(Brray+k)=*(Brray+k+1);
*(Brray+k+1)=temp;
}
}
}
}
}
By
*(*(ArrayPtr +i)+j)=rand()%55+1;
it seems you want
ArrayPtr[i][j] = (rand() % 55) + 1;
You can try something along the line of
int const offset = AS * i + j;
int const elem = (rand() % 55) + 1;
*(ArrayPtr + offset) = elem;
Your function signature is:
void FillingRandomly(int *ArrayPtr)
where you are telling to compiler that you are passing a simple pointer, but in the line:
*(*(ArrayPtr +i)+j)=rand()%55+1;
you are doing a double derreference, which is illegal and causing the compiler to complain
COMPLEMENT
I was seeing the comments in the other answer and, as what I need to write is bigger than the reserved commentary space, I decided to complement my own answer.
You defined Array as:
int Array[AS][AS];
Indeed, what you are doing is a promise to compiler that you will use Array as defined, but the compiler doesn't believe in you too much, so that any time you use Array the compiler will make sure that it is being used as declared.
The problem arises when you declare your FillingRandomly function. Here you are broking your promise and are trying to use Array by declaring a differente type. Note how you declare your function:
void FillingRandomly(int *ArrayPtr)
Due the fact that c++ supports function overloading, the compiler doesn't warn you until it initiate the linking phase, when it is unable to find a function whose signature is:
void FillingRandomly(int ArrayPtr[][AS])
note that both are different.
Once you are a beginner, the best way to keep your programs correctly is to keep your promise immutable. Bellow I show you a piece of your own code, correcting those issues for FillingRandomly function (you have to correct it for the others functions too):
const int AS = 6;
void FillingRandomly(int [][AS]); // Note that I've changed your prototype here
....
void FillingRandomly(int ArrayPtr[][AS]) // Keep your function signature the same as your prototype signature
{
for(int i=0;i<AS;i++)
{
for (int j=0;j<AS;j++)
{
ArrayPtr[i][j]=rand()%55+1; // Note how ArrayPtr is being used exactly as your promised early
}
}
}
#include <iostream>
#include <vector>
using namespace std;
class PerformSort
{
public:
const vector<int> * p;
vector<int>& getElements(int);
vector<int>& sortArray(vector<int>&);
void printer(vector<int>&);
}firstSort;
vector<int>& PerformSort::getElements (int num)
{
vector<int> elements(num);
for (int i = 0; i < num; i++)
{
cout << "Enter elements into the array: ";
cin >> elements[i];
}
p = &elements;
return p;
}
vector<int>& PerformSort::sortArray (vector<int>& vector)
{
int holder, min;
for (int i = 0; i < (sizeof(vector) - 1); i++)
{
min = i;
for (int j = (i + 1); j < sizeof(vector); j++)
{
if (vector[j] < vector[min])
{
min = j;
}
}
if (min != i)
{
holder = vector[i];
vector[i] = vector[min];
vector[min] = holder;
}
}
return vector;
}
void PerformSort::printer(vector<int>& vector2)
{
for (int i = 0; i < sizeof(vector2); i++)
{
cout << vector2[i] << " ";
}
}
int main ()
{
int numberOfTimes;
cin >> numberOfTimes;
firstSort.printer(firstSort.sortArray(firstSort.getElements(numberOfTimes)));
return 0;
}
This returns the error: "invalid initialization of reference of type from expression of type". My first approach to create a SelectionSort algorithm was to try passing the vector by value (stupidly). After this I started to use pointers instead, after some research. However, this resulted in the aforementioned error. Declaring everything as constant does not seem to resolve the underlying error, despite how, if I understand things correctly, the error lies with temporary references being passed where constant ones are required. Any thoughts on how I might achieve this passing and returning of vectors? (I come from a Java background and am just beginning C++, so forgive me if I have made any obvious errors with regards to the pointers).
Return it by value:
vector<int> PerformSort::getElements (int num)
{
vector<int> elements(num);
for (int i = 0; i < num; i++)
{
cout << "Enter elements into the array: ";
cin >> elements[i];
}
return elements;
}
This will also let you get rid of p, which is a huge can of worms in its own right.
Finally, I notice that you use sizeof(vector) in quite a few places. This won't give you the number of elements in the vector; use vector.size() instead.
Rename the variable vector to something else:
vector<int>& PerformSort::sortArray (vector<int>& wayBetterName)
&
return wayBetterName;
What urged you to name a variable the same as a type?
There's many more other issues with the code.
You don't need pointers, you don't need the references, plus you're better off just using std::sort.
I am trying to write my own bubble sort algorithm as an exercise. I do not understand the two error messages. Can anyone point out the problem with my code?
// Bubble sort algorithm
#include <iostream>
#include <iomanip>
using namespace std;
void bubbleSort(int array[], int arraySize); // bubbleSort prototype
int main(void)
{
const int arraySize = 10;
int array[arraySize] = {2,3,6,5,7,8,9,3,7,4};
cout << "Unsorted: ";
for(int i = 0; i < arraySize; ++i)
cout << setw(5) << array[i];
cout << "Sorted: " << bubbleSort(array, arraySize);
}
void bubbleSort(int array[], int arraySize)
{
const int max = arraySize;
int swap = 0;
for(int i = 0; i < max; ++i)
{
if(array[i] > array[i + 1])
{
swap = array[i + 1];
array[i + 1] = array[i];
array[i] = swap;
}
else
break;
}
}
I see that you are using
using namespace std;
So when you type
array[i] = swap;
The compiler cannot disambiguate whether you are referring to the std::swap function or your int swap variable. In fact it looks like it assumed you were referring to the function and tried to somehow convert it to type int. Try renaming your variable to something else.
In general, try to stay away from using directives, to avoid name collisions like this.
array[i] = swap;
This line is causing problem. It is better to change the name of swap local variable, as there exists already a function with same name, in std namespace which is brought into scope by the line using namespace std; which is to be avoided, anyway.
I would also suggest you to declare the variable, inside the if-block where it is actually used:
if(array[i] > array[i + 1])
{
//declare temp here where it is actually used!
int temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
}
Best practice: reduce the scope local variables by delaying their declarations, which means declare them where they are actually used. Do not declare them in the beginning of the function.
Another way to fix the problem in your code is to give the compiler a context which you can by doing this (though I wouldn't suggest this solution; it is just for you to know):
array[i] = (int)swap; //giving compiler contextual type information
When you cast swap to int, the compiler can know that swap refers to the local variable, not the function which is defined in std namespace.
cout << "Sorted: " << bubbleSort(array, arraySize);
The return type of the function is void. There is nothing to print for. If you need to print the sorted array, you need to iterate over the array elements after the function call.