How to assign a filename with a pointer one? - c++

I do have a function that I have created with a pointer as an argument.
That argument will be used to save at the end an image.
Every time when I would like to call that function with the desired parameter, I want that the saved image file would be with the specified name. I show you how:
void SaveImage(IplImage *img)
{
...
cvSaveImage("C:/img.png", img);
...
}
when calling the function: SaveImage(image1), I want to have an image on my C:/ whose name is image.png
Can you help me with that?

Apparently, you can't answer this question with the only answer that is actually viable, because you get downvoted...
So, I'll rephrase my answer:
You need to pass two variables to SaveImage:
void SaveImage(const char *name, IplImage *img)
{
...
cvSameImage(name, img);
}
Then your calling code will have to produce the correct name, such as:
SaveImage("c:\image.png", image);
SaveImage("c:\other.png", other);
Now, of course, if all you actually want is a unique name, rather than one that reflects the name of the variable in your code, then there are plenty of other possibilities, such as using a formatted string that contains a serial number, a random number, tmpnam() or other similar schemes.

Related

C++ copy_if lambda capturing std::string

This is a follow up question from here: C++ - Developing own version of std::count_if?
I have the following function:
// vector for storing the file names that contains sound
std::vector<std::string> FilesContainingSound;
void ContainsSound(const std::unique_ptr<Signal>& s)
{
// Open the Wav file
Wav waveFile = Wav("Samples/" + s->filename_);
// Copy the signal that contains the sufficient energy
std::copy_if(waveFile.Signal().begin(), waveFile.Signal().end(),
FilesContainingSound.begin(), [] (const Signal& s) {
// If the energy bin > threshold then store the
// file name inside FilesContaining
}
}
But to me, I only need to capture the string "filename" inside of the lambda expression, because I'll only be working with this. I just need access to the waveFile.Signal() in order to do the analysis.
Anyone have any suggestions?
EDIT:
std::vector<std::string> FilesContainingSound;
std::copy_if(w.Signal().begin(), w.Signal().end(),
FilesContainingSound.begin(), [&] (const std::unique_ptr<Signal>& file) {
// If the energy bin > threshold then store the
// file name inside FilesContaining
});
You seem to be getting different levels of abstraction confused here. If you're going to work with file names, then you basically want something on this order:
std::vector<std::string> input_files;
std::vector<std::string> files_that_contain_sound;
bool file_contains_sound(std::string const &filename) {
Wav waveFile = Wav("Samples/" + filename);
return binned_energy_greater(waveFile, threshold);
}
std::copy_if(input_files.begin(), input_files.end(),
std::back_inserter(files_that_contain_sound),
file_contains_sound);
For the moment I've put the file_contains_sound in a separate function simply to make its type clear -- since you're dealing with file names, it must take a file name as a string, and return a bool indicating whether that file name is one of the group you want in your result set.
In reality, you almost never really want to implement that as an actual function though--you usually want it to be an object of some class that overloads operator() (and a lambda is an easy way to generate a class like that). The type involved must remain the same though: it still needs to take a file name (string) as a parameter, and return a bool to indicate whether that file name is one you want in your result set. Everything dealing with what's inside the file will happen inside of that function (or something it calls).

Dll Plug-in basic questions

For the last couple of days i've been learning C++ to make a dll plug-in for a program.
My objective is to get data(the Flight Plan's to be more precise) from the program and on a first phase save them to a text file(second phase will be connect them with python but for now it's just that).
So in my header file i imported a file with many classes and many functions(which is given by the plugin development guide). The class i'm interested in is the class CAircraftFlightPlan and it has some functions inside like this:
bool IsReceived(void) const;
//-----------------------------------------------------------------
// Return :
// true - if any kind of FL is received from the servers
// false - else
//-----------------------------------------------------------------
const char * GetOrigin ( void ) const ;
//-----------------------------------------------------------------
// Return :
// The origin airport.
//-----------------------------------------------------------------
int GetFinalAltitude ( void ) const ;
//-----------------------------------------------------------------
// Return :
// The final requested altitude.
//-----------------------------------------------------------------
I have many doubts about this, hope you can help:
1-what does it mean having "nameoffuction"(void) const? It receives nothing?how do i call these functions then
2-i do not understand this function "const char * GetOrigin ( void ) const ;",what does it want, a const or a char?
3-The comments below the functions tell that they return this or that. But how do they return that if the function is empty, it's just "int GetFinalAltitude(void) const"...
4-In the source file, i try to call one of the functions to write it to a txt file,how can i do this:
int airplane;
ofstream textfile;
textfile.open("FP.txt");
textfile<<int GetTrueAirspeed("MAH545"); //i know there's an error here, how do i solve it?
textfile.close();
I'm very sorry for asking these (noob i suppose) questions but they are way to specific to search for an answer online(i tried already)
Thank you for the help
Yes, it takes no arguments so you call it like so: nameoffunction()
This also takes no arguments so it is called as GetOrigin(). It returns a pointer to a const char.
As above, the functions take no arguments but do return values.
Delete the int in front of the function call. This should get rid of at least one error.
textfile<< GetTrueAirspeed("MAH545");

Using the same variable as input/output in a function

I'm writing a Qt GUI program in conjuction with OpenCV to create a people tracking application. OpenCV has a lot of functions that take a matrix as input and output, for example a color conversion one:
cvtColor(inputArray src, outputArray dst, int code, int dstCn=0);
Mat is the default matrix class of OpenCV, and assuming I have a Mat object called frame, I would implement the function like this to change its properties:
cvtColor(frame, frame, CV_RGB2HSV,0);
Is there any downside on using the same variable as input and output on any function? or should I create a copy first?
or should I look in every function documentation?
I think it's a personal choice. Here's some personal samples:
Take readonly input, a reference to the output and, after you process the input, push it to the output. Optional error result friendly.
bool function(const type& input, type& output){
output = input;
return true;
}
Take readonly input, assign it to output, change output and return it (C++11 move optimized).
type function(const type& input){
type output = input;
return output;
}
type output = function(input);
Here you force a new copy of the object as the argument and you can use it and return it (C++11 best when you don't want to alter your copy). See also: Want speed, pass by value..
type function(type input){
// modify input
return input;
}
type output = function(input);
Input and output in the same argument. Use with caution. Can return error.
bool function(type& put){
return true;
}
It depends on your design. Don't need errors?... use a movable one. Need errors?... use one that leaves the return value accessible to you. Or, just follow existing practices but know how each can help or penalize your performance like:
// this makes a pointless copy for the input (use const ref here)
bool function(type input, type& output){
output = input;
return true;
}
(Right way is)
bool function(const type& input, type& output){
output = input;
return true;
}
PS: Personal opinion of a self taught C++ dev :)
This is a personal choice. If you don't need the input image later then by all means do it.
I already tried it actually, it works most of times but some other times it works poorly.
it depends on the function you're using.

storing to a map inside a function

I'm trying to write a function that will input information into a map from a text file. My main code goes as follows:
int main(){
typedef map<int,student*> record;
record allstudents;
fileinput("inputtest.txt",allstudents);
//rest of code....
}
where the function 'fileinput' is defined as:
void fileinput(string datafile, record map){
fstream file1(datafile);
if(!file1.good()){
//error code
}
//Pulls information from file
student* S1= new physics(name,ID); //creates a new pointer
//(*S1).printinfo(); //Can print info if required for de-bug
map[ID]=S1; //store to map
entries++; //counts entries read in
}
cout<<"Import complete. "<<entries<<" new students entered."<<endl;
}
When I run this piece of code from a test file, it will read in the data and output it fine if I uncomment (*S1).printinfo(); and will correctly count the number of students that have been read in. However when I come back to my main function and output what is now stored in allstudents there appears to be nothing there?
Why is this occurring and does anybody know the way around this problem? I've cut a lot of code out to try and make it easier to read but if you need to see the rest I can always edit this.
Thanks.
This is because you are passing in map by value. Change the signature of the function to
void fileinput(string datafile, record &map)
Short explanation: when you pass by value, a copy of the argument (map) is made. Inside your function you perform modifications to that copy, but these modifications are lost when the function returns and the copy goes out of scope. They do not automatically propagate back to the "source" object.
For a detailed explanation, see Pass by Reference / Value in C++.
You are passing the map by value, so the function makes it's own copy and your original remains unchanged. Try passing by reference:
void fileinput(string datafile, record& map) { ... }
^ reference!

Trying to pass a pointer as a parameter to a member of fstream that points to a file

/* Thanks to anyone looking at this who might attempt to answer it. I'm really not trying to waste anyone's time here, but I have beat my head on this for about three days. I realize it is probably very simple for someone who understands it. I have tried most every possible combination I can think of and still get compiler errors.
C:\random\RNDNUMTEST.cpp(41) : error C2102: '&' requires l-value
I am trying to pass a pointer as a parameter to a function makeRndmNumber() for the member function fstream.open(). I want to open the file in RNDNUMTEST.cpp and then pass it to makeRndmNumber() so that it can be modified in some way. I have looked online for help, including this website, but I feel like I am overlooking something important or simple or maybe I am just missing the concept altogether.
This isn't for homework, I'm not a college student. Although I did go to school for it, it has been over 10 years since I've done any programming and I never really understood this that well to begin with. Any suggestions would be appreciated.
// These are only excerpts from the actual files.
// RndmNum_Class.h file
typedef void(fstream::*fStream_MPT)(const char*); // fStream_MPT (Member Pointer Type)
class RandomNumber {
public:
RandomNumber();
~RandomNumber() {};
static void loadDigits(double, double, char array[]);
static int getLastNDigits(char array[], int);
static int makeRndmNumber(int, int, fStream_MPT);
};
//*************************************************************8
//RndmNum_Class.cpp file
int RandomNumber::makeRndmNumber(int seed, int _fileSize, fStream_MPT FILE) {
......
}
//**************************************************************/
// RNDNUMTEST.cpp file
#include "RndmNum_Class.h"
int main() {
const char* RNDM_FILE = "c:\\RandomFile.txt";
fstream FStream_Obj;
// FStream_Obj.open(RNDM_FILE);
fStream_MPT FileMembPtr = &FStream_Obj.open(RNDM_FILE);
//fStream_MPT FileMembPtr = &fstream::open;
int seed = 297814;
int size = 20000;
cout << RandomNumber::makeRndmNumber(seed, size, FileMembPtr);
return 0;
}
This: &FStream_Obj.open(RNDM_FILE) is not taking the address of the function, it's trying to take the address of the return value of a call to that function. But that function returns void, hence the error message.
First, change the function definition from typedef void(fstream::*fStream_MPT)(const char*); to typedef void(fstream::*fstream_MPT)(const char*,ios_base::openmode), there is a default parameter you are forgetting.
Change the fStream_MPT FileMembPtr = &FStream_Obj.open(RNDM_FILE); to fStream_MPT FileMembPtr = &fstream::open; as per your comment, and add an additional parameter to makeRndNumber, a pointer to an fstream to operate on.
int RandomNumber::makeRndmNumber(int seed, int _fileSize, fStream_MPT FILE, fstream *file)
{
((*file).*FILE)("ExampleText",ios_base::in | ios_base::out);
}
FILE = fstream::open;
EDIT
This could also be done a little cleaner with std::function objects.
First redefine your type.
typedef std::function<void(const char*)> fStream_MPT;
Then when you assign, be sure to bind your objects.
fStream_MPT FILE = std::bind(&fstream::open,&file,std::placeholders::_1, ios_base::in | ios_base::out);
Then in your function you simply call the function
int RandomNumber::makeRndmNumber(int seed, int _fileSize, fStream_MPT FILE)
{
FILE("Example text");
}
It doesn't make any sense: member function pointers is used so you can apply different member functions somewhere without knowing which exact function is called. It is like passing the function's name around (except that the name is resolved at compile-time). It doesn't seem that this is what you want to do!
Even if you would correctly obtain the function's address (rather than trying to get the address of the result of calling open()), it wouldn't work because std::fstream::open() takes two arguments: the second argument is for the open-mode and it is defaulted to std::ios_base::in | std::ios_base::out.
I'm not quite sure what you really want to d but it seems you want to pass the file stream around. The normal way to do this is to pass a reference to a std::iostream as argument to the function. Well, actually you probably want to use a std::ifstream initially and hence pass the argument as std::istream&.