简体   繁体   中英

recursive function cannot return value as expected

I want to use recursive to achieve beziercurve, in recursive_bezier function it recursives all input points until there is only one point left and return that point, then in bezier function get that value by execute recursive_bezier . But in bezier function I can only get the value of the first input point, have no ideal why? Please help.

#include <chrono>
#include <iostream>
#include <opencv2/opencv.hpp>

std::vector<cv::Point2f> control_points;

cv::Point2f recursive_bezier(const std::vector<cv::Point2f> &control_points, float t) 
{
    int control_size = control_points.size();
    std::vector<cv::Point2f> temp_points;
    if (control_size != 1)
    {
        
        for (int i = 0; i < control_size - 1; i++)
        {
            cv::Point2f t_point;
            auto vt = (control_points[i+1] - control_points[i])*t;
            t_point.x = control_points[i].x + vt.x;
            t_point.y = control_points[i].y + vt.y;
            temp_points.push_back(t_point);

        }
        recursive_bezier(temp_points, t);

    }
    std::cout << "from recursive" << control_points[0] << std::endl;  //here can output correct point value
    return control_points[0];
}

void bezier(const std::vector<cv::Point2f> &control_points) 
{

    for (double t = 0.0; t <= 1.0; t +=0.5)
    {
        cv::Point2f point = recursive_bezier(control_points, t);  
        std::cout << "from bezier:" << point << std::endl;  //here cannot get the point correct, it always printout the first value of the input control_points
    }

}

int main() 
{
    control_points.emplace_back(4,5);
    control_points.emplace_back(3.6);
    bezier(control_points);
    return 0;
}

Ignoring the details, your code is this:

cv::Point2f recursive_bezier(const std::vector<cv::Point2f> &control_points, float t) 
{
    int control_size = control_points.size();
    std::vector<cv::Point2f> temp_points;
    if (control_size != 1)
    {
        recursive_bezier(temp_points, t);    
    }       
    return control_points[0];
}

Because the function takes the vector by const reference, the call recursive_bezier(temp_points,t) has no effect on what the function eventually returns. The only return is return control_points[0]; and thats what the function returns always.

You forgot to actually use the returned value of the recursive calls. I suppose you simply want to return it:

cv::Point2f recursive_bezier(const std::vector<cv::Point2f> &control_points, float t) 
{
    int control_size = control_points.size();
    std::vector<cv::Point2f> temp_points;
    if (control_size != 1)
    {
        return recursive_bezier(temp_points, t);     // <---
    }       
    return control_points[0];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM