Pass a vector by reference C++ - c++

I can't figure out why this won't work?
I need to pass the vector reference so I can manipulate it from an external function.
There are several questions on this on the internet but I can't understand the replies?
code below:.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string funct(vector<string> *vec)
{
cout << vec[1] << endl;
}
int main()
{
vector<string> v;
v.push_back("one");
v.push_back("two");
v.push_back("three");
}

Firstly you need to learn the differences between references and pointers and then the difference between pass-by-reference and pass-by-pointer.
A function prototype of the form:
void example(int *); //This is pass-by-pointer
expects a function call of the type:
int a; //The variable a
example(&a); //Passing the address of the variable
Whereas, a prototype of the form:
void example(int &); //This is pass-by-reference
expects a function call of the type:
int a; //The variable a
example(a);
Using the same logic, if you wish to pass the vector by reference, use the following:
void funct(vector<string> &vec) //Function declaration and definition
{
//do something
}
int main()
{
vector<string> v;
funct(v); //Function call
}
EDIT: A link to a basic explanation regarding pointers and references:
https://www.dgp.toronto.edu/~patrick/csc418/wi2004/notes/PointersVsRef.pdf

Related

How do I pass a function with an argument of a structure passed by reference?

I was working on my program and noticed that it doesn't compile. I was wondering why I can't pass my structure array as an array of references. My code is down below
#include <iostream>
#include <cstring>
using namespace std;
struct a{
int name;
};
void input(a & array1[10]){
for(int i=0;i<10;i++){
array1[i].name=i+1;
}
}
void print(a & array1[10]){
for(int i=0;i<10;i++){
cout<<array1[i].name<<endl;
}
}
int main(){
a array1[10];
input(array1[10]);
print(array1[10]);
}
When you pass an array into a function:
<opinion> The array degrades to a pointer. So you might as well have the
function declare the parameter as a pointer, "a*", instead of as an
array, a[].
The function has no idea how many items are in the array parameter. You should get in the habit of passing "size" as a parameter to a function when you pass the array.
On the flip side, arrays passed as pointers are inherently a reference parameter not a value (copy of) parameter. So you are implicitly meeting your goal of passing your array and all the items in the array by reference.
This is probably what you want.
#include <iostream>
#include <cstring>
using namespace std;
struct a {
int name;
};
void input(a* array, size_t count){
for(int i=0; i<count; i++) {
array[i].name = i + 1;
}
}
void print(a* array, size_t count) {
for(int i=0; i<count; i++) {
cout<<array[i].name<<endl;
}
}
int main() {
a array1[10] = {}; // zero-init the array of a's
input(array1, 10);
print(array1, 10);
}
Your syntax to pass the array by reference is wrong.
Please see the working code below.
#include <iostream>
#include <cstring>
using namespace std;
struct a{
int name;
};
void input(a (&array1)[10]){
for(int i=0;i<10;i++){
array1[i].name=i+1;
}
}
void print(a (&array1)[10]){
for(int i=0;i<10;i++){
cout<<array1[i].name<<endl;
}
}
int main(){
a array1[10];
input(array1); // make sure you simply pass the array name
print(array1);
}
Try it out yourself
As enforced by the syntax of the language parenthesis that enclose array1 as in (&array1) are necessary. If you don't use them you're simply passing an array of reference not a referene to an array.
array1[10] is the 10th element of the array(which actually in your case doesn't exists, it's simply out-of-array-bound access), instead you need to pass the address of the first element of the array which is the same as array name i.e. the array name decays to a pointer.

Storing a vector of various void function pointers with its parameters

I'm looking for a way to store function pointers in a container like a vector. This is possible if all the functions have the same parameters but can I do if the functions have individually unique parameters?
#include <iostream>
#include <vector>
using namespace std;
void sayHi() {
cout << "Hi" << endl;
}
void sayNum(int num) {
cout << num << endl;
}
int main() {
vector<void(*)()> funcs; // vector of 0 argument functions
funcs.push_back(sayHi);
funcs.push_back(sayNum); // can't store sayNum because it takes arguments
}
Note that I can't use std::function or std::bind because VS2013 doesn't have them and I'd rather not use the boost library. The solution must be allow the possibility to iterate through the vector of function pointers and execute each one with some valid arguments.
Forgive my potential ignorance about how function pointers work, I'm very used to doing this sort of thing in Javascript in one statement :P
Made the mistake of not including as I couldn't see it mentioned in anybody's code examples but it's probably just me being bad at C++.
Not going to accept my own answer, but thought I'd post my code just in the interests of anybody who might find it useful.
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
typedef std::vector<std::function<void(void)>> f_list;
f_list f1;
void _sayHi();
void _sayNum(int num);
void sayHi() {
f1.push_back(
std::bind(&_sayHi)
);
}
void sayNum(int num) {
f1.push_back(
std::bind(&_sayNum, num)
);
}
void _sayHi() {
cout << "hi" << endl;
}
void _sayNum(int num) {
cout << num << endl;
}
int main() {
sayHi();
sayNum(5);
for (int i = 0; i < f1.size(); i++) {
f1.at(i)(); // will execute desired functions
}
}
VS 2103 has std::function, std::bind and lambdas. Simply use them.

How Do I Store Objects in a Object in a Vector? (C++)

I hope this is not a stupid question. Basically I would like to access a string stored in a Class (Statement is the name I am using) in a vector of type Statement. Basically I am trying to store objects in a dynamic hierarchy of objects.
Types.cpp:
#include<iostream>
#include<fstream>
#include <string>
#include <vector>
using namespace std;
class Statement{
public:
vector<string> Inner_String;
vector<Statement> Inner_Statement;
string contents;
void set_contents (string);
string get_contents(){ return contents;}
void new_string(string);
string get_string(int v){return Inner_String[v];}
void new_Inner_Statement(Statement);
Statement get_Inner_Statement(int v){return Inner_Statement[v];}
};
void Statement::set_contents(string s){
contents = s;
}
void Statement::new_string(string s){
Inner_String.push_back(s);
}
void Statement::new_Inner_Statement(Statement s){
Inner_Statement.push_back(s);
}
Main method:
#include <iostream>
#include "FileIO.h"
#include "Types.h"
using namespace std;
int main()
{
Statement test;
test.new_Inner_Statement(Statement());
Statement a = test.get_Inner_Statement(0);
a.set_contents("words");
cout << a.get_contents();
test.get_Inner_Statement(0).set_contents("string");
cout << test.get_Inner_Statement(0).get_contents();
return 0;
}
What happens is
cout << a.get_contents()
returns its string while
cout << test.get_Inner_Statement(0).get_contents()
does not.
Look at this piece of code:
test.get_Inner_Statement(0).set_contents("string");
^^^^^^^^^^^^^^^^^^^^^^^^^^^
It calls this function:
Statement get_Inner_Statement(int v)
which returns a copy object (temporary) of type statement. On this object, you calls set_contents function, at which cease to exists at the end of the call.
Then, you call:
test.get_Inner_Statement(0).get_contents();
that creates a new temporary, from the unchanged statement, and try to get its contents.

Calling a member function pointer stored in a std map

I'm storing a map in a class that has strings as keys and pointers to member functions as values. I'm having trouble calling the right function throw the function pointer.
Here is the code:
#include <iostream>
#include <string>
#include <map>
using namespace std;
class Preprocessor;
typedef void (Preprocessor::*function)();
class Preprocessor
{
public:
Preprocessor();
~Preprocessor();
void processing(const string before_processing);
private:
void take_new_key();
map<string, function> srch_keys;
string after_processing;
};
Preprocessor::Preprocessor()
{
srch_keys.insert(pair<string, function>(string("#define"), &Preprocessor::take_new_key));
}
Preprocessor::~Preprocessor()
{
}
void Preprocessor::processing(const string before_processing)
{
map<string, function>::iterator result = srch_keys.find("#define");
if(result != srch_keys.end())
result->second;
}
void Preprocessor::take_new_key()
{
cout << "enters here";
}
int main()
{
Preprocessor pre;
pre.processing(string("...word #define other word"));
return 0;
}
In function Preprocessor::processing if the string is found in the map then, I call the proper function. The problem is that, in this code, Preprocessor::take_new_key is never called.
Where is the mistake ?
Thanks
The correct syntax is this:
(this->*(result->second))();
That is ugly. So lets try this:
auto mem = result->second; //C++11 only
(this->*mem)();
Use whichever makes you happy.
result->second does not call the function pointer. Try ((*this).*result->second)();

C++ class member function callback

I have the following problem. I have a function from an external library (which cannot be modified) like this:
void externalFunction(int n, void udf(double*) );
I would like to pass as the udf function above a function member of an existing class. Please look at the following code:
// External function (tipically from an external library)
void externalFunction(int n, void udf(double*) )
{
// do something
}
// User Defined Function (UDF)
void myUDF(double* a)
{
// do something
}
// Class containing the User Defined Function (UDF)
class myClass
{
public:
void classUDF(double* a)
{
// do something...
};
};
int main()
{
int n=1;
// The UDF to be supplied is myUDF
externalFunction(n, myUDF);
// The UDF is the classUDF member function of a myClass object
myClass myClassObj;
externalFunction(n, myClassObj.classUDF); // ERROR!!
}
I cannot declare the classUDF member function as a static function, so the last line of the code above results in a compilation error!
This is impossible to do - in c++, you must use either a free function, or a static member function, or (in c++11) a lambda without capture to get a function pointer.
GCC allows you to create nested function which could do what you want, but only in C. It uses so-called trampolines to do that (basically small pieces of dynamically generated code). It would be possible to use this feature, but only if you split some of the code calling externalFunction to a separate C module.
Another possibility would be generating code at runtime eg. using libjit.
So if you're fine with non-reenrant function, create a global/static variable which will point to this and use it in your static function.
class myClass
{
public:
static myClass* callback_this;
static void classUDF(double* a)
{
callback_this.realUDF(a);
};
};
Its really horrible code, but I'm afraid you're out of luck with such a bad design as your externalFunction.
You can use Boost bind or TR1 bind (on recent compilers);;
externalFunction(n, boost::bind(&myClass::classUDF, boost::ref(myClassObj)));
Unfortunately, I lived in a pipe dream for the last 10 minutes. The only way forward is to call the target using some kind of a static wrapper function. The other answers have various neat (compiler-specific) tidbits on that, but here's the main trick:
void externalFunction(int n, void (*udf)(double*) )
{ double x; udf(&x); }
myClass myClassObj;
void wrapper(double* d) { myClassObj.classUDF(d); }
int main()
{
externalFunction(1, &wrapper);
}
std::function<>
Store a bound function in a variable like this:
std::function<void(double*)> stored = std::bind(&myClass::classUDF, boost::ref(myClassObj))
(assuming C++0x support in compiler now. I'm sure Boost has a boost::function<> somewhere)
Vanilla C++ pointers-to-member-function
Without magic like that, you'd need pointer-to-memberfunction syntax:
See also live on http://ideone.com/Ld7It
Edit to clarify to the commenters, obviously this only works iff you have control over the definition of externalFunction. This is in direct response to the /broken/ snippet int the OP.
struct myClass
{
void classUDF(double* a) { };
};
void externalFunction(int n, void (myClass::*udf)(double*) )
{
myClass myClassObj;
double x;
(myClassObj.*udf)(&x);
}
int main()
{
externalFunction(1, &myClass::classUDF);
}
C++98 idiomatic solution
// mem_fun_ref example
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <string>
int main ()
{
std::vector<std::string> numbers;
// populate vector:
numbers.push_back("one");
numbers.push_back("two");
numbers.push_back("three");
numbers.push_back("four");
numbers.push_back("five");
std::vector <int> lengths (numbers.size());
std::transform (numbers.begin(), numbers.end(), lengths.begin(),
std::mem_fun_ref(&std::string::length));
for (int i=0; i<5; i++) {
std::cout << numbers[i] << " has " << lengths[i] << " letters.\n";
}
return 0;
}
Here is how I do this, when MyClass is a singleton:
void externalFunction(int n, void udf(double) );
class MyClass
{
public:
static MyClass* m_this;
MyClass(){ m_this = this; }
static void mycallback(double* x){ m_this->myrealcallback(x); }
void myrealcallback(double* x);
}
int main()
{
MyClass myClass;
externalFunction(0, MyClass::mycallback);
}