Error: No Matching function to call to 'online' - c++

I know this is probably a really simple fix, but I'm having trouble finding what my error is, and none of the posts I've checked online have been able to help me. I get the error on the cout lines. Here's the code:
#include <iostream>
bool online(int a, int network[a][a]) {
/*post condition: returns true if every switch in a network is of even degree. Otherwise, returns false.*/
int switches;
for(int x=0; x < a; x++) {
switches = 0;
for(int y=0; y < a; y++)
if(network[x][y])
switches += 1;
if(switches & 1)
return 0;
}
return 1;
}
int main() {
int arrayOne[6][6] =
{
{0,1,1,0,0,0},
{1,0,0,1,0,0},
{1,0,0,1,0,0},
{0,1,1,0,1,1},
{0,0,0,1,0,1},
{0,0,0,1,1,0}
};
int arrayTwo[8][8] =
{
{0,1,1,0,0,0,0,0},
{1,0,0,1,0,0,0,0},
{1,0,0,1,0,0,0,0},
{0,1,1,0,1,0,0,0},
{0,0,0,1,0,1,1,0},
{0,0,0,0,1,0,0,1},
{0,0,0,0,1,0,0,1},
{0,0,0,0,0,1,1,0}
};
std::cout << online(6, arrayOne) << std::endl;
std::cout << online(8, arrayTwo) << std::endl;
}

For C99 (which supports variable length arrays), there is no <iostream>. Make sure you are compiling the program as C and not C++, and then use <stdio.h> instead, and include <stdbool.h>.
printf("%d\n", online(6, arrayOne));
printf("%d\n", online(8, arrayTwo));
For C++, variable length arrays may not be supported for your compiler. You should use a template instead for online().
template <unsigned a>
bool online(int, int (&network)[a][a]) {
//...
}

Related

C++ Segmentation fault while dereferencing a void pointer to a vector

#include <iostream>
#include <vector>
#include <mutex>
struct STRU_Msg
{
std::string name;
void *vpData;
};
class CMSG
{
public:
template <typename T>
int miRegister(std::string name)
{
STRU_Msg msg;
msg.name = name;
msg.vpData = malloc(sizeof(T));
msgtable.push_back(msg);
std::cout << "registeratio ok\n";
return 0;
}
template <typename T>
int miPublish(std::string name, T tData)
{
for (int i = 0; i < msgtable.size(); i++)
{
if (!name.compare(msgtable[i].name))
{
(*(T *)msgtable[i].vpData) = tData;
std::cout << "SUccess!\n";
return 0;
}
else
{
std::cout << "cannot find\n";
return 0;
}
}
}
private:
std::vector<STRU_Msg> msgtable;
};
int main()
{
CMSG message;
std::string fancyname = "xxx";
std::vector<float> v;
// message.miRegister< std::vector<float> >(fancyname);
// for (int i = 0; i < 1000; i++)
// {
// v.push_back(i);
// }
// std::cout << "v[0]: " << v[0] << ", v[-1]: " << v[v.size()-1] << '\n';
// message.miPublish< std::vector<float> >(fancyname, v);
for (int i = 0; i < 1000; i++)
{
v.push_back(i);
}
std::cout << "v[0]: " << v[0] << ", v[-1]: " << v[v.size()-1] << '\n';
message.miRegister< std::vector<float> >(fancyname);
message.miPublish< std::vector<float> >(fancyname, v);
return 0;
}
What I want to achieve is to write a simple publish/subscribe (like ROS) system, I use void pointer so that it works for all data type. This is the simplified code.
If I publish an int, it works fine, but what really confuse me are:
If I pass a long vector (like this code), it gave me the
"segmentation fault (core dump)" error.
If I define the vector between "register" and "publish" (i.e. like
the commented part), this error goes away.
If I use a shorter vector, like size of 10, no matter where I define
it, my code run smoothly.
I use g++ in Linux.
Please help me fix my code and explain why above behaviors will happen, thanks in ahead!
You cannot copy std::vector or any other non-trivial type like that. Before you do anything (even assignment-to) with such an object, you need to construct it using a constructor and placement new.
A way to do this would be
new(msgtable[i].vpData) T;
Do this in the register function.
Then you can assign a value as you do.
Still better, do not use malloc at all, allocate your object with (normal, non-placement) new.
I however strongly suggest ditching void* and moving to a template based implementation of STRU_Msg. If you don't feel like reinventing the wheel, just use std::any.

C++ struct behavior

I'm trying to improve my knowledge of the C++ language and am making a stack of stacks. Below is a very short example of my question: why do I have to directly access the members of the struct in order to change them instead of using functions to do that? If anyone knows why this happens a answer is very appreciated! Thanks
#include <iostream>
#include <vector>
using namespace std;
struct Stack {
int N;
vector<int> stack;
int len() { return stack.size(); }
void add(int N) { stack.push_back(N); }
};
struct Stacks {
vector<Stack> stacks;
Stack getStackAtIndex(int i) { return stacks[i]; }
void addStack(Stack stack) { stacks.push_back(stack); }
void printStacks() {
cout << "Printing stacks" << endl;
for (int i = 0; i < stacks.size(); i++) {
cout << "Stack #" << i << ": ";
for (int j = 0; j < stacks[i].len(); j++) {
cout << stacks[i].stack[j];
if (j != stacks[i].len()-1) cout << " -> ";
}
cout << endl;
}
}
};
int main() {
Stacks stacks;
Stack stack;
stack.add(1);
stacks.addStack(stack);
// This does not work:
// stacks.getStackAtIndex(0).add(2);
// This works:
stacks.stacks[0].stack.push_back(2);
stacks.printStacks();
return 0;
}
stacks.getStackAtIndex(0)
returns a copy of the first Stack, while
stacks.stacks[0]
returns a reference to it. (c.f. std::vector::operator[]).
You can fix this by changing the return type of getStackAtIndex to a reference of Stack:
Stack& getStackAtIndex(int i) {
return stacks[i];
}
You are returning a copy of the stack at [i] when you call
Stack Stacks::getStackAtIndex(int i);
this means you aren't actually operating on the stack at that index but a completely new one that is constructed by copying the data from the stack you want. Just change the return value from
Stack
to
Stack&
Also try not to use namespace std, you will be surprised how many things you use are actually in that namespace. It may overwhelm you if you are ever forced to avoid using it.
Additionally i have noticed you used
int N;
as both a data member in Stack and a parameter in
void Stack::add(int);
i would change this.

c++ program crashes before main

When I run my code below, the program crashes and the compiler message is Segmentation fault. I've searched for bugs in my code but I can't find any. My program doesn't even seem to enter main(), because I've tried using 'cout' to see where it crashes but I get no output, even when 'cout'-ing immedeately after main starts. Here is the code. Can someone tell me what the problem is?
#include <cmath>
#include <stdio.h>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct edge_t
{
int a,b,w;
};
bool comp(edge_t a, edge_t b)
{
if(a.w < b.w)
return true;
return false;
}
vector<int> parent;
int find_parent(int x)
{
if(parent[x] == x)
return x;
parent[x] = find_parent(parent[x]);
return parent[x];
}
void join(int a,int b)
{
parent[find_parent(a)] = find_parent(b);
return;
}
int mst(vector<edge_t> v)
{
sort(v.begin() , v.end() , comp);
for(int i=0;i<v.size();++i)
parent[i] = i;
int sum = 0;
for(int i=0;i<v.size();++i)
{
if(find_parent(v[i].a) != find_parent(v[i].b))
{
join(v[i].a, v[i].b);
sum += v[i].w;
}
}
return sum;
}
int main() {
cout<<"Hello?\n"; ///does not display anything QQ
int n,m;
scanf("%d %d",&n,&m);
parent.resize(n);
int p,q,r;
vector<edge_t> edges;
int s =0;
for(int i=0;i<m;++i)
{
scanf("%d %d %d",&p,&q,&r);
edge_t tmp;
tmp.a = p;
tmp.b = q;
tmp.w = r;
s+=r;
edges.push_back(tmp);
}
printf("%d\n", s - mst(edges));
return 0;
}
I'm using the online ide on hackerrank.com (I'm practising problems there).
Inside your mst function
for (int i = 0; i<v.size(); ++i)
parent[i] = i;
This assumes that parent has the same or more elements that v, and if that's not the case, your program crashes.
In the same function, you are calling find_parent and you haven't verified that a & b are lower than parent.size(), which would be fine if you checked that in your find_parent function, but you don't check it there either.
if (find_parent(v[i].a) != find_parent(v[i].b))
{
join(v[i].a, v[i].b);
sum += v[i].w;
}
Therefore, if find_parent gets invalid input, your program crashes
int find_parent(int x)
{
if (parent[x] == x)
return x;
}
Depending on your compilation environment if you have an instruction set enabled that your system does not support (e.g. AVX) crashes can occur prior to main (I have seen this happen on Windows with VC++). Try compiling with all optimisations switched off, for an "ancient" target architecture.
Depending on your platform, this could also be due to shared libraries not being found, although this seems less likely.
EDIT: Deleted the bit about cout since you have a end line character and main. That was an off thought.

Same variable for different datatypes?

I have to call one simple functions with different datatypes in c++. eg,
void Test(enum value)
{
int x;
float y; // etc
if(value == INT)
{
// do some operation on x
}
else if(value == float)
{
// do SAME operation on y
}
else if(value == short)
{
// AGAIN SAME operation on short variable
}
.
.
.
}
Thus I want to eliminate the repetitive code for different datatypes ...
So , I tried to use macro ,depending on values of enum, to define same variable for different datatypes .. but then not able to differentiate between the MACROS
e.g.
void Test(enum value)
{
#if INT
typedef int datatype;
#elif FLOAT
typedef float datatype;
.
.
.
#endif
datatype x;
// Do operation on same variable
}
But now every time the first condition #if INT is getting true.
I tried to set different values of macro to differentiate but not working :(
Can anyone help me achieve the above thing.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//type generic method definition using templates
template <typename T>
void display(T arr[], int size) {
cout << "inside display " << endl;
for (int i= 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int a[10];
string s[10];
double d[10];
for (int i = 0; i < 10; i++) {
a[i] = i;
d[i] = i + 0.1;
stringstream std;
std << "string - "<< i;
s[i] = std.str();
}
display(a, 10); //calling for integer array
display(s, 10); // calling for string array
display(d, 10); // calling for double array
return 0;
}
If you really want your function to be generic, template is the way to go. Above is the way to do and call the method from main method. This might be of some help for you to reuse a function for different types. Pick up any tutorial or C++ books for complete understanding on templates and get a grip of the full concepts. Cheers.
You can use templates to achieve you purpose.
Simply write a template function which take the value in the function argument which is of generic type and put the operational logic inside it. Now call the function with different data types.
I advice you to use function overloading:
void foo(int arg) { /* ... */ }
void foo(long arg) { /* ... */ }
void foo(float arg) { /* ... */ }
Supposing you want do the same operation with integer and long types you can eliminate the code repetition in this way:
void foo(long arg) { /* ... */ }
void foo(int arg) { foo((long) arg); }

C++: How do you create a return function that returns a vector/array?

This is the motivation behind the code. There is a boy named Bob and its his birthday today. He invites 50 friends over but not all of his friends want to buy him gifts. Bob is presented with 50 presents, though some of them are empty. His good friends tell him to close every 2nd box. For every third box, he is supposed to change every closed to open and every open to closed. He continues to do this for every n-th box where n is less than 50. The open boxes in the end will have the presents.
This is supposed to assist me in figuring out a problem for my math class, but I am not aware of all the complicated aspects of C++ programming. I want my string getValue(vector &arr) to return an array/vector. This code doesn't compile but it shows what I'm trying to do.
#include <iostream>
#include <vector>
#include<algorithm>
using namespace std;
string getValue(vector<string> &arr);
int main()
{
vector<string> myArr(2);
vector<string> newArr(2);
for(int i=2; i <= 50; i++)
{
if(i%2==0)
{
myArr.push_back("close");
}
else
{
myArr.push_back("open");
}
}
newArr = getValue(myArr);
for(int i=2; i <=50; i++)
{
cout << i << " " << newArr[i] << endl;
}
}
string getValue(vector<string> &arr)
{
for(int i=2; i <=50; i++)
{
if(arr[i]=="close")
{
arr[i]="open";
}
else if(arr[i]=="open")
{
arr[i]="close";
}
}
return arr;
}
You can't make your string getValue(vector<string> &arr) return an array/vector. It can only return a string. If you want a function to return an array/vector, then you have to say so in the function signature.
You're passing the vector into getValue() by reference, which means changes you make to it in that function will affect the original (in other words, you're not operating on a copy of the vector - you're actually operating on the vector).
So you don't need to return anything from getValue() - just make it void and it should do what you want.
string getValue(vector &arr) - the return type is string, not vector. You need to change its return type or set it to none.
PS:
newArr = getValue(myArr);
it's behind the SCOPE and it's wrongly positioned...
damn, third PS, wrong code rules are assigned
For the syntax part :-
The return type of the function is a string. Change it to vector for
your function to work properly.
You can simply declare the vectors globally. This will eliminate the
need to pass it to the function as well as return it.
For the logic part :-
Your question says that Bob toggles every third box but in your program Bob is changing every box to open if it is closed and every box to close if it is open. If what you wrote in the question is correct your code should be like this.
#include <iostream>
#include <vector>
using namespace std;
void getValue();
vector<string> myArr(2);
int main()
{
for(int i=2; i <= 50; i++)
{
if(i%2==0)
{
myArr.push_back("close");
}
else
{
myArr.push_back("open");
}
}
getValue();
for(int i=2; i <=50; i++)
{
cout << i << " " << myArr[i] << endl;
}
}
void getValue()
{
for(int i=3; i <=50; i+=3)
{
if(myArr[i]=="close")
{
myArr[i]="open";
}
else if(myArr[i]=="open")
{
myArr[i]="close";
}
}
}