In order to do some simulations, I create a class containing vectors, then a vector of objects of this class. Once it's done, I need to check vectors in each object whether there is negative elements. If it is the case, I have to increase each negative element of 0.5 in a round, till there is no negative element anymore.
I have written following code. However, it cannot compile. There are some problems with the lambda expression, maybe also with other fractions.
Could someone please tell me where is the mistake, or how can I code in a more efficient way to make the execution fast?
1) You try to pass variable i to the lambda instead of capturing it. it=find_if(myVec.begin(), myVec.end(), [&i](CTest *v)->bool{return (*v).length[i]<0;});
2) Memory leak. In C++, usually every new must have its corresponding delete. myVec.push_back(new CTest(al[0]));
If you want to stick to dynamic memory allocation, even if you don't need to in my opinion, look into smart pointers: http://en.cppreference.com/w/cpp/memory
Then you can "forget" about the delete.
3) What does *it+=0.5; mean? *it returns a pointer to a CTest object.
I wanted to increase each negative element of each vector 0.5 till there is no negative element. There was a code mistake.
To be brief, 1. check whether there exists negative element. 2. If true, increment all negative element 0.5. 3. recheck for negative element. 4. If true,... I tried to use do... while structure, it doesn't fit; neither the while structure.
I use VS2010 so it should support c++11. However, I would like to use some traditional for loop like for(int i=0; i<4; i++) then use some "automatic" control structure to check negative element of vectors and adjust them, and recheck, and readjust, and ....
Actually, here is just a demonstration code. The vector "myVec" in reality contains thousands of objects, each objects contains 40 vectors like length, and the whole iteration round int i runs from 0 to 1000.
That's why I cannot write all the case one by one with if.
Well, it seems in your code we check the vector of length from begin to end. But actually I need to check each length[0] of each object at one time. Then move to length[1] of each object...
I have just modified my previous code following a traditional way:
1. check whether there is a negative element. 2. if yes, increment the element of all vectors by 0.5. 3. recheck for negative element... till there is no negative element, turn to next level of i.
Is this code correct? Even if it's correct, I feel it too complicated, not efficient.
1) So you have a vector of objects (Vo), all objects containing a vector of doubles (Vd). 2) You check each element in the Vd of each object in Vo to see if it's negative. 3) If it is you keep position i, and increase all elements at Vd[i] of all objects in Vo by 0.5?
for 3): And then recheck all Vd[i], whether there is negative. if yes, increase by 0.5 again. And recheck... till there is no negative element among all Vd[i].