I'm a beginner in C++ and am having trouble with the iterator for function pointers right now. Here's what I've got so far.
I'm using Visual Studio.
typedef int(*IntFunPointer)(int);
for (IntFunPointer::iterator it = f.begin(); it != f.end(); ++it) {
//some code
}
Any help will be greatly appreciated. Thanks!
Sorry I should be more clear.
Here is the question:
Implement a function
void fill_with_values(int[] a, int size, IntFunPointer f)
that sets the ith element of the array to f(i). Here IntFunPointer is a typedef for a
pointer to a function that consumes an int and yields an int.
So what I was trying to do is to iterate through the array and set each element to f(i) accordingly. But it doesn't work out well...
Edit:
Now that I see the real question...
Implementing fill_with_values is very simple.
void fill_with_values(int a[] int size, IntFunPointer f)
{
for ( int i = 0; i < size; ++i )
{
a[i] = f(i);
}
}
What you are doing here is not iterating over the function pointer. You are executing the code in the for loop size times. You are calling the function f in every iteration of the for loop and filling the contents of a[i] in the iteration.
Related
I was wondering.. Whenever I deal with arrays, when I have to cut it, or sort it, or anything, and then return it, I pass it to the void function like f(array, length, newarray) and in the function declaration I have void f(T *array, int length, T *&new array).
Is there a better way to do this?
Here's some code, I want to remove repeats from an array:
template<class T>
void eliminate(T *niz, int duzina, T *&podniz)
{
int ind;
podniz = new T[duzina];
for (int i = 0; i<duzina; i++)
{
ind = 0;
for (int j = i; j<duzina; j++)
{
if (niz[i] == niz[j])ind++;
}
if (ind == 1)podniz[nova++] = niz[i];
}
}
As already noted in the comments, you really want std::vector.
The main problem with your code is that there is no way to tell how many of the output elements are actually initialized. And accessing uninitialized elements is Undefined Behavior, so you are returning a time bomb to the caller.
With std::vector<T> eliminate(std::vector const&), there's no such doubt. The returned vector has exactly .size() elements.
Vector is also exception-safe. Your code will leak memory if the copy constructor of T throws, e.g. on a std::bad_alloc.
Sure. You can use pointers and pass the array by reference to the function.
Then manipulate the array and return from the function with void type i.e no need of returning the array as it is passed by reference.
I am a student who is doing an assignment for C++ and I have encountered something I am very unfamiliar with. I have an int array with no size but a list of numbers. After it's creation, there is a function call inside a function that has that array as a parameter with an index in it.
For example:
for (int x = 0; x < CAPACITY, x++)
functionCall(array[x]);
Now I am supposed to create a function so the call can work. However when I make my function:
void functionCall(int array[]);
It does not work because it cannot turn an int to an int[].
I guess my question is, how am I supposed to get that list of numbers created originally by the array if I have to call it in my function as if it isn't an array.
Right now if I just put as an int but not an array like it wants me to do it just gives me the number 5 but not any of the numbers in the array. For example:
void functionCall(int array);
Sincere thank you for anything and I apologize if this sounds confusing.
functionCall(array[x]);
This passes the xth element in the array to the function, so a single int.
array[2] = 5;
functionCall(array[2]); // This is the same as functionCall(5);
So in the function, you get the current element of the array. Not the array itself.
You cannot get the list inside the function, because you only give a single element of that list each time you call it.
Taking a wild guess, I suspect you are looking for something like the MCVE below:
#include <iostream>
void functionCall(int v) {
std::cout << v << " ";
}
void func(int array[], size_t CAPACITY) {
for (size_t x = 0; x < CAPACITY; x++)
functionCall(array[x]);
}
int main() {
int list[] = { 1,2,3,4,3,0, 42 };
func(list, std::distance(std::begin(list), std::end(list)));
return 0;
}
I have a method, which i want to execute differently depending on if the passed variable is an element of a vector or not, like for example:
void method(int a){
if (/*a is an element of a vector*/) //do one thing
else //do another thing
}
and then in main:
vector<int> a;
a.pushback(1);
int b = 1;
method(a[0]); // does one thing
method(b); // does the other thing
What is the simplest way to do that?
Well, for all cases this is impossible, because it actually requires your function to look at how it is executed, and there is no such thing in C++. The hated eval() comes to mind.
But in a certain case, when your vector is a global entity, you could pass your variable by link instead of value. Then, you can check if it fits the space between the start and end of the desired vector. This is how it is done(not tested though, but should work)
vector<int> v;
//fill it somewhere somehow
void method(int& a)
{
int* beg = v.data();
int* end = beg + v.size();
int* val = &a;
if ((val >= beg) && (val < end))
{
//it is a part of vector
}
else
{
//it is not a part of vector
{
}
Problem is that you really shouldn't do it this way... As people in the comments said, it DOES look like an XY problem.
An int is an int. An int does not wear a label around its neck, telling everyone where it came from. When an int is passed to a function, there is nothing that specifies where the int originates.
You should take this as an opportunity to learn about iterators, and implement an overloaded method that takes either an
void method(int);
for a parameter, or a
void method(std::vector<int>::iterator iter);
for a parameter (or, perhaps, a const_iterator), and invoke the alternative method() by passing it an iterator to the int in your vector.
I included the "not using strings" part in the title because when I was searching to find an answer on here I saw this problem a lot but it was with people using strings and getting chars mixed up. This is not my issue.
Trying to call an element of a 2D vector and see if it equals a certain number. I'm getting the comparison between pointer/integer error and I don't understand why. Here's my code, any help would be really appreciated.
bool UsedInRow(vector< vector<int> > vec(int n, vector<int> (int n)), int row, int num)
{
int n;
for (int col = 0; col < n; col++)
{
if (vec[row][col] == num)
{
return true;
}
}
return false;
}
Try this:
bool UsedInRow(const vector< vector<int> >& vec, int row, int num) { ... }
The expression you used vector< vector<int> > vec(int n, vector<int> (int n)) is actually a function pointer.
The compiler thinks that you are passing a function pointer.
Instead, pass the vector by reference:
bool UsedInRow(vector< vector<int> > &vec, int row, int num)
As the other answers point out, vec is a function pointer, not a vector.
You're being advised to change vec to a vector, but it's not clear that that's the right solution. There's no ambiguity in your declaration; vec is defined as a parameter of function pointer type.
If that's what you intended, you need to replace the reference to vec inside the function with a function call. For example, you might change
if (vec[row][col] == num)
to
if ((vec(42, something))[row][col] == num)
where something would itself have to be a function pointer, pointing to a function that takes an int argument and returns a vector<int> result.
The declaration of your UsedInRow function is quite complicated, and I can't tell how it's intended to be used.
If vec really should be just a vector, then you can make it one by deleting the (int n, vector<int> (int n)) part of the parameter declaration -- but then I'd have to wonder why you wrote it in the first place.
For a definitive answer, you'd need to explain to us what your UsedInRow function is supposed to do.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
length of array in function argument
Hi am doing homework and I am completly stumped. We were suppose to get every order of a list an array of integers so I wrote this piece of code, based off of my teacher's pseudocode:
void permute(int v[], int curr,char letters[])
{
if(curr >= sizeof(v)/sizeof(int))
{
checkit(v,letters);
}
for(int i = curr; i < sizeof(v)/sizeof(int); i++)
{
swap(i,curr,v);
permute(v,curr + 1,letters);
swap(v[curr],v[i]);
}//for
}//permu
The only thing I am not sure of is if sizeof(v)/sizeof(int) is the right way to go.
sizeof(v)/sizeof(int) is not the way to go. Your function is exactly equivalent to:
void permute(int *v, int curr, char *letters)
{
...
}
i.e. v is not really an array, it's a pointer. You cannot pass arrays in C or C++.
The solution is one of the following (not exhaustive):
add an extra argument that explicitly describes the length of the array
add an extra argument that points at the last element of the array
use a proper container (e.g. std::vector), which you can call size() on
the template solution that #sehe suggests
One of my pet peeves: you can get C++ to deduce the array size for you
template <size_t N>
void permute(int (&v)[N], int curr,char letters[])
{
if(curr >= N)
{
checkit(v,letters);
}
for(int i = curr; i < N; i++)
{
swap(i,curr,v);
permute(v,curr + 1,letters);
swap(v[curr],v[i]);
}//for
}//permu
In addition to Oli's answer: the typical way in C++ is to pass a pointer to the beginning and a pointer to the end of the sequence that you want to permute. By convention the beginning pointer is inclusive, the ending pointer is exclusive.
void permute(int *v, int *begin, int *end, char *letters) {
if (begin == end) {
checkit(v, end, letters);
} else {
...
permute(v, begin + 1, end, letters);
...
}
}