Search Results

Search found 2562 results on 103 pages for 'vector'.

Page 41/103 | < Previous Page | 37 38 39 40 41 42 43 44 45 46 47 48  | Next Page >

  • Simplifying const Overloading?

    - by templatetypedef
    Hello all- I've been teaching a C++ programming class for many years now and one of the trickiest things to explain to students is const overloading. I commonly use the example of a vector-like class and its operator[] function: template <typename T> class Vector { public: T& operator[] (size_t index); const T& operator[] (size_t index) const; }; I have little to no trouble explaining why it is that two versions of the operator[] function are needed, but in trying to explain how to unify the two implementations together I often find myself wasting a lot of time with language arcana. The problem is that the only good, reliable way that I know how to implement one of these functions in terms of the other is with the const_cast/static_cast trick: template <typename T> const T& Vector<T>::operator[] (size_t index) const { /* ... your implementation here ... */ } template <typename T> T& Vector<T>::operator[] (size_t index) { return const_cast<T&>(static_cast<const Vector&>(*this)[index]); } The problem with this setup is that it's extremely tricky to explain and not at all intuitively obvious. When you explain it as "cast to const, then call the const version, then strip off constness" it's a little easier to understand, but the actual syntax is frightening,. Explaining what const_cast is, why it's appropriate here, and why it's almost universally inappropriate elsewhere usually takes me five to ten minutes of lecture time, and making sense of this whole expression often requires more effort than the difference between const T* and T* const. I feel that students need to know about const-overloading and how to do it without needlessly duplicating the code in the two functions, but this trick seems a bit excessive in an introductory C++ programming course. My question is this - is there a simpler way to implement const-overloaded functions in terms of one another? Or is there a simpler way of explaining this existing trick to students? Thanks so much!

    Read the article

  • string s; &s+1; Legal? UB?

    - by John Dibling
    Consider the following code: #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { string myAry[] = { "Mary", "had", "a", "Little", "Lamb" }; const size_t numStrs = sizeof(myStr)/sizeof(myAry[0]); vector<string> myVec(&myAry[0], &myAry[numStrs]); copy( myVec.begin(), myVec.end(), ostream_iterator<string>(cout, " ")); return 0; } Of interest here is &myAry[numStrs]: numStrs is equal to 5, so &myAry[numStrs] points to something that doesn't exist; the sixth element in the array. There is another example of this in the above code: myVec.end(), which points to one-past-the-end of the vector myVec. It's perfecly legal to take the address of this element that doesn't exist. We know the size of string, so we know where the address of the 6th element of a C-style array of strings must point to. So long as we only evaluate this pointer and never dereference it, we're fine. We can even compare it to other pointers for equality. The STL does this all the time in algorithms that act on a range of iterators. The end() iterator points past the end, and the loops keep looping while a counter != end(). So now consider this: #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { string myStr = "Mary"; string* myPtr = &myStr; vector<string> myVec2(myPtr, &myPtr[1]); copy( myVec2.begin(), myVec2.end(), ostream_iterator<string>(cout, " ")); return 0; } Is this code legal and well-defined? It is legal and well-defined to take the address of an array element past the end, as in &myAry[numStrs], so should it be legal and well-defined to pretend that myPtr is also an array?

    Read the article

  • I am getting the below mentioned error in my program. what will be the solution?

    - by suvirai
    // Finaldesktop.cpp : Defines the entry point for the console application. // include include include include include using namespace std; int SearchDirectory(vector &refvecFiles, const string &refcstrRootDirectory, const string &refcstrExtension, bool bSearchSubdirectories = true) { string strFilePath; // Filepath string strPattern; // Pattern string strExtension; // Extension HANDLE hFile; // Handle to file WIN32_FIND_DATA FileInformation; // File information strPattern = refcstrRootDirectory + "\."; hFile = FindFirstFile(strPattern.c_str(), &FileInformation); if(hFile != INVALID_HANDLE_VALUE) { do { if(FileInformation.cFileName[0] != '.') { strFilePath.erase(); strFilePath = refcstrRootDirectory + "\" + FileInformation.cFileName; if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if(bSearchSubdirectories) { // Search subdirectory int iRC = SearchDirectory(refvecFiles, strFilePath, refcstrExtension, bSearchSubdirectories); if(iRC) return iRC; } } else { // Check extension strExtension = FileInformation.cFileName; strExtension = strExtension.substr(strExtension.rfind(".") + 1); if(strExtension == refcstrExtension) { // Save filename refvecFiles.push_back(strFilePath); } } } } while(FindNextFile(hFile, &FileInformation) == TRUE); // Close handle FindClose(hFile); DWORD dwError = GetLastError(); if(dwError != ERROR_NO_MORE_FILES) return dwError; } return 0; } int main() { int iRC = 0; vector vecAviFiles; vector vecTxtFiles; // Search 'c:' for '.avi' files including subdirectories iRC = SearchDirectory(vecAviFiles, "c:", "avi"); if(iRC) { cout << "Error " << iRC << endl; return -1; } // Print results for(vector::iterator iterAvi = vecAviFiles.begin(); iterAvi != vecAviFiles.end(); ++iterAvi) cout << *iterAvi << endl; // Search 'c:\textfiles' for '.txt' files excluding subdirectories iRC = SearchDirectory(vecTxtFiles, "c:\textfiles", "txt", false); if(iRC) { cout << "Error " << iRC << endl; return -1; } // Print results for(vector::iterator iterTxt = vecTxtFiles.begin(); iterTxt != vecTxtFiles.end(); ++iterTxt) cout << *iterTxt << endl; // Wait for keystroke _getch(); return 0; }

    Read the article

  • Collision Detection probelm (intersection with plane)

    - by Demi
    I'm doing a scene using openGL (a house). I want to do some collision detection, mainly with the walls in the house. I have tried the following code: // a plane is represented with a normal and a position in space Vector planeNor(0,0,1); Vector position(0,0,-10); Plane p(planeNor,position); Vector vel(0,0,-1); double lamda; // this is the intersection point Vector pNormal; // the normal of the intersection // this method is from Nehe's Lesson 30 coll= p.TestIntersionPlane(vel,Z,lamda,pNormal); glPushMatrix(); glBegin(GL_QUADS); if(coll) glColor3f(1,0,0); else glColor3f(1,1,1); glVertex3d(0,0,-10); glVertex3d(3,0,-10); glVertex3d(3,3,-10); glVertex3d(0,3,-10); glEnd(); glPopMatrix(); Nehe's method: #define EPSILON 1.0e-8 #define ZERO EPSILON bool Plane::TestIntersionPlane(const Vector3 & position,const Vector3 & direction, double& lamda, Vector3 & pNormal) { double DotProduct=direction.scalarProduct(normal); // Dot Product Between Plane Normal And Ray Direction double l2; // Determine If Ray Parallel To Plane if ((DotProduct<ZERO)&&(DotProduct>-ZERO)) return false; l2=(normal.scalarProduct(position))/DotProduct; // Find Distance To Collision Point if (l2<-ZERO) // Test If Collision Behind Start return false; pNormal= normal; lamda=l2; return true; } Z is initially (0,0,0) and every time I move the camera towards the plane, I reduce its z component by 0.1 (i.e. Z.z-=0.1 ). I know that the problem is with the vel vector, but I can't figure out what the right value should be. Can anyone please help me?

    Read the article

  • How can I represent a line of music notes in a way that allows fast insertion at any index?

    - by chairbender
    For "fun", and to learn functional programming, I'm developing a program in Clojure that does algorithmic composition using ideas from this theory of music called "Westergaardian Theory". It generates lines of music (where a line is just a single staff consisting of a sequence of notes, each with pitches and durations). It basically works like this: Start with a line consisting of three notes (the specifics of how these are chosen are not important). Randomly perform one of several "operations" on this line. The operation picks randomly from all pairs of adjacent notes that meet a certain criteria (for each pair, the criteria only depends on the pair and is independent of the other notes in the line). It inserts 1 or several notes (depending on the operation) between the chosen pair. Each operation has its own unique criteria. Continue randomly performing these operations on the line until the line is the desired length. The issue I've run into is that my implementation of this is quite slow, and I suspect it could be made faster. I'm new to Clojure and functional programming in general (though I'm experienced with OO), so I'm hoping someone with more experience can point out if I'm not thinking in a functional paradigm or missing out on some FP technique. My current implementation is that each line is a vector containing maps. Each map has a :note and a :dur. :note's value is a keyword representing a musical note like :A4 or :C#3. :dur's value is a fraction, representing the duration of the note (1 is a whole note, 1/4 is a quarter note, etc...). So, for example, a line representing the C major scale starting on C3 would look like this: [ {:note :C3 :dur 1} {:note :D3 :dur 1} {:note :E3 :dur 1} {:note :F3 :dur 1} {:note :G3 :dur 1} {:note :A4 :dur 1} {:note :B4 :dur 1} ] This is a problematic representation because there's not really a quick way to insert into an arbitrary index of a vector. But insertion is the most frequently performed operation on these lines. My current terrible function for inserting notes into a line basically splits the vector using subvec at the point of insertion, uses conj to join the first part + notes + last part, then uses flatten and vec to make them all be in a one-dimensional vector. For example if I want to insert C3 and D3 into the the C major scale at index 3 (where the F3 is), it would do this (I'll use the note name in place of the :note and :dur maps): (conj [C3 D3 E3] [C3 D3] [F3 G3 A4 B4]), which creates [C3 D3 E3 [C3 D3] [F3 G3 A4 B4]] (vec (flatten previous-vector)) which gives [C3 D3 E3 C3 D3 F3 G3 A4 B4] The run time of that is O(n), AFAIK. I'm looking for a way to make this insertion faster. I've searched for information on Clojure data structures that have fast insertion but haven't found anything that would work. I found "finger trees" but they only allow fast insertion at the start or end of the list. Edit: I split this into two questions. The other part is here.

    Read the article

  • Calling compiled C from R with .C()

    - by Sarah
    I'm trying to call a program (function getNBDensities in the C executable measurementDensities_out) from R. The function is passed several arrays and the variable double runsum. Right now, the getNBDensities function basically does nothing: it prints to screen the values of passed parameters. My problem is the syntax of calling the function: array(.C("getNBDensities", hr = as.double(hosp.rate), # a vector (s x 1) sp = as.double(samplingProbabilities), # another vector (s x 1) odh = as.double(odh), # another vector (s x 1) simCases = as.integer(x[c("xC1","xC2","xC3")]), # another vector (s x 1) obsCases = as.integer(y[c("yC1","yC2","yC3")]), # another vector (s x 1) runsum = as.double(runsum), # double DUP = TRUE, NAOK = TRUE, PACKAGE = "measurementDensities_out")$f, dim = length(y[c("yC1","yC2","yC3")]), dimnames = c("yC1","yC2","yC3")) The error I get, after proper execution of the function (i.e., the right output is printed to screen), is Error in dim(data) <- dim : attempt to set an attribute on NULL I'm unclear what the dimensions are that I should be passing the function: should it be s x 5 + 1 (five vectors of length s and one double)? I've tried all sorts of combinations (including sx5+1) and have found only seemingly conflicting descriptions/examples online of what's supposed to happen here. For those who are interested, the C code is below: #include <R.h> #include <Rmath.h> #include <math.h> #include <Rdefines.h> #include <R_ext/PrtUtil.h> #define NUM_STRAINS 3 #define DEBUG void getNBDensities( double *hr, double *sp, double *odh, int *simCases, int *obsCases, double *runsum ); void getNBDensities( double *hr, double *sp, double *odh, int *simCases, int *obsCases, double *runsum ) { #ifdef DEBUG for ( int s = 0; s < NUM_STRAINS; s++ ) { Rprintf("\nFor strain %d",s); Rprintf("\n\tHospitalization rate = %lg", hr[s]); Rprintf("\n\tSimulation probability = %lg",sp[s]); Rprintf("\n\tSimulated cases = %d",simCases[s]); Rprintf("\n\tObserved cases = %d",obsCases[s]); Rprintf("\n\tOverdispersion parameter = %lg",odh[s]); } Rprintf("\nRunning sum = %lg",runsum[0]); #endif } naive solution While better (i.e., potentially faster or syntactically clearer) solutions may exist (see Dirk's answer below), the following simplification of the code works: out<-.C("getNBDensities", hr = as.double(hosp.rate), sp = as.double(samplingProbabilities), odh = as.double(odh), simCases = as.integer(x[c("xC1","xC2","xC3")]), obsCases = as.integer(y[c("yC1","yC2","yC3")]), runsum = as.double(runsum)) The variables can be accessed in >out.

    Read the article

  • What's the fastest lookup algorithm for a key, pair data structure (i.e, a map)?

    - by truncheon
    In the following example a std::map structure is filled with 26 values from A - Z (for key) and 0 – 26 for value. The time taken (on my system) to lookup the last entry (10000000 times) is roughly 250 ms for the vector, and 125 ms for the map. (I compiled using release mode, with O3 option turned on for g++ 4.4) But if for some odd reason I wanted better performance than the std::map, what data structures and functions would I need to consider using? I apologize if the answer seems obvious to you, but I haven't had much experience in the performance critical aspects of C++ programming. #include <ctime> #include <map> #include <vector> #include <iostream> struct mystruct { char key; int value; mystruct(char k = 0, int v = 0) : key(k), value(v) { } }; int find(const std::vector<mystruct>& ref, char key) { for (std::vector<mystruct>::const_iterator i = ref.begin(); i != ref.end(); ++i) if (i->key == key) return i->value; return -1; } int main() { std::map<char, int> mymap; std::vector<mystruct> myvec; for (int i = 'a'; i < 'a' + 26; ++i) { mymap[i] = i - 'a'; myvec.push_back(mystruct(i, i - 'a')); } int pre = clock(); for (int i = 0; i < 10000000; ++i) { find(myvec, 'z'); } std::cout << "linear scan: milli " << clock() - pre << "\n"; pre = clock(); for (int i = 0; i < 10000000; ++i) { mymap['z']; } std::cout << "map scan: milli " << clock() - pre << "\n"; return 0; }

    Read the article

  • Game Object Factory: Fixing Memory Leaks

    - by Bunkai.Satori
    Dear all, this is going to be tough: I have created a game object factory that generates objects of my wish. However, I get memory leaks which I can not fix. Memory leaks are generated by return new Object(); in the bottom part of the code sample. static BaseObject * CreateObjectFunc() { return new Object(); } How and where to delete the pointers? I wrote bool ReleaseClassType(). Despite the factory works well, ReleaseClassType() does not fix memory leaks. bool ReleaseClassTypes() { unsigned int nRecordCount = vFactories.size(); for (unsigned int nLoop = 0; nLoop < nRecordCount; nLoop++ ) { // if the object exists in the container and is valid, then render it if( vFactories[nLoop] != NULL) delete vFactories[nLoop](); } return true; } Before taking a look at the code below, let me help you in that my CGameObjectFactory creates pointers to functions creating particular object type. The pointers are stored within vFactories vector container. I have chosen this way because I parse an object map file. I have object type IDs (integer values) which I need to translate them into real objects. Because I have over 100 different object data types, I wished to avoid continuously traversing very long Switch() statement. Therefore, to create an object, I call vFactoriesnEnumObjectTypeID via CGameObjectFactory::create() to call stored function that generates desired object. The position of the appropriate function in the vFactories is identical to the nObjectTypeID, so I can use indexing to access the function. So the question remains, how to proceed with garbage collection and avoid reported memory leaks? #ifndef GAMEOBJECTFACTORY_H_UNIPIXELS #define GAMEOBJECTFACTORY_H_UNIPIXELS //#include "MemoryManager.h" #include <vector> template <typename BaseObject> class CGameObjectFactory { public: // cleanup and release registered object data types bool ReleaseClassTypes() { unsigned int nRecordCount = vFactories.size(); for (unsigned int nLoop = 0; nLoop < nRecordCount; nLoop++ ) { // if the object exists in the container and is valid, then render it if( vFactories[nLoop] != NULL) delete vFactories[nLoop](); } return true; } // register new object data type template <typename Object> bool RegisterClassType(unsigned int nObjectIDParam ) { if(vFactories.size() < nObjectIDParam) vFactories.resize(nObjectIDParam); vFactories[nObjectIDParam] = &CreateObjectFunc<Object>; return true; } // create new object by calling the pointer to the appropriate type function BaseObject* create(unsigned int nObjectIDParam) const { return vFactories[nObjectIDParam](); } // resize the vector array containing pointers to function calls bool resize(unsigned int nSizeParam) { vFactories.resize(nSizeParam); return true; } private: //DECLARE_HEAP; template <typename Object> static BaseObject * CreateObjectFunc() { return new Object(); } typedef BaseObject*(*factory)(); std::vector<factory> vFactories; }; //DEFINE_HEAP_T(CGameObjectFactory, "Game Object Factory"); #endif // GAMEOBJECTFACTORY_H_UNIPIXELS

    Read the article

  • Issues glVertexAttribPointer last 2 parameters?

    - by NoobScratcher
    Introduction Hello I will start out by explaining my setup, showing samples as I go along explaining the situation. I'm using these tools: OpenGL 3.3 GLSL 330 C++ Problem The problem is when I render the wavefront obj 3d model it gives a very weird visual glitch the model was supposed to be a square but instead its a triangluated mess with parts of the vertexes pointing in a stretched direction in massive amounts towards the bottom left side of the frustum.... Explanation: I'm using std::vectors to store my wavefront .obj model data using sscanf to get the floating point values into the structure members x,y,z and store them into the Points structure variable p; int index = IndexAssigner(1, 1); ifstream file (list[index].c_str() ); points.push_back(Point()); Point p; int face[4]; while (!file.eof() ) { char modelbuffer[10000]; file.getline(modelbuffer, 10000); switch(modelbuffer[0]) { case 'v' : sscanf(modelbuffer, "v %f %f %f", &p.x, &p.y, &p.z); points.push_back(p); break; case 'f': sscanf(modelbuffer, "f %d %d %d %d", face, face+1, face+2, face+3 ); faces.push_back(face[0]); faces.push_back(face[1]); faces.push_back(face[2]); faces.push_back(face[3]); } //Turn on FileReader aka "RENDER CODE" FileReader = true; } then I render the Points vector using the .data() member of std::vectors to the frustum. Other declarations: int numfloats = 4; float* point=reinterpret_cast<float*>(&points[0]); int num_bytes=numfloats*sizeof(float); Vector declarations: struct Point {float x, y , z; }; std::vector<int>faces; std::vector<Point>points; Render code: glGenBuffers(1, &vertexbuffer); glGenTextures(1, &ModelTexture); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBindTexture(GL_TEXTURE_3D, ModelTexture); glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA, ModelSurface->w, ModelSurface->h, 0, GL_BGR, GL_UNSIGNED_BYTE, ModelSurface->pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBufferData(GL_ARRAY_BUFFER, sizeof(points), points.data(), GL_STATIC_DRAW); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE,num_bytes ,points.data()); glEnableVertexAttribArray(3); //Translation Process GLfloat TranslationMatrix[] = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0 }; //Send Translation Matrix up to the vertex shader glUniformMatrix4fv(translation, 1, TRUE, TranslationMatrix); glDrawElements( GL_QUADS, faces.size(), GL_UNSIGNED_INT, faces.data()); I tried looking at what was causing this and went through every function every parameter ,etc looked at the man pages. Then found out that it could be my glVertexAttribPointer. Here are the man pages for glVertexAttribPointer http://www.opengl.org/sdk/docs/man/xhtml/glVertexAttribPointer.xml The last 2 parameters is my problem How do I write those 2 last parameters do I try putting the data from Points into it?. glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE,num_bytes ,points.data()); How does it work with vectors? Is it fast?* if you can not be bothered too look at the man pages here is the scripts coming from the man pages directly. Stride Specifies the byte offset between consecutive generic vertex attributes. If stride is 0, the generic vertex attributes are understood to be tightly packed in the array. The initial value is 0. Pointer Specifies a pointer to the first component of the first generic vertex attribute in the array. The initial value is 0. If you want my full source - http://ideone.com/fPfkg Thanks Again if you do read this.

    Read the article

  • Calling Matlab's MLApp.MLAppClass.FEval from F#

    - by Matthew
    Matlab provides a COM interface that supports remote execution of arbitrary functions (and code snippets). In particular, it has an Feval method that calls a given Matlab function. The third parameter to this method, pvarArgOut, has COM type VARIANT*, and appears in the Visual Studio F# editor as an argument of type: pvarArgOut: byref<obj> The following code calls interp1, which in Matlab returns a matrix (i.e. 2D double array) result, as is normal for most Matlab functions. let matlab = new MLApp.MLAppClass() let vector_to_array2d (v : vector) = Array2D.init v.Length 1 (fun i j -> v.[i]) let interp1 (xs : vector) (ys : vector) (xi : vector) = let yi : obj = new obj() matlab.Feval("interp1", 1, ref yi, vector_to_array2d xs, vector_to_array2d ys, vector_to_array2d xi) yi :?> float[,] This code compiles fine, but when calling interp1, I get a COM exception: A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll Additional information: Invalid callee. (Exception from HRESULT: 0x80020010 (DISP_E_BADCALLEE)) I get the same error whether initialize yi with a new obj, a new Array2D, or null. How does F# translate VARIANT output arguments?

    Read the article

  • simple Stata program

    - by Cyrus S
    I am trying to write a simple program to combine coefficient and standard error estimates from a set of regression fits. I run, say, 5 regressions, and store the coefficient(s) and standard error(s) of interest into vectors (Stata matrix objects, actually). Then, I need to do the following: Find the mean value of the coefficient estimates. Combine the standard error estimates according to the formula suggested for combining results from "multiple imputation". The formula is the square root of the formula for "T" on page 6 of the following document: http://bit.ly/b05WX3 I have written Stata code that does this once, but I want to write this as a function (or "program", in Stata speak) that takes as arguments the vector (or matrix, if possible, to combine multiple estimates at once) of regression coefficient estimates and the vector (or matrix) of corresponding standard error estimates, and then generates 1 and 2 above. Here is the code that I wrote: (breg is a 1x5 vector of the regression coefficient estimates, and sereg is a 1x5 vector of the associated standard error estimates) mat ones = (1,1,1,1,1) mat bregmean = (1/5)*(ones*breg’) scalar bregmean_s = bregmean[1,1] mat seregmean = (1/5)*(ones*sereg’) mat seregbtv = (1/4)*(breg - bregmean#ones)* (breg - bregmean#ones)’ mat varregmi = (1/5)*(sereg*sereg’) + (1+(1/5))* seregbtv scalar varregmi_s = varregmi[1,1] scalar seregmi = sqrt(varregmi_s) disp bregmean_s disp seregmi This gives the right answer for a single instance. Any pointers would be great! UPDATE: I completed the code for combining estimates in a kXm matrix of coefficients/parameters (k is the number of parameters, m the number of imputations). Code can be found here: http://bit.ly/cXJRw1 Thanks to Tristan and Gabi for the pointers.

    Read the article

  • Statically Compiling QWebKit 4.6.2

    - by geeko
    I tried to compile Qt+Webkit statically with MS VS 2008 and this worked. C:\Qt\4.6.2configure -release -static -opensource -no-fast -no-exceptions -no-accessibility -no-rtti -no-stl -no-opengl -no-openvg -no-incredibuild-xge -no-style-plastique -no-style-cleanlooks -no-style-motif -no-style-cde -no-style-windowsce -no-style-windowsmobile -no-style-s60 -no-gif -no-libpng -no-libtiff -no-libjpeg -no-libmng -no-qt3support -no-mmx -no-3dnow -no-sse -no-sse2 -no-iwmmxt -no-openssl -no-dbus -platform win32-msvc2008 -arch windows -no-phonon -no-phonon-backend -no-multimedia -no-audio-backend -no-script -no-scripttools -webkit -no-declarative However, I get these errors whenever building a project that links statically to QWebKit: 1 Creating library C:\Users\Geeko\Desktop\Qt\TestQ\Release\TestQ.lib and object C:\Users\Geeko\Desktop\Qt\TestQ\Release\TestQ.exp 1QtWebKit.lib(PluginPackageWin.obj) : error LNK2019: unresolved external symbol _VerQueryValueW@16 referenced in function "class WebCore::String __cdecl WebCore::getVersionInfo(void * const,class WebCore::String const &)" (?getVersionInfo@WebCore@@YA?AVString@1@QAXABV21@@Z) 1QtWebKit.lib(PluginPackageWin.obj) : error LNK2019: unresolved external symbol _GetFileVersionInfoW@16 referenced in function "private: bool __thiscall WebCore::PluginPackage::fetchInfo(void)" (?fetchInfo@PluginPackage@WebCore@@AAE_NXZ) 1QtWebKit.lib(PluginPackageWin.obj) : error LNK2019: unresolved external symbol _GetFileVersionInfoSizeW@8 referenced in function "private: bool __thiscall WebCore::PluginPackage::fetchInfo(void)" (?fetchInfo@PluginPackage@WebCore@@AAE_NXZ) 1QtWebKit.lib(PluginDatabaseWin.obj) : error LNK2019: unresolved external symbol _imp_PathRemoveFileSpecW@4 referenced in function "class WebCore::String __cdecl WebCore::safariPluginsDirectory(void)" (?safariPluginsDirectory@WebCore@@YA?AVString@1@XZ) 1QtWebKit.lib(PluginDatabaseWin.obj) : error LNK2019: unresolved external symbol _imp_SHGetValueW@24 referenced in function "void __cdecl WebCore::addWindowsMediaPlayerPluginDirectory(class WTF::Vector &)" (?addWindowsMediaPlayerPluginDirectory@WebCore@@YAXAAV?$Vector@VString@WebCore@@$0A@@WTF@@@Z) 1QtWebKit.lib(PluginDatabaseWin.obj) : error LNK2019: unresolved external symbol _imp_PathCombineW@12 referenced in function "void __cdecl WebCore::addMacromediaPluginDirectories(class WTF::Vector &)" (?addMacromediaPluginDirectories@WebCore@@YAXAAV?$Vector@VString@WebCore@@$0A@@WTF@@@Z) 1C:\Users\Geeko\Desktop\Qt\TestQ\Release\TestQ.exe : fatal error LNK1120: 6 unresolved externals Do I need to check something in the Qt project options ? I have QtCore, QtGui, Network and WebKit checked.

    Read the article

  • Parsing string, with Boost Spirit 2, to fill data in user defined struct

    - by Surya
    I'm using Boost.Spirit which was distributed with Boost-1.42.0 with VS2005. My problem is like this. I've this string which was delimted with commas. The first 3 fields of it are strings and rest are numbers. like this. String1,String2,String3,12.0,12.1,13.0,13.1,12.4 My rule is like this qi::rule<string::iterator, qi::skip_type> stringrule = *(char_ - ',') qi::rule<string::iterator, qi::skip_type> myrule= repeat(3)[*(char_ - ',') >> ','] >> (double_ % ',') ; I'm trying to store the data in a structure like this. struct MyStruct { vector<string> stringVector ; vector<double> doubleVector ; } ; MyStruct var ; I've wrapped it in BOOST_FUSION_ADAPT_STRUCTURE to use it with spirit. BOOST_FUSION_ADAPT_STRUCT (MyStruct, (vector<string>, stringVector) (vector<double>, doubleVector)) My parse function parses the line and returns true and after qi::phrase_parse (iterBegin, iterEnd, myrule, boost::spirit::ascii::space, var) ; I'm expecting var.stringVector and var.doubleVector are properly filled. but it is not the case. What is going wrong ? Thanks in advance, Surya

    Read the article

  • Boost Mersenne Twister: how to seed with more than one value?

    - by Eamon Nerbonne
    I'm using the boost mt19937 implementation for a simulation. The simulation needs to be reproducible, and that means storing and potentially reusing the RNG seeds later. I'm using the windows crypto api to generate the seed values because I need an external source for the seeds and not because of any particular guarantees of randomness. The output of any simulation run will have a note including the RNG seed - so the seed needs to be reasonably short. On the other hand, as part of the analysis of the simulation, I'll be comparing several runs - but to be sure that these runs are actually different, I'll need to use different seeds - so the seed needs to be long enough to avoid accidental collisions. I've determined that 64-bits of seeding should suffice; the chance of a collision will reach 50% after about 2^32 runs - that probability is low enough that the average error caused by it is negligible to me. Using just 32-bits of seed is tricky; the chance of a collision reaches 50% already after 2^16 runs; and that's a little too likely for my tastes. Unfortunately, the boost implementation either seeds with a full state vector - which is far, far too long - or a single 32-bit unsigned long - which isn't ideal. How can I seed the generator with more than 32-bits but less than a full state vector? I tried just padding the vector or repeating the seeds to fill the state vector, but even a cursory glance at the results shows that that generates poor results.

    Read the article

  • best way to pick a random subset from a collection?

    - by Tom
    I have a set of objects in a Vector from which I'd like to select a random subset (e.g. 100 items coming back; pick 5 randomly). In my first (very hasty) pass I did an extremely simple and perhaps overly clever solution: Vector itemsVector = getItems(); Collections.shuffle(itemsVector); itemsVector.setSize(5); While this has the advantage of being nice and simple, I suspect it's not going to scale very well, i.e. Collections.shuffle() must be O(n) at least. My less clever alternative is Vector itemsVector = getItems(); Random rand = new Random(System.currentTimeMillis()); // would make this static to the class List subsetList = new ArrayList(5); for (int i = 0; i < 5; i++) { // be sure to use Vector.remove() or you may get the same item twice subsetList.add(itemsVector.remove(rand.nextInt(itemsVector.size()))); } Any suggestions on better ways to draw out a random subset from a Collection?

    Read the article

  • Ways std::stringstream can set fail/bad bit?

    - by Evan Teran
    A common piece of code I use for simple string splitting looks like this: inline std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } Someone mentioned that this will silently "swallow" errors occurring in std::getline. And of course I agree that's the case. But it occurred to me, what could possibly go wrong here in practice that I would need to worry about. basically it all boils down to this: inline std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } if(ss.fail()) { // *** How did we get here!? *** } return elems; } A stringstream is backed by a string, so we don't have to worry about any of the issues associated with reading from a file. There is no type conversion going on here since getline simply reads until it sees a newline or EOF. So we can't get any of the errors that something like boost::lexical_cast has to worry about. I simply can't think of something besides failing to allocate enough memory that could go wrong, but that'll just throw a std::bad_alloc well before the std::getline even takes place. What am I missing?

    Read the article

  • How to keep only duplicates efficiently?

    - by Marc Eaddy
    Given an STL vector, I'd like an algorithm that outputs only the duplicates in sorted order, e.g., INPUT : { 4, 4, 1, 2, 3, 2, 3 } OUTPUT: { 2, 3, 4 } The algorithm is trivial, but the goal is to make it as efficient as std::unique(). My naive implementation modifies the container in-place: My naive implementation: void keep_duplicates(vector<int>* pv) { // Sort (in-place) so we can find duplicates in linear time sort(pv->begin(), pv->end()); vector<int>::iterator it_start = pv->begin(); while (it_start != pv->end()) { size_t nKeep = 0; // Find the next different element vector<int>::iterator it_stop = it_start + 1; while (it_stop != pv->end() && *it_start == *it_stop) { nKeep = 1; // This gets set redundantly ++it_stop; } // If the element is a duplicate, keep only the first one (nKeep=1). // Otherwise, the element is not duplicated so erase it (nKeep=0). it_start = pv->erase(it_start + nKeep, it_stop); } } If you can make this more efficient, elegant, or general, please let me know. For example, a custom sorting algorithm, or copy elements in the 2nd loop to eliminate the erase() call.

    Read the article

  • Declaring functors for comparison ??

    - by Mr.Gando
    Hello, I have seen other people questions but found none that applied to what I'm trying to achieve here. I'm trying to sort Entities via my EntityManager class using std::sort and a std::vector<Entity *> /*Entity.h*/ class Entity { public: float x,y; }; struct compareByX{ bool operator()(const GameEntity &a, const GameEntity &b) { return (a.x < b.x); } }; /*Class EntityManager that uses Entitiy*/ typedef std::vector<Entity *> ENTITY_VECTOR; //Entity reference vector class EntityManager: public Entity { private: ENTITY_VECTOR managedEntities; public: void sortEntitiesX(); }; void EntityManager::sortEntitiesX() { /*perform sorting of the entitiesList by their X value*/ compareByX comparer; std::sort(entityList.begin(), entityList.end(), comparer); } I'm getting a dozen of errors like : error: no match for call to '(compareByX) (GameEntity* const&, GameEntity* const&)' : note: candidates are: bool compareByX::operator()(const GameEntity&, const GameEntity&) I'm not sure but ENTITY_VECTOR is std::vector<Entity *> , and I don't know if that could be the problem when using the compareByX functor ? I'm pretty new to C++, so any kind of help is welcome.

    Read the article

  • Issue with clipping rectangles and back to front rendering

    - by Milo
    Here is my problem. My rendering algorithm renders from back to front. But logically, clipping rectangles need to be applied from front to back. Hence why the following does not work: void AguiWidgetManager::recursiveRender(const AguiWidget *root) { //recursively calls itself to render widgets from back to front AguiWidget* nonConstRoot = (AguiWidget*)root; if(!nonConstRoot->isVisable()) { return; } //push the clipping rectangle if(nonConstRoot->isClippingChildren()) { graphicsContext->pushClippingRect(nonConstRoot->getClippingRectangle()); } if(nonConstRoot->isEnabled()) { nonConstRoot->paint(AguiPaintEventArgs(true,graphicsContext)); for(std::vector<AguiWidget*>::const_iterator it = root->getPrivateChildBeginIterator(); it != root->getPrivateChildEndIterator(); ++it) { recursiveRender(*it); } for(std::vector<AguiWidget*>::const_iterator it = root->getChildBeginIterator(); it != root->getChildEndIterator(); ++it) { recursiveRender(*it); } } else { nonConstRoot->paint(AguiPaintEventArgs(false,graphicsContext)); for(std::vector<AguiWidget*>::const_iterator it = root->getPrivateChildBeginIterator(); it != root->getPrivateChildEndIterator(); ++it) { recursiveRenderDisabled(*it); } for(std::vector<AguiWidget*>::const_iterator it = root->getChildBeginIterator(); it != root->getChildEndIterator(); ++it) { recursiveRenderDisabled(*it); } } //release clipping rectangle if(nonConstRoot->isClippingChildren()) { graphicsContext->popClippingRect(); } } I could ofcourse go to the top of the tree, then apply clipping rectangles inward until I get to the currently rendered widget, but that would involve lots of clipping rectangles @ 60 frames per second. I want to minimize calls to pushing and popping rectangles. What could I do, Thanks

    Read the article

  • Why might stable_sort be affecting my hashtable values?

    - by zebraman
    I have defined a struct ABC to contain an int ID, string NAME, string LAST_NAME; My procedure is this: Read in a line from an input file. Parse each line into first name and last name and insert into the ABC struct. Also, the struct's ID is given by the number of the input line. Then, push_back the struct into a vector masterlist. I am also hashing these to a hashtable defined as vector< vector , using first name and last name as keywords. That is, If my data is: Garfield Cat Snoopy Dog Cat Man Then for the keyword cash hashes to a vector containing Garfield Cat and Cat Man. I insert the structs into the hashtable using push_back again. The problem is, when I call stable_sort on my masterlist, my hashtable is affected for some reason. I thought it might be happening since the songs are being ordered differently, so I tried making a copy of the masterlist and sorting it and it still affects the hashtable though the original masterlist is unaffected. Any ideas why this might be happening?

    Read the article

  • Weird behaviour of C++ destructors

    - by Vilx-
    #include <iostream> #include <vector> using namespace std; int main() { vector< vector<int> > dp(50000, vector<int>(4, -1)); cout << dp.size(); } This tiny program takes a split second to execute when simply run from the command line. But when run in a debugger, it takes over 8 seconds. Pausing the debugger reveals that it is in the middle of destroying all those vectors. WTF? Note - Visual Studio 2008 SP1, Core 2 Duo 6700 CPU with 2GB of RAM. Added: To clarify, no, I'm not confusing Debug and Release builds. These results are on one and the same .exe, without even any recompiling inbetween. In fact, switching between Debug and Release builds changes nothing.

    Read the article

  • Idiomatic STL: Iterating over a list and inserting elements

    - by mkilling
    I'm writing an algorithm that iterates over a list of points, calculates the distance between them and inserts additional points if the distance is too great. However I seem to be lacking the proper familiarity with STL to come up with an elegant solution. I'm hoping that I can learn something, so I'll just show you my code. You might have some hints for me. for (std::list<PathPoint>::iterator it = ++points_.begin(); it != points_.end(); it++) { Vector curPos = it->getPosition(); Vector prevPos = (--it)->getPosition(); Vector vecFromPrev = curPos - prevPos; float distance = vecFromPrev.abs(); it++; if (distance > MAX_DISTANCE_BETWEEN_POINTS) { int pointsToInsert = (int)(distance / MAX_DISTANCE_BETWEEN_POINTS); Vector curPos = prevPos; for (int i = 0; i < pointsToInsert; i++) { curPos += vecFromPrev / pointsToInsert; it = points_.insert(it, PathPoint(curPos, false)); it++; } } }

    Read the article

  • Fastest way to modify a decimal-keyed table in MySQL?

    - by javanix
    I am dealing with a MySQL table here that is keyed in a somewhat unfortunate way. Instead of using an auto increment table as a key, it uses a column of decimals to preserve order (presumably so its not too difficult to insert new rows while preserving a primary key and order). Before I go through and redo this table to something more sane, I need to figure out how to rekey it without breaking everything. What I would like to do is something that takes a list of doubles (the current keys) and outputs a list of integers (which can be cast down to doubles for rekeying). For example, input {1.00, 2.00, 2.50, 2.60, 3.00} would give output {1, 2, 3, 4, 5). Since this is a database, I also need to be able to update the rows nicely: UPDATE table SET `key`='3.00' WHERE `key`='2.50'; Can anyone think of a speedy algorithm to do this? My current thought is to read all of the doubles into a vector, take the size of the vector, and output a new vector with values from 1 => doubleVector.size. This seems pretty slow, since you wouldn't want to read every value into the vector if, for instance, only the last n/100 elements needed to be modified. I think there is probably something I can do in place, since only values after the first non-integer double need to be modified, but I can't for the life of me figure anything out that would let me update in place as well. For instance, setting 2.60 to 3.00 the first time you see 2.50 in the original key list would result in an error, since the key value 3.00 is already used for the table.

    Read the article

  • Fastest way to convert a list of doubles to a unique list of integers?

    - by javanix
    I am dealing with a MySQL table here that is keyed in a somewhat unfortunate way. Instead of using an auto increment table as a key, it uses a column of decimals to preserve order (presumably so its not too difficult to insert new rows while preserving a primary key and order). Before I go through and redo this table to something more sane, I need to figure out how to rekey it without breaking everything. What I would like to do is something that takes a list of doubles (the current keys) and outputs a list of integers (which can be cast down to doubles for rekeying). For example, input {1.00, 2.00, 2.50, 2.60, 3.00} would give output {1, 2, 3, 4, 5). Since this is a database, I also need to be able to update the rows nicely: UPDATE table SET `key`='3.00' WHERE `key`='2.50'; Can anyone think of a speedy algorithm to do this? My current thought is to read all of the doubles into a vector, take the size of the vector, and output a new vector with values from 1 => doubleVector.size. This seems pretty slow, since you wouldn't want to read every value into the vector if, for instance, only the last n/100 elements needed to be modified. I think there is probably something I can do in place, since only values after the first non-integer double need to be modified, but I can't for the life of me figure anything out that would let me update in place as well. For instance, setting 2.60 to 3.00 the first time you see 2.50 in the original key list would result in an error, since the key value 3.00 is already used for the table.

    Read the article

  • Your favourite C++ Standard Library wrapper functions?

    - by Neil Butterworth
    This question, asked this morning, made me wonder which features you think are missing from the C++ Standard Library, and how you have gone about filling the gaps with wrapper functions. For example, my own utility library has this function for vector append: template <class T> std::vector<T> & operator += ( std::vector<T> & v1, const std::vector <T> v2 ) { v1.insert( v1.end(), v2.begin(), v2.end() ); return v1; } and this one for clearing (more or less) any type - particularly useful for things like std::stack: template <class C> void Clear( C & c ) { c = C(); } I have a few more, but I'm interested in which ones you use? Please limit answers to wrapper functions - i.e. no more than a couple of lines of code.

    Read the article

< Previous Page | 37 38 39 40 41 42 43 44 45 46 47 48  | Next Page >