Std:swap vector has side effect on drawing a string


#1

Hi,
I have 2 instances of a custom class ArtWork in a vector. For each instance I draw a property “name” on screen.
These to strings are aligned along y axis like:

Art00 Art01

Now if I use std:swap to change the z-order the “Art00” is not drawn anymore, and the result is

      Art01

I cannot figure out where the problem is. Here the very simple code:

// File ArtWork.cpp
#pragma once
#include <stdio.h>
#include <iostream>
#include "ofPoint.h"
#include "ofxAssets.h"
using namespace std;

class ArtWork  {
public:
    ArtWork();
    void setup(string _name, ofVec2f _position);
    void draw();
private:
    string name;
    ofTrueTypeFont font;
    ofVec2f position;
};

// File ArtWork.cpp
#include "ArtWork.h"
ArtWork::ArtWork() {
}
void ArtWork::setup(std::string _name, ofVec2f _position) {
    name = _name;
    position = _position;
    font.load("verdana.ttf", 14, true, true);
    font.setLineHeight(18.0f);
    font.setLetterSpacing(1.037);
}

void ArtWork::draw() {
    font.drawString(name, position.x, position.y);
}

// ofApp.cpp
#include "ofApp.h"
#include "ArtWork.h"

vector<ArtWork> artWorks;

void ofApp::setup(){
    ofBackground(22);
    
    ArtWork artWork0 = ArtWork();
    artWork0.setup("Art00",ofVec2f(10,30));
    
    ArtWork artWork1 = ArtWork();
    artWork1.setup("Art01",ofVec2f(100,30));
    
    artWorks.push_back(artWork0);
    artWorks.push_back(artWork1);

    // Changes z-order
    // std::swap(artWorks[0], artWorks[1]);  // uncomment, and Art00 is not drawn anymore
}

void ofApp::draw(){
    ofSetColor(200);
    for(int i = 0; i < artWorks.size(); i++) {
        artWorks[i].draw();
    }
}

Just a little update:
If I replace

font.drawString(name, position.x, position.y);

with

ofDrawBitmapString(name, position.x, position.y);

both string “Art00” & “Art01” are drawn.

I have also defined font as a global variable and passed its pointer to ArtWork instances in order to have
only one instance of font but “Art00” is not drawn. I cannot really understand where the problem is.

thanks for you help