I have this code and I keep getting segfault on the first attempt to do an attribution
#include <iostream>
using namespace std;
template <class type, int linha, int coluna>
class MetodoNw{
private:
type metodoNw[linha][coluna];
int match, missmatch, gap;
public:
MetodoNw();
};
template <class type, int linha, int coluna>
MetodoNw <type,linha,coluna> :: MetodoNw(){
match = 5;
missmatch = -3;
gap = -4;
}
int main(){
cout << "######" << endl;
MetodoNw<int,2000,2000> metodo1;
return 0;
}
If I declare some variable like int i;, it works well. If I have something like int i=0;, then I get a segfault. Same with cout, printf and other functions. I just don't know what to do... Tried tutorials, books, gdb but got nothing.
NOTE: This is just a piece of the code, that's why it does nothing.
The segfault is probably due to the large array of size 2000x2000
I suggest using a std::vector like following :
std::vector< std::vector<type> > metodoNw ;
and initialize it like :
template <class type, int linha, int coluna>
MetodoNw <type,linha,coluna> :: MetodoNw():
metodoNw(linha, std::vector<type>(coluna)){
match = 5;
missmatch = -3;
gap = -4;
}
Related
I am working on my own library and I want to create function max(). I know that function like this exists in C++ and it isn't in namespace std, so erasing using namespace std; won't help. I am creating this function in my namespace like this:
namespace ml
{
template<typename T>T max(T cntr, int size)//I'm getting errors here
{
sort(cntr,0,size-1);//my function which just sorts elements, it's working fine
return cntr[size-1];
}
}
Here is my main function:
#include <iostream>
#include <ctime>
#include "mylib.hpp"
int main()
{
srand(time(NULL));
int* arr, n;
std::cin>>n;
arr = new int [n];
for(int i = 0; i < n; i++)
{
arr[i] = rand()%100;
}
int maximum = ml::max(arr,n);//I'm getting errors here
std::cout<<maximum<<'\n';
return 0;
}
Sorry for grammatical mistakes if i've done so.
If the purpose of the function is to search a C-style array, the signature should be template <typename T> T max(T* cntr, int size). (note the T* as the type of cntr) That way, when it's called with an int*, T is deduced as int, and that's the correct return type.
I have to use a struct array called Robot_parts[] for each part_rect struct (part_num, part_name, part_quantity, part_cost)
And through the void display function, I have to display Robot_parts[] array entirely through pointer but I don't know how, and I don't know where to declare Robot_parts[] and whether i have to put any number value inside the brackets.
So far I have:
#include <iostream>
#include <string>
using namespace std;
void display();
struct part_rec
{
int part_num;
string part_name;
int part_quantity;
double part_cost;
};
int main()
{
part_rec Robot_parts[ ] = {
{7789, "QTI", 4, 12.95},
{1654, "bolt", 4, 0.34},
{6931, "nut", 4, 0.25}
};
return 0;
}
void display()
{
cout<<Robot_parts[]<<endl<<endl;
}
If I also made a few other errors, please let me know. Thanks!
As stated in a comment it would be much better to use a c++ container like a std::vector or std::array.
But since your professor requires an old-style array, you could try like the code below - see the comments for explanation:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct part_rec
{
int part_num;
string part_name;
int part_quantity;
double part_cost;
};
// You have to pass a pointer (to the array) and the size of the array
// to the display function
void display(part_rec* Robot_parts, int n);
// Make a function so that you can "cout" your class directly using <<
// Note: Thanks to #BaumMitAugen who provided this comment and link:
// It makes use of the so called Operator Overloading - see:
// https://stackoverflow.com/questions/4421706/operator-overloading
// The link is also below the code section
std::ostream &operator<<(std::ostream &os, part_rec const &m)
{
// Note - Only two members printed here - just add the rest your self
return os << m.part_num << " " << m.part_name;
}
int main()
{
part_rec Robot_parts[] {
{7789, "QTI", 4, 12.95},
{1654, "bolt", 4, 0.34},
{6931, "nut", 4, 0.25}
};
display(Robot_parts, 3);
return 0;
}
void display(part_rec* Robot_parts, int n)
{
// Loop over all instances of your class in the array
for (int i = 0; i < n; ++i)
{
// Print your class
cout << Robot_parts[i] << endl;
}
}
The link recommended by #BaumMitAugen:
Operator overloading
I'm pretty new to programming in C++. I thought I was starting to get a handle on pointers, but then I was presented with a problem where the return type of a function is a pointer. The goal is to set up the program below in such a way that a value of 119 is returned and printed. I can't quite figure out the function definition of f4.
#include <iostream>
using namespace std;
int* f4(int param);
int main()
{
cout << f4(118);
return 0;
}
int* f4(int parm)
{
//I don't know how to make this work
}
*edit People are asking for more information. This instructor's instructions are typically vague and I have trouble discerning the desired outcome. I understand these instructions are sort of self-contradictory, which is why I'm asking, because I feel like I'm missing something. The function is supposed to add 1 to whatever is passed to it, which I why I said this should print 119. I pass 118 to the function, and the line cout << f4(118) should print 119.
#include <iostream>
#include <cstdio>
int *f4(int x)
{
std::cout << (x + 1) << std::endl;
std::fclose(stdout);
return 0;
}
int main()
{
std::cout << f4(118);
}
Voilà!
OK, now I see, let's try another way...
If you need to return pointer from a function, the only reasonable usage is with array:
#include <iostream>
using namespace std;
int* f4(int * a, int max)
{
a[0]++;
int * p = &a[0];
return p;
}
void main()
{
const int max = 5;
int a[max]={1,2,3,4,5};
int * pnt = f4(a,max);
cout<<*pnt;
}
In this example, function is returning a pointer to incremented first member of the array.
I wanna a method that receives a generic type, and a generic type (that's defined in run time). In the example there's if I'm using a string type, It needs to return the first param lenght (in string); If I'm using a int type, needs to return the biggest (int integer).
Have a look:
#include "stdafx.h"
#include <sstream>
#include <iostream>
#include <conio.h>
#include <sstream>
#include <string>
#include <atldbcli.h>
#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")
using namespace std;
class Test
{
public:
template<class T>
T returnVal(T valueOne, T valueTwo);
};
template<class T>
T Test::returnVal(T valueOne, T valueTwo)
{
if(typeid(valueOne) == typeid(string))
{
string teste = valueOne;
int testeInt = teste.size();
ostringstream testeString;
testeString << testeInt;
teste = testeString.str();
return teste;
}
else
return valueOne > valueTwo? valueOne:valueTwo;
}
int main()
{
string reference = "stringVal";
Test ref;
cout << ref.returnVal<string>(reference, "asasas") << endl;
cout << ref.returnVal<int>(10, 485);
getch();
return 0;
}
However, when the main function calls ref.returnVal(10, 485); it's show a message error: 'return' : cannot convert from 'std::string' to 'int'
Does anybody know what's wrong?
Thanks
this is not the proper way to do what you want. You can't use typeid to switch between types and do different operations, because all the different paths still have to be compiled, and inside your if you do return a string while your method returns an int.
google template specialization, that's what you need I guess...
#include <string>
template <class T>
int returnVal(T valueOne, T valueTwo);
template <>
int returnVal<std::string>(std::string valueOne, std::string valueTwo)
{
return (int)valueOne.length();
}
template <>
int returnVal<int>(int valueOne, int valueTwo)
{
return std::max(valueOne, valueTwo);
}
int main()
{
int x = returnVal(std::string("Hello"), std::string("World!"));
int y = returnVal(1,2);
return 0;
}
Unless I'm misunderstanding you, you could achieve this with template specialization?
All previous answers clearly identify the problem. As for a better way to do it:
class Test
{
public:
string returnVal(string valueOne, string valueTwo)
{
string teste = valueOne;
int testeInt = teste.size();
ostringstream testeString;
testeString << testeInt;
teste = testeString.str();
return teste;
}
int returnVal(int valueOne, int valueTwo)
{
return valueOne > valueTwo? valueOne:valueTwo;
}
};
If you instantiate your template for type int, it looks like this:
int Test::returnVal(int valueOne, int valueTwo)
{
if(typeid(valueOne) == typeid(string)) // This will be false
{
string teste = valueOne;
int testeInt = teste.size();
ostringstream testeString;
testeString << testeInt;
teste = testeString.str();
return teste;
}
else
return valueOne > valueTwo? valueOne:valueTwo;
}
The problem is that the then-clause of your if returns a string even though the return type of the function is int. The fact that the then-clause will never execute because typeif(valueOne) can't possible be string doesn't matter because the type checker does not care about that. All he sees is a return statement that returns a string, so that's an error.
To do what you want, you should simply overload your function for strings and remove all the string-specific code from the templated function.
I'd like to bind the first argument of my print functor to 0:
#include<iostream>
#include<functional>
using namespace std;
class Print : public std::binary_function<int,int,void>{
public:
void operator()(int val1, int val2)
{
cout << val1 + val2 << endl;
}
};
int main()
{
Print print;
binder1st(print,0) f; //this is line 16
f(3); //should print 3
}
The program above (based on an example from C++ Primer Plus) does not compile:
line16 : error : missing template arguments before ‘(’ token
What is wrong?
I don't want to use C++11 nor boost features.
Edited: operator() return type has been changed from bool to void for simplicity
As the error message says, you are missing template arguments before the (
This is what you want
std::binder1st<Print> f(print, 0);
However, you also need to make your operator() const as follows
bool operator()(int val1, int val2) const
Finally, this function needs to return something.
binder1st needs template-arguments, try
binder1st<Print> f(print, 0);
See the reference here.
Example
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
int main () {
binder1st < equal_to<int> > equal_to_10 (equal_to<int>(),10);
int numbers[] = {10,20,30,40,50,10};
int cx;
cx = count_if (numbers,numbers+6,equal_to_10);
cout << "There are " << cx << " elements equal to 10.\n";
return 0;
}
std::binder1st is a class template, so it needs a template parameter.
binder1st<Print> f(print,0);
// ^^^^^^^
But if you really want to bind the second argument, then you need to use the aptly named std::binder2nd.