Static function call not working (C++) - c++

For some reason the following code gives a compiler error in DevC++: [Error] cannot declare member function 'static double* Sort::bubbleSort(double*, int)' to have static linkage [-fpermissive]
BubbleSort.cpp:
#include <iostream>
#include "Sort.h"
int main(int argc, char** argv) {
double list[] = {4.0, 4.5, 3.2, 10.3, 2.1, 1.6, 8.3, 3.4, 2.1, 20.1};
int size = 10;
double* sortedList = Sort::bubbleSort(list, size);
return 0;
}
Sort.h:
class Sort
{
public:
static double* bubbleSort (double list[], int size);
}
;
Sort.cpp:
#include "Sort.h"
#include <algorithm> // std::swap
static double* Sort::bubbleSort (double list[], int size)
{
bool changed = true;
do
{
changed = false;
for (int j = 0; j < size - 1; j++)
{
if (list[j] > list[j +1])
{
std::swap(list[j], list[j + 1]);
changed = true;
}
}
}
while (changed);
return list; // return pointer to list array
}
Essentially, I'm trying to call the bubbleSort function without creating a Sort object. The code works fine if I create an object first.
What could be causing the error?
Thanks for any suggestions.

The static modifier goes in Sort.h, but not in Sort.cpp.
That's because it means two different things in the two contexts.
When used inside a class declaration, static indicates that the method it refers to is a class method (that you should use without a object reference), rather than a instance method (that you need a object reference to invoke).
When used inside the implementation file (i.e. outside of a class declaration), it indicates that the method it refers to should have static linkage, which means it should not be made visible from outside the object file that contains it. From an object oriented point of view, these functions are private to the file that contains them. It's pretty obvious that this cannot work if other files (which are using your class) should access the method.

Remove the static keyword in the .cpp file. Also, you do not need to return the pointer list since only the contents of the array change change, not the array itself. You can keep using the pointer that you put into the function. sortedList will point to the same memory location as list at the end of your main function.

If all that is in your Sort class is this one static member, there is absolutely no need for a class.
double* bubbleSort (double list[], int size)
{
bool changed = true;
do
{
changed = false;
for (int j = 0; j < size - 1; j++)
{
if (list[j] > list[j +1])
{
std::swap(list[j], list[j + 1]);
changed = true;
}
}
}
while (changed);
return list; // return pointer to list array
}
Additionally, there is no need to return the pointer to the list because you are modifying the list as you sort it (double list[] is the same as double* list, and since you are changing the values in your routine, the pointer to the first element will still be the same, but the values in the array will be swapped around).
void bubbleSort (double list[], int size)
{
bool changed = true;
do
{
changed = false;
for (int j = 0; j < size - 1; j++)
{
if (list[j] > list[j +1])
{
std::swap(list[j], list[j + 1]);
changed = true;
}
}
}
while (changed);
}

You should make the function free-standing and if you need a class method, make it call the free-standing function with the correct parameters.

Related

Difficulty in passing function pointer of a class member function

In trying to implement a suggested answer here in my own context, I am running into a compilation error.
Consider code:
#include <iostream>
class SIMPLE {
public:
SIMPLE() { for (int i = 0; i < 5; i++) val[i] = 5; };
int retval(int index) { return val[index]; }
private:
int val[5];
};
void print_array_of_length5(int (*fnptr)(int index)){
for (int i = 0; i < 5; i++)
printf("%d ", fnptr(i));
}
int global_array[5] = { 0, 1, 2, 3, 4 };
int global_function(int index){
return global_array[index];
}
int main(){
print_array_of_length5(&global_function);//Works fine.
int (SIMPLE::*p)(int) = &SIMPLE::retval;//Following method suggested in the answer above
class SIMPLE smpl;
print_array_of_length5(smpl.*p);//Compile error: a pointer to a bound function may only be used to call the function
}
The function works when supplied with the address of a global function. It does not work when passed smpl.*p analogous to the method suggested. How should one fix this error?
You need another overload for print_array_of_length5 in order to pass a member function pointer:
template<typename T>
void print_array_of_length5(int (T::*fnptr)(int index), T& obj)
{
for(int i = 0; i < 5; ++i)
{
printf("%d ", (obj.*fnptr)(i));
}
}
int main()
{
SIMPLE smpl;
print_array_of_length5(&SIMPLE::retval, smpl);
}
You can't pass a non-static member function pointer as a regular function pointer. Member functions have access to the this pointer, and the way they get that is via an invisible implicit function parameter. You need to have the object on which to call the function, and the function itself, be bound together, which a function pointer simply can't do.
What we can do is make print_array_of_length5 a function template, and allow it to take any type of callable. That would give you something like this:
template <typename Function>
void print_array_of_length5(Function func){
for (int i = 0; i < 5; i++)
printf("%d ", func(i));
}
To call it with a non-static member function, you can use a lambda expression, or std::bind(), like this:
SIMPLE smpl;
print_array_of_length5([&smpl](int foo){ return smpl.retval(foo); });
using namespace std::placeholders;
SIMPLE smpl;
auto func = std::bind(&SIMPLE::retval, &smpl, _1);
print_array_of_length5(func);

non static member in static cpp

The below program is giving as error invalid use of mep in static function
When i declaring mep also as static giving as error undefined reference to mep
when i am declaring comp as non static and also mep as non static
i am giving error invalid use of non static member in sort
what should I do I have to submit this solution class in leetcode?
class Solution {
public:
unordered_map<char,int>mep;
static bool comp(string a,string b){
int n = min(a.size(),b.size());
for(int i=0;i<n;i++){
int diff = mep[a[i]]-mep[b[i]];
if(diff<0)return false;
if(diff>0)return true;
}
return true;
}
bool isAlienSorted(vector<string>& words, string order) {
for(int i=0;i<order.size();i++){
mep[order[i]]=i;
}
vector<string>temp;
temp=words;
sort(temp.begin(),temp.end(),comp);
return temp==words;
}
};
I know other approach for comparator can be lambda function , which one is efficient the above or lambda?
Declare a custom comparator type, using that as the groundwork for your eventual comparator argument for std::sort. In the process, you gain re-usability; something sorely lacking with a static implementation.
class Solution {
public:
struct Comp
{
unordered_map<char, int> mep;
bool operator()(std::string const& a, std::string const& b)
{
size_t n = min(a.size(), b.size());
for (size_t i = 0; i<n; i++) {
int diff = mep[a[i]] - mep[b[i]];
if (diff<0)
return false;
if (diff>0)
return true;
}
return true;
}
};
bool isAlienSorted(vector<string> const& words, string order)
{
Comp comp;
for (int i = 0; i<order.size(); i++) {
comp.mep[order[i]] = i;
}
vector<string>temp = words;
sort(temp.begin(), temp.end(), comp);
return temp == words;
}
};
Regarding your last question, compile to optimized code and measure with a sound benchmark (not as easy as it sounds). If there even is a noticeable difference, my money is on the lambda (which is pretty much what we have above anyway) for no other reason than because of the stronger likelihood the compiler will inline the comparator within the std::sort expansion.
You cannot access a non-static member variable inside a static member function. In addition, you should define the static member variables outside of the class as well. The below code works fine, without any compilation warnings and errors.
#include <string>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
static unordered_map<char, int> mep;
static bool comp(string a, string b) {
int n = min(a.size(), b.size());
for (int i = 0; i < n; i++) {
int diff = mep[a[i]] - mep[b[i]];
if (diff < 0)return false;
if (diff > 0)return true;
}
return true;
}
bool isAlienSorted(vector<string>& words, string order) {
for (size_t i = 0; i < order.size(); i++) {
mep[order[i]] = i;
}
vector<string> temp;
temp = words;
sort(temp.begin(), temp.end(), comp);
return temp == words;
}
};
unordered_map<char, int> Solution::mep;
void main()
{
}
The below program is giving as error invalid use of mep in static
function
Because static function (comp) in C++ cannot access non-static variable (mep)
When i declaring mep also as static giving as error undefined
reference to mep
A static variable of a class need to have a definition not just declaration. So give mep an inittialize.
You can pass the unordered_map as a parameter to the comp function. That way you won't be accessing the non-static object but it will require you to write your own sorting algorithm:
static bool comp(const unordered_map<char, int>& map_mep, string a, string b)
{
int n = min(a.size(), b.size());
for (int i = 0; i < n; i++) {
// this way there is no non-static involved
int diff = map_mep[a[i]] - map_mep[b[i]];
if (diff < 0)return false;
if (diff > 0)return true;
}
return true;
}
Because mep is not a static member of the class a static function cannot see it. You should set mep to be static in order to fix this.

How to declare new private variables from constructor?

I want to pass 2-dimensional arrays with different sizes to my class and store the arrays as private member variables.
When I try to declare the array in the constructor I get an error.
How should I declare a private variable from constructor?
If it is not possible, what else can I do to make my class flexible for different array sizes?
Here is the header file:
#ifndef NUMCPP_H
#define NUMCPP_H
class numcpp
{
public:
numcpp(int *Arr,int *Shape,int Dims);
private:
int *shape;
int dims;
};
#endif
Here is the source file:
#include <iostream>
#include "numcpp.h"
using namespace std;
numcpp::numcpp(int *Arr,int *Shape,int Dims) // *arr points to input array's first element
{
shape = Shape;
dims = Dims;
int i = shape[0];
int j = shape[1];
int numcpp::array[i][j]; // error happens in this line
//assigning input array to our variable
for (int x = 0; x < i; x++)
{
for (int y = 0; y < j; y++)
{
array[x][y] = *(arr + (x * i) + y);
};
};
};
Classes must have a compile time fixed size, so a true flexible array member isn't possible. The best you could do is either:
Templating the class on the array dimensions (compile time chosen fixed size)
Using a dynamically resizable type like std::vector<std::vector<int>> to get something functionally similar (runtime dynamically chosen size); the class itself remains fixed size, with the vector storing the dynamically allocated arrays on the free store (heap).
One implementation approach would look something like this (adding a declaration of std::vector<std::vector<int>> array; in the private section of the class declaration):
// Use initializers to initialize directly instead of default initializing, then replacing
numcpp::numcpp(int *arr,int *Shape,int Dims) : shape(Shape), dims(Dims), array(shape[0], std::vector<int>(shape[1]))
{
int i = shape[0];
int j = shape[1];
for (int c = 0; c < i * j; ++c) {
array[c / j][c % j] = arr[c];
}
};

Organising C++ code

I am looking for some advice on how to organise my C++ code.
I have an int array, side, that I would like to be static in the sense that its value is kept constant between calls. This is because my function foo(), will modify the array side recursively and so I don't want copies to be made of side. Furthermore, the size of side can only be determined at compile time from the size of a vector that is passed into the function bar().
I have thought of the following structure to layout such a problem.
I keep a global int pointer, side, which I can then use to point to the address of my int array and then use the pointer *side within foo to do my modifications.
Please can you give me advise on the layout and organisation of this code? I am quite new to C++ so would appreciate any advice on the below structure.
#include <iostream>
#include <vector>
using namespace std;
int *side;
class A {
public:
int foo(bool);
int bar(vector<int>);
void set_n(int n){ class_n = n;};
private:
int class_n;
};
int A::foo(bool fl)
{
int n = class_n;
for(int i = 0; i < n; i++) {
// modify side[] and then recursively call foo
}
return 0;
}
int A::bar(vector<int> t)
{
int size = t.size();
set_n(size);
int a = foo(true);
int *side_local = new int[size];
for(int i = 0; i < size; i++) {
side_local[i] = 0;
}
side = side_local;
return 0;
}
int main()
{
A a;
vector<int> t = {1, 2, 3};
a.bar(t);
return 0;
}
A recursive call can pass a pointer to itself:
void foo(int *pList)
{
foo(pList); // recursive
}
the same list is then being worked on.
That being said, since foo is inside a class you wouldn't need a global either, but a member variable.
class A
{
int *pMemberList;
...
void foo();
}
now foo can see pMemberList all the time.
BUT ... passing it is probably a better option as in the future your class might house 2 lists that you want to do foo on.

Arguments passing vs. Variable declaration

What's the difference between passing an argument inside a function as a parameter and declaring the argument as a variable inside the function declaration block in function definition?
Example: Make use of my comments to get the gist of the question.
#include<iostream>
int max=0;
int t=0;
class stack
{
int s[10];
public:
void push(int);
void pop();
};
void stack::push(int y) //argument passed inside function parameter
{
if(t<=max);
{
s[t]=y;
t=t+1;
}
else
cout<<"Stack overflow";
}
void stack::pop()
{
int item; //variable declared inside function definition
if(t>=0)
{
t=t-1;
item=s[t+1];
}
}
One difference is that parameters are initialized by the caller but local variables have to be initialized by the function.
int somefunc(int arg)
{
int local = 0;
…
return local + arg;
}
When the function is called:
int x = somefunc(23);
the variable arg in the function is initialized with the value 23 by the calling code. However, the local variable local has to be explicitly initialized (in this case with the = 0; if it was a class type, by an appropriate constructor). Local variables of built-in types such as int that are not explicitly initialized get a quasi-random value.
One difference is in how arrays are interpreted:
// returns nonzero iff array1 equals {1, 2, 3}
int func(int array1[], size_t size1)
{
int array2[] = {1, 2, 3};
return size1 == sizeof(array2) && memcmp(array1, array2, size1) == 0;
}
While array2 is an array of 3 integers, array1 is an array of unknown size, which is why we usually pass a second parameter for the size. This is because of arrays "decay to pointers" when passed into functions like this. You can read about it here: What is array decaying?
There are fancier techniques for dealing with this in C++ using value templates for the array size, but the above is true of C and most C++ code in the wild too.
Other than arrays, C types used in function parameters behave pretty much the same as C types used in local variables.
The arguments is passed by calling that function. so caller decides what should be passed.
functions decides what should it accept.
for example:
main()
{
int i=0;
int k=i;
for (int j=i; j `enter code here`< n; j++)
{
}
}
is same as
main()
{
int i=0,k;
for (int j=k=i; j < n; j++)
{
}
}
but this
main()
{
int i=0,k;
for (int j=i; j < n; j++)
{
k=i;
}
}
is totally different.