I'm trying to get a divide and conquer algorithm working that returns a vector, and since it's a divide and conquer algorithm it obviously needs to run more than one instance at a time. The problem is when it comes down to the return portion.
Right now I have:
vector<MyObject> MyProgram(...){
...Code that's not important...
return MyProgram(...) + MyProgram(...);
}
unfortunately apparently I can't just use the + operand. I know that you can concatenate vectors by inserting one into the other, or copying one into the other, but then MyProgram would be getting called one after the other, not simultaneously.
I'm literally guessing that this is what you're trying to accomplish, but it is conjecture at best, so let me know whether this answer should be deleted due to being inapplicable.
The following defines a function that returns an empty vector if the argument is zero. Otherwise is returns a vector of N instances of the value N concatenated with the function evaluated at N-1. The concatenation is done asynchronously via a separate thread, thereby giving you the potential for concurrency.
#include <iostream>
#include <vector>
#include <future>
std::vector<unsigned int> MyFunction(unsigned arg)
{
std::vector<unsigned int> result;
if (arg == 0)
return result;
auto fc = std::async(std::launch::async, MyFunction, arg-1);
for (unsigned int i=0; i<arg; ++i)
result.emplace_back(arg);
std::vector<unsigned int> theirs = fc.get();
result.insert(result.begin(), theirs.begin(), theirs.end());
return result;
}
int main()
{
std::vector<unsigned int> res = MyFunction(8);
for (auto x : res)
std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
Output
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8
Each miniature sequence is generated on a separate thread except the first one, in this case the sequence of 8's, generated on the primary thread.
Anyway, I hope it gives you some ideas.
Use a wrapper. Now just add an overloaded operator+ to that class.
Such a Wrapper can look like this:
class Wrapper
{
public:
Wrapper(const vector<MyObject>& _vec) : vec(_vec) {}
Wrapper operator+(Wrapper& rhs)
{
vector<MyObject> tmp(vec);
tmp.insert(tmp.end(), rhs.vec.begin(), rhs.vec.end());
return Wrapper(tmp);
}
operator const vector<MyObject>&(){return vec;}
private:
vector<MyObject> vec;
};
Your function would then be like:
Wrapper MyProgram(...){
...Code that's not important...
return MyProgram(...) + MyProgram(...);
}
Please check the comments for important warnings about your current design.
Related
So I'm trying to solve this question that was asked for me, And I'm very close on finding it by running the code, but I cannot because I get this C++ error message: a value of type "void" cannot be assigned to an entity of type "int"
Let Q be an instance of an ADT per Row. Q.enqueue (x) adds an element x
in a row. Q.dequeue () performs the subtraction operation in the row and returns the removed value.
Consider the following code snippet:
Demonstrate the execution of this code by showing the state of Queue. Which will
be the value of the variable count, when the execution of the above code is completed?
C++ Code:
#include <iostream>
#include <queue>
using namespace std;
int main(){
queue<int> myqueue;
int count = 1;
int x;
myqueue.push(1);
do{
count=count+1;
x = myqueue.pop();
myqueue.push( 2*x );
myqueue.push( 2*x+1);
} while(x != 967);
return 0;
}
The compilation error is caused by the fact that pop does not return anything – you need to use front first, then pop.
However, this is not what you're supposed to do; you are supposed to solve this by thinking and understanding how a queue works.
Start with the first task: "Demonstrate the execution of this code by showing the state of Queue."
These are the first few states of the queue:
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
6 7 8 9 10 11
7 8 9 10 11 12 13
And now you can see a pretty obvious relationship between count and the front of the queue.
I've seen instances where someone would use return statements with multiple values. For example: return 8, 10, 6; As far as I know, only one of these values will actually be returned. What is the benefit of using return this way?
Specifically, this question appears on my homework.
The statement: return 2 * 3 + 1, 1 + 5; returns the value ____.
I know it would always return 6, so why would I ever write it like this?
Forgive me if this is a simple question. I am still somewhat new to programming.
The statement return 2 * 3 + 1, 1 + 5; returns the value 6.
This the trick of comma operator in C++. You can read more about it here:
https://en.cppreference.com/w/cpp/language/operator_other
A comma operator is basically a list of expressions separated by commas, they will be evaluated from left to right, and the result of the last item will be treated as the result of the whole comma operator.
Here is a simple example demonstrating how comma operator works.
int foo() {
int i = 1;
return i += 2, i++, i + 5; // This is a comma operator with three items
// i += 2 will be evaluated first, then i == 3
// i++ will be evaluated second, then i == 4
// i + 5 will be evaluate last, and the result is 9
// the result of the last item is returned by the return statement
}
int main() {
std::cout << foo();
return 0;
}
This code prints 9.
When you do this you are avoiding using math in your function block and this make your function like working 3 time and result would be the one you want
The input consists of a set of tasks given in increasing order of start time, and each task has a certain duration associated.
The first line is number of tasks, for example
3
2 5
4 23
7 4
This means that there are 3 tasks. The first one starts at time 2, and ends at 7 (2+5). Second starts at 4, ends at 27. Third starts at 7, ends at 11.
We assume each task starts as soon as it is ready, and does not need to wait for a processor or anything else to free up.
This means we can keep track of number of active tasks:
Time #tasks
0 - 2 0
2 - 4 1
4 - 11 2
11 - 27 1
I need to find 2 numbers:
Max number of active tasks at any given time (2 in this case) and
Average number of active tasks over the entire duration computed here as :
[ 0*(2-0) + 1*(4-2) + 2*(11-4) + 1*(27-11) ] / 27
For this,
I have first found the time when all tasks have come to an end using the below code:
#include "stdio.h"
#include "stdlib.h"
typedef struct
{
long int start;
int dur;
} task;
int main()
{
long int num_tasks, endtime;
long int maxtime = 0;
scanf("%ld",&num_tasks);
task *t = new task[num_tasks];
for (int i=0;i<num_tasks;i++)
{
scanf("%ld %d",&t[i].start,&t[i].dur);
endtime = t[i].start + t[i].dur;
if (endtime > maxtime)
maxtime = endtime;
}
printf("%ld\n",maxtime);
}
Can this be done using Priority Queues implemented as heaps ?
Your question is rather broad, so I am going to just give you a teaser answer that will, hopefully, get you started, attempting to answer your first part of the question, with a not necessarily optimized solution.
In your toy input, you have:
2 5
4 23
7 4
thus you can compute and store in the array of structs that you have, the end time of a task, rather than its duration, for later usage. That gives as an array like this:
2 7
4 27
7 11
Your array is already sorted (because the input is given in that order) by start time, and that's useful. Use std::sort to sort the array, if needed.
Observe how you could check for the end time of the first task versus the start time of the other tasks. With the right comparison, you can determine the number of active tasks along with the first task. Checking whether the end time of the first task is greater than the start time of the second task, if true, denotes that these two tasks are active together at some point.
Then you would do the same for the comparison of the first with the third task. After that you would know how many tasks were active in relation with the first task.
Afterwards, you are going to follow the same procedure for the second task, and so on.
Putting all that together in code, we get:
#include "stdio.h"
#include "stdlib.h"
#include <algorithm>
typedef struct {
int start;
int dur;
int end;
} task;
int compare (const task& a, const task& b) {
return ( a.start < b.start );
}
int main() {
int num_tasks;
scanf("%d",&num_tasks);
task *t = new task[num_tasks];
for (int i=0;i<num_tasks;i++) {
scanf("%d %d",&t[i].start,&t[i].dur);
t[i].end = t[i].start + t[i].dur;
}
std::sort(t, t + num_tasks, compare);
for (int i=0;i<num_tasks;i++) {
printf("%d %d\n", t[i].start, t[i].end);
}
int max_noOf_tasks = 0;
for(int i = 0; i < num_tasks - 1; i++) {
int noOf_tasks = 1;
for(int j = i + 1; j < num_tasks; j++) {
if(t[i].end > t[j].start)
noOf_tasks++;
}
if(max_noOf_tasks < noOf_tasks)
max_noOf_tasks = noOf_tasks;
}
printf("Max. number of active tasks: %d\n", max_noOf_tasks);
delete [] t;
}
Output:
2 7
4 27
7 11
Max. number of active tasks: 2
Now, good luck with the second part of your question.
PS: Since this is C++, you could have used an std::vector to store your structs, rather than a plain array. That way you would avoid dynamic memory allocation too, since the vector takes care that for you automatically.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am taking a course on edx.org Introduction to C++ by Microsoft. I get unwanted output when looping through a single dimensional array. The code is below.
<#include <iostream>
int main() {
int arrayName[10] = { 1,2,3,4,5,6,7,8,9,10 };
for (int i = 1; arrayName[i] <= 20; i++) {
std::cout << i << std::endl;
}
The output of this is:
1
2
3
4
5
6
7
8
9
10
11
Where does the 11 come from? And, if I make i=0, it also prints a 0. How does it print more than 10? And, when I try to change arrayName[10] to arrayName[9], I get a compiler error that there are too many initialized values:
int arrayName[10] = { 1,2,3,4,5,6,7,8,9,10 };
do {
std::cout << i << std::endl;
i++;
} while (arrayName[i] < 5);
The output is:
12
13
14
15
16
17
18
That do-while loop outputs 7 integers that I did not specify to be included in the arrayName[] array.
I don't know what I am doing wrong or what I am not understanding.
Please help. Thank you!
First, note that arrays in c++ start at index 0. So in int arrayName[3] = {10, 42, 88}; then arrayName[1] is 42, not 10. That means the last element in this array is int arrayName[2]. There is no element at index 3.
Your array only contains 10 elements (indices 0 to 9). The standard does not specify what happens when you access an element past the end of an array, anything can happen. In your case, arrayName[10] and arrayName[11] happens to give you something less than or equal to 20, and then arrayName[12] gave you something greater than 20, ending the loop. If you try it on another computer, or even at a different time, the results will vary. It might also crash (this is the best case scenario).
See this answer for more information on undefined behavior.
I finally found this: Correct way of loop through the C++ arrays, answer by https://stackoverflow.com/users/1619294/mark-garcia.
Changed my code to:
std::cout << "Looping through arrayName3 with std::array and letting the compiler determine how many objects to print:" << std::endl;
// Need to #include <array>
std::array<int, 10> arrayName3 = { 1,2,3,4,5,6,7,8,9,10 };
for (const auto& i : arrayName3) // Range-for
{
std::cout << i << std::endl;
}
The output was what I wanted:
1
2
3
4
5
6
7
8
9
10
This let's the compiler know it is deciding what to output. It would be great to know how to change this to control how many indices to loop through.
Does anybody know why
vector<int> test(10);
int a=0;
for_each(test.begin(),test.end(),(_1+=var(a),++var(a)));
for_each(test.begin(),test.end(),(cout << _1 << " "));
cout << "\n"
Gives : "0 1 2 3 4 5 6 7 8 9"
but
transform(test.begin(),test.end(),test.begin(), (_1+=var(a),++var(a)));
...(as before)
Gives : "1 2 3 4 5 6 7 8 9 10"
?
Comma operator evaluates left to right, so the result of the
_1+=var(a), ++var(a)
is ++var(a), which you'll store using the transform version.
for_each:
_1 += var(a) is evaluated, updating your sequence (via the lambda _1), then ++var(a) is evaluated, but this has no effect on your sequence.
transform:
_1+=var(a) is evaluated, updating your sequence (just like before), then ++var(a) is evaluated, this also gives the result of the whole expression, then that is used to update your sequence again (via the transform)
Essentially, in the for_each you provide a function with a side-effect, while in the transform, your use the returnvalue of a function.
In your case, you reuse the same function. Since operator += happens to have a return value, this is the one used as a result of the transformation.
transform(test.begin(),test.end(),test.begin(),
(_1+=var(a),++var(a)));
This will translate to
int doit(int & elem) {
elem += a;
return ++a;
}
for each elem : elem = doit(elem);
Starting with a=0 will result in 1 in the first run. We are incrementing a 10 times, so we will get 10 in the last run.
for_each(test.begin(),test.end(),(_1+=var(a),++var(a)));
This will translate to
void doit(int & elem) {
elem += a;
++a;
}
for each elem : doit(elem);
Starting with a=0, we will get 0 in the first run. We increment a 10 times, but assign it just before incrementing. Thus the last number is 9.
I hope it's clear now with the translation to ordinary functions what those two do.