Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Fill a vector with another vector

Tags:

c++

vector

I have two vectors, and I would like to fill the first one with the second. The vectors are declared like this:

vector<Vec3> firstVector;

Where Vec3 is a struct with float x, y, z. I have tried liked this with assign:

secondVector.assign(firstVector.begin(), firstVector.end());

But it stops and complains, that there is problem with the end(). I have also tried pushback, but of course it's not working.

As I read before I should do it with assign, but I don't know how to solve it properly.

EDIT:

The error message with insert and assign are the same:

this 0x00000000 ... std::vector > * const

[size] CXX0030: Error: expression cannot be evaluated
[capacity] CXX0030: Error: expression cannot be evaluated

And it points to Visual Studio's vector file to iterator end to the return. With insert it points to iterator begin.

THE CODE:

The first Vector is also part of a struct:

struct o3DModel
{
    vector<Vec3> v_Vertices;
};

struct Vec3 {
public:
Vec3() {}

Vec3(float X, float Y, float Z)
{
    x = X;
    y = Y;
    z = Z;
}

float x, y, z;
};

I declare the "o3DModel" struct above in my app class like this and send it to my loader class:

o3DModel *tfTable;

void TheApp::Init()
{
    objLoader->ImportOBJ(tfTable, "testcube.obj");
}

The objLoader class, where I successfully fill my "v_Vertices" vector, where "oModel" is the sent "tfTable":

bool OBJLoader::ImportOBJ(o3DModel *oModel, char *strFileName)
{
    FillObjData(oModel);
    ...
    return true;
}

void OBJLoader::FillObjData(o3DModel *oModel)
{
    oModel->v_Vertices.insert(oModel->v_Vertices.begin(), v_Vertices.begin(), v_Vertices.end());
    // This here with insert
    outFile2 << oModel->v_Vertices[0].x << "\n";
}

Hope this helps.

like image 679
matthew3r Avatar asked Mar 28 '12 16:03

matthew3r


1 Answers

If you want secondVector to take on all of the values of firstVector and no others,

secondVector = firstVector;

If you want each of the elements of firstVector to be added to the end secondVector:

secondVector.insert(secondVector.end(), 
                    firstvector.begin(), firstVector.end());

If you want each of the elements of firstVector to be added to the beginning of secondVector:

secondVector.insert(secondVector.begin(), 
                    firstVector.begin(), firstVector.end());
like image 115
Robᵩ Avatar answered Oct 17 '22 02:10

Robᵩ