在for循环C ++中创建变量的新实例

时间:2014-03-17 22:37:17

标签: c++ for-loop openframeworks

我的一些基础知识有很多漏洞,但这是我的问题。

我有一个for循环。它循环遍历所有实例contourFinder(到目前为止运行良好),但是一旦它尝试构建折线和pathFromContour,我就无法找到一种链接轮廓ID的方法(' i&#39 ;)到新创建的折线和路径。

void draw(){
for(int i = 0; i < n; i++) {

    //FOR FILLING
    ofPolyline polyline = contourFinder.getPolyline(i);//to convert
    ofPath pathFromContour;//path to be built

    for(int i = 0; i < polyline.getVertices().size(); i++) {
        if(i == 0) {
            pathFromContour.newSubPath();
            pathFromContour.moveTo(polyline.getVertices()[i]);
        } else {
            pathFromContour.lineTo(polyline.getVertices()[i]);
        }
    }
    pathFromContour.close();
    pathFromContour.simplify();

    ofColor pathColor(ofRandom(255),ofRandom(255),ofRandom(255));
    pathFromContour.setFillColor(pathColor);
    pathFromContour.draw();

}
}

因此,我似乎无法区别对待我的路径或折线。任何人都能解释一下我的错误吗?

由于

2 个答案:

答案 0 :(得分:2)

尝试将内部for循环上的计数器更改为“j”或“k”。使用i作为外循环和内循环是不好的做法。

答案 1 :(得分:2)

这样的东西?

void draw(){
    ofPolyline* polylines = new ofPopyline[n];
    ofPath* path = new ofPath[n];
    for(int i = 0; i < n; i++) {

        //FOR FILLING
        ofPolyline& polyline = polylines[i];
        polyline = contourFinder.getPolyline(i);//to convert
        ofPath& pathFromContour = ofPath[i];//path to be built

        for(int j = 0; j < polyline.getVertices().size(); j++) {
            if(j == 0) {
                pathFromContour.newSubPath();
                pathFromContour.moveTo(polyline.getVertices()[j]);
            } else {
                pathFromContour.lineTo(polyline.getVertices()[j]);
            }
        }
        pathFromContour.close();
        pathFromContour.simplify();

        ofColor pathColor(ofRandom(255),ofRandom(255),ofRandom(255));
        pathFromContour.setFillColor(pathColor);
        pathFromContour.draw();

    }
    // free resources if they are no longer needed
    delete[] polylines;
    delete[] path;
}

更新:替代变体,使用向量

void draw(){
    vector<ofPolyline> polylines;
    vector<ofPath> paths;
    for(int i = 0; i < n; i++) {

        //FOR FILLING
        ofPolyline polyline = contourFinder.getPolyline(i);//to convert
        polylines.push_back(polyline);

        ofPath pathFromContour;//path to be built

        for(int j = 0; j < polyline.getVertices().size(); j++) {
            if(j == 0) {
                pathFromContour.newSubPath();
                pathFromContour.moveTo(polyline.getVertices()[j]);
            } else {
                pathFromContour.lineTo(polyline.getVertices()[j]);
            }
        }
        pathFromContour.close();
        pathFromContour.simplify();

        ofColor pathColor(ofRandom(255),ofRandom(255),ofRandom(255));
        pathFromContour.setFillColor(pathColor);
        pathFromContour.draw();
        paths.push_back(pathFromContour);

    }
    // no need to explicitly free the resources
  }