question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
6,203,015
6,203,029
Automatically generate a uml diagram of my c++ code
Some time ago I was a TA in a introductory programming course on Java. We used an IDE called BlueJ which had the nice feature that the overview of your development files was a light-weight UML diagram with 'usage' pointers and inheritance pointers drawn in, this made it easy to see the structure of the program. My que...
Do you know about Doxygen and its many options? In fact, Google's number two hit for Doxygen and UML is this previous StackOverflow question.
6,203,019
6,203,658
No call stack in VS2010 debugger
I've got an app that loads a DLL, and subsequently crashes. I modified the IDE's working directory to be the solution build directory, so that I could run the debugger on the built DLL which is built from another project in this solution. When the app gets an access violation, I can see the current function, but nothin...
Having the debugger work when it hits a break point and fails when you break after an access violation in native code usually a sign that the access violation is preceded or accompanied by a corruption of the stack. The debugger depends on certain values in the stack being properly set in order for it to both build t...
6,203,124
6,203,403
(Not) Pointer Adjusting ruining my day and the heap? (C++)
-edit2- I was going down the wrong path. I solved it by correcting one typo and adding one line to fix an oversight that allowed me to write 4 bytes to many over an array. -edit- maybe i am running through a wrong path. Maybe VS is showing me incorrect data but still runs the code properly (after all my code does show ...
If you are using linux you might be able to use Valgrind. This is an exellent tool for finding heap related issues.
6,203,266
6,203,316
cannot open source file "stdafx.h"
I have two include file headers #include "stdafx.h" #include "psapi.h" However it gives a cannot open source file "stdafx.h" compile time error. I am using Visual Studios 2010. Is "stdafx.h" even necessary? I think so because the program cannot compile if i take it away.
Visual Studio uses it for "precompiled headers" feature. If you are not experienced with Visual Studio, I would recommend to keep the stdafx.h in the project. And of course, if you #include it, you ought to have it.
6,203,429
6,204,764
Access Violation calling imported function
I've got a function imported from a DLL. I control the source of both the host executable and the dynamic library. Now, in DLLMain then I used MessageBox to pop up the address of the function I'm exporting, and compared it using a breakpoint to the function pointer returned by GetProcAddress, and they're identical. Ho...
I completely failed this one. Wrote a class that manages a resource without respecting my move and copy semantics properly. Turns out that I was calling FreeLibrary() on the library in question mistakenly before I needed to use it.
6,203,539
6,322,801
How can I receive multipart messages with ZeroMQ?
I can't get ZeroMQ C++ wrapper to receive multipart messages. The same code using C version works just fine, but it leads to an exception with no explanations at all with C++. The multipart handling code is as follows: int _tmain(int argc, _TCHAR* argv[]) { zmq::context_t context(1); zmq::socket_t socket(contex...
I decided to use the C version of the code. In general all examples seem to be in C anyway.
6,203,598
6,203,900
C++ std::out_of_range error when I try to run the program
Okay so first off, Im pretty new to programming, Ive only read a bit of stuff and have been working on some project Euler problems to kind of wrap my head around concepts and such. However, I got an error message today that I couldn't make any sense of so I thought I would ask here for some help! Any links or advice is...
As other answers have already pointed out, in substr If the position passed is past the end of the string, an out_of_range exception is thrown. In your code: for (int j = i; j<(i+4); j++) When i is 1 less than s_testnum.length() j goes past s_testnum.length() and when you do, s_testnum.substr(j, 1); causes an out_of_r...
6,203,790
6,205,040
Boost binary serialization with a map and doubles crashes on serialize in
This is a sample that represents my problem. The map will serialize perfectly fine unless finalTime is greater than 25. With boost unit testing I was given a std::exception input stream error. Also, this code works fine using polymorphic_text_archives. The error occurs while reading in the map. #include <fstream> #incl...
You need to serialize to a binary file stream. Add the ios_base::binary to the stream constructors.
6,203,902
6,206,491
User defined Class Serialization, C++ and msgpack
I am quite new trying msgpack. I need to serialize an object (instance of an user defined class), that contains pointers (internal tree, hashes,etc), and some basic types attributes. Until now I can do what is done in the quick example of msgpack.org wiki, just serialize the class to a msgpack::sbuffer, and then read ...
From the example here: http://wiki.msgpack.org/pages/viewpage.action?pageId=1081387 it looks like sbuf.data() would return the address, and sbuf.size() would return the size, of the data which you would write to the binary file. When you want to load the data from a binary file, read it into a buffer you've allocated a...
6,203,925
6,204,206
15Bit Color Components, Bit shifting
Okay bit shifting is still a bit weird to me. I've got a 16bit value. The first 15 bits are colors and the last bit is alpha. I have done this with 24 and 32 bit colors no problem as they are nice byte size's to deal with, but I cant seem to get this to work with 15/16 bits. This is what I've done in the past, with 24/...
If I understand correctly: red = (packed >> 0) & 0x1F; green = (packed >> 5) & 0x1F; blue = (packed >> 10) & 0x1F; alpha = (packed >> 15) & 0x01; packed should better be an unsigned and I'm probably off for the order.
6,203,943
6,203,967
operator<< stackoverflow
Consider the following code : class TextMessage{ public : TextMessage(){}; TextMessage(std::string _text):text(_text){} std::string text; friend std::ostream & operator<<( std::ostream & os, const TextMessage & m); }; std::ostream & operator<<( std::ostream & os, const TextMessage & m){ return os <...
I'm guessing that you failed to #include <string>. Thus, when the compiler comes to output a std::string, it can't, and starts looking for implicit conversions- and your implicit constructor to a TextMessage looks like just the bill. But wait- now we're outputting a TextMessage in the TextMessage's output function, and...
6,203,961
6,215,973
Problems in configuring OpenWrt for socket programming
I have a code which receives packets from the Ethernet and sends it via wireless network. This works on a wireless box which uses OpenWrt. The code is written below. It gives me the following error at runtime. Based on the printf statements I feel the error is somewhere on this syntax, but I cant figure out whats wrong...
In the main(), replace v2vmessage* buf by v2vmessage buf and in the following while(1), replace the buf by &buf to solve the problem. Since, no memory was allocated to the pointer, hence it gave an error at runtime.
6,204,152
6,204,275
Reducing C++ code size
I am working on a dynamic language (that compiles into C++) for microcontrollers, being a CS guy I decided to do it properly first then worry about optimization. Below is how my object system is structured, Base (Interface) | |---- Number (Interface) | | | |-- Int | |-- Float | |---- Char | |---- Sequ...
During the link step, you should have avr-gcc generate a map file so you can look at it and see what is taking up so much space. Be sure to use the -ffunction-sections compilation option and the -Wl,-gc-sections linker option to remove unused functions from the binary. What features of C++ are you using? Some of them ...
6,204,171
6,204,346
Assertion Error in Dialog manipulation
The title is pretty weak, but I will try to explain here. I am working on an MFC Application. When a button is clicked, a new dialog is created, some strings are added to a ComboBox from that second dialog, and then the dialog is showed. The code is depicted below. Combo1 is a CComboBox variable defined in the Class1.h...
You can add the strings to the combo box inside of OnInitDialog(), which gets called automatically during DoModal(): In the header: class CClass1 : public CDialog { protected: virtual BOOL OnInitDialog(); } In the cpp file: BOOL CClass1::OnInitDialog() { __super::OnInitDialog(); Combo1.AddString(TE...
6,204,378
6,204,461
C++ DLL function does not seem to work in C#
I have developed a small program using C# and bird.dll, but the birdRS232WakeUp() function seem not to be working. When I call the birdRS232WakeUp() function in C++ the program will stop for a while (8-10 seconds). It looks like it is beginning to do the process connecting with the hardware (Flock of bird). But in C#, ...
Not sure if these points will solve your problem, but: 1) pwComport should be declared as ushort[] pwComport, not ref ushort[] pwComport 2) you need to pass nGroupMode parameter from C#. You can set it to default value if you use C#4, but don't ignore it at all.
6,204,395
6,204,513
event handling inheritance (C++)
I am redesigning how events (related to data) are handled for existing code (in C++). The events to be handled are DataTable related events, and XmlNode related events. I'm wanting to create a general super class with virtual functions (calling it EventManager) in order to provide consistency across the application. I ...
Pass the arguments by reference, passing by value just adds an additional overhead. But by using it in the virtual functions, I will have lost information unique to the derived event args. You can use dynamic_cast and check the validity of the downcast, no information will be lost.
6,204,576
6,215,497
How do I prevent the creation of a new property in a Luabind class?
I'm using Luabind to bind C++ classes to Lua. From the Lua script, I can add arbitrary properties (key/value pairs) to the tables that represent my classes, even if I never told Luabind these properties exist: cheese = Cheese() cheese.type = "gouda" cheese.age = 2 cheese.hippopotamus = "monkey" -- Oops! This member was...
I don't speak from experience, but here are some email threads from the luabind-user mailing list: first, a monologue by a guy trying to do exactly what you want. Second, somewhat old (Nov 2009) email from the luabind maintainer, stating that providing custom __newindex metamethod is not currently possible, but planned...
6,204,621
6,218,183
Sending an HTTP request using QNetworkAccessManager
I've got a problem trying to send a request using QNetworkAccessManager from a QObject derived class. Firstly in my constructor I do the following: QObject::connect( &mAccessManager, SIGNAL( finished( QNetworkReply* ) ), this, SLOT( requestFinished( QNetworkReply* ) ) ); Then when I wish to send the request I do the f...
Ok so it turns out the problem is caused byt the fact that Qt does not include SSL support by default. http://doc.qt.nokia.com/4.7/ssl.html
6,204,632
6,204,656
swap fails in case of int and works in case of string
#include <iostream> #include <string> #include <algorithm> int main() { std::string str1 = "good", str2 = "luck"; swap(str1,str2); /*Line A*/ int x = 5, y= 3; swap(x,y); /*Line B*/ } If I comment Line B the code compiles(http://www.ideone.com/hbHwf) whereas commenting Line A the code fails to compile(http://ww...
swap(str1, str2) works because of Argument dependent lookup P.S: Pitfalls of ADL
6,204,679
6,205,113
c++ functional programming ( boost::phoenix && boost::spirit) testing for null-ptrs in pointer placeholders
So, I have the following spirit karma rule body: base_rule = eps(_r1 != 0) [ // _r1 is a pointer_typed placeholder eps ] ; which leads to a rather long error message from g++ which (helpfully) ends with : /opt/dev_64_swat/Boost/include/boost/spirit/home/phoenix/operator/comparison.hpp :37:5: error: I...
Using implicit pointer-to-bool conversion, as suggested in my comment, works for me out of the box with Boost 1.46.1. The following is a minimal repro wherein parse succeeds if (and only if) p != 0 && input == "not null" or p == 0 && input == "null": #include <string> #include <ios> #include <ostream> #include <iostrea...
6,204,734
10,122,432
Convert C++ code to C#
Im having very tough challenge in converting the following code C#, can anybody help me on how do we do that. typedef struct ACSNameAddr_t { char FAR *serverName; // How do i use FAR in C# struct { short length; unsigned char FAR *value; } serverAddr; } ACSNameAddr_t; and how do i use th...
So including all your answers, here by i'm writing the converted code. Please edit it if there is anything wrong, it might be useful for someone.. [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct ACSNameAddr_t { string serverName; [StructLayout(LayoutKind.Sequential, Pack = 4)] public stru...
6,204,834
6,205,036
heap vs data segment vs stack allocation
Am looking at the following program and not sure how the memory is allocated and why: void function() { char text1[] = "SomeText"; const char* text2 = "Some Text"; char *text = (char*) malloc(strlen("Some Text") + 1 ); } In the above code, the last one is obviously in the heap. However, as I understand tex...
// Array allocated on the stack and initialized with "SomeText" string. // It has automatic storage duration. You shouldn't care about freeing memory. char text1[] = "SomeText"; // Pointer to the constant string "Some Text". // It has static storage duration. You shouldn't care about freeing memory. // Note that it s...
6,205,099
6,205,600
Detect when two keys are pressed on the same time
I want to do something when two keys are pressed at the same time. This is not working for me. Don't know why. if(GetAsyncKeyState(VK_F12) && GetAsyncKeyState(VK_F1)) { MessageBoxA(0, "Injection is working!", "Succes!", MB_ICONINFORMATION | MB_OK); } I want to know how to achieve so that code is executed when I pres...
How do you know your code is getting called at the time the keys are getting pressed? For your code to be getting called your in ether: in the message pump, in which case handle the WM_KEYUP or WM_KEYDOWN events, and check if the keys are "down" at the same time. in a timer thread, not sure the best way here.
6,205,681
6,207,150
How and when is the memory of a global or static array allocated?
When defining a global or static array in c++ its memory is not immediately reserved at the start of the programme but only once we write to the array. What I found surprising is, if we only write to a small part of the array it still does not reserve the entire memory. Consider the following small example which writes...
There are two things in play here viz. virtual memory and physical memory. The virtual memory for for the static data, just like the instructions for your program are assigned before your program begins execution. By this I mean that the address, for your program is always defined. The operating system might be lazy, h...
6,205,826
6,206,640
Open CV 2.2 Include Directory Missing
I have several Windows 7 64bit systems with OpenCV 2.2 installed on them using CMake and Visual Studio 2008 Standard. CMake generates everything in C:\libs\OpenCV-2.2.0\build just fine and Visual Studio 2008 compiles everything without complaint. However, every time I do this process on various machines I find that the...
To solve this problem compile everything in release and debug then right click the INSTALL project in Visual Studio 2008 and choose Build. This will "install" numerous files and move all the include files into the proper location. Now /include will contain subfolders opencv opencv2 and /include/opencv2 will contain n...
6,205,840
6,206,005
How to determine type of widget in a qtable cell?
I have created a QTable with lots of gui elements like comboBoxes and checkBoxes in various cells. I am able to access these elements by creating pointers to them. What I want to know is, is there any way to know what type of widget(comboBox or checkBox) a cell is having?
Check out the answers to this question. The accepted answer gets the class name (as a const char*) from the widget's meta-object like so: widget->metaObject()->className(); There's another answer that suggests using C++'s type management, but that sounds a lot less wieldly (more unwieldy?).
6,205,908
6,205,935
Determing type of DataTable event in C++
I am creating an inheritance model for event handling (particularly for DataTables and XmlNode). I have a super class called EventManager with the following virtual functions: DataChanged(EventArgs *arg) DataChanging(EventArgs *arg) DataInserted(EventArgs *arg) DataInserting(EventArgs *arg) DataRemoved(EventArgs *arg) ...
Normally, you should invoke derived-class functionality using virtual functions. However, if you really must test for a type, do this: DataRowChangeEventArgs* foo = dynamic_cast<DataRowChangeEventArgs*>(arg); if (foo) { // is a DataRowChangeEventArgs } Of course, you can also roll that into a single line: if (Data...
6,205,960
6,206,219
How do I build a runtime version agnostic DLL in C++?
My product is a C++ library, which, on Windows, is distributed as a dll. It makes very little use of the c-runtime (basic iostream and that's it), so I'm sure that all recent versions of the CRT will be fine. Since my client is supposed to build his application using my dll, I don't want to impose upon him any specific...
There's no real way to ensure your DLL works with multiple runtimes -- any of the types that change between them can lead to incompatibilities. For instance, the size of an object can change, or the location of members in them. There is very little room in C++ for this kind of thing. The best thing you can do is stat...
6,206,144
6,206,628
How Can A .dll File Read a .txt File?
I would like my Browser Helper Object which is simply a .dll, to be able to read a text file. I have tried using a pointer to a FILE, as well as ifstream in("file name goes here"). Before implementing these two methods of reading files into the BHO, I tested them individually, and made sure each example dealt with simi...
Are you providing an absolute path to the file? If you're just using a relative path you may not be in the same working directory while running IE.
6,206,152
6,206,174
Do static libraries, which depend on other slibs need the actual 'code' from them to work?
Sorry about the vague question title, I just want to ascertain some things. Static libraries don't link with other static libraries, right? So when I write a slib: A, that uses functionality of another: B, all I have to provide are the headers of B to A, and only those, even if A actually uses functionality from B? Ye...
Yes, you have got it pretty much right. Executables (and DLLs) which depend on static libraries cannot be created without those dependencies being resolved, but static libraries that contain dependencies on other static libraries do not require those dependencies to be resolved at static library creation time. In fac...
6,206,302
6,206,722
C++ - How to use a stream to parse a file?
I have a file and I need to loop through it assigning an int foo, string type, 64/128 bit long. How would I use a stream to parse these lines into the following variables - I want to stick with the stream syntax ( ifs >> foo >> type ) but in this case type would end up being the rest of the line after the 0/52 ... and ...
This is a rather trivial task for a more sophisticated parser such as boost.spirit. To solve this using just the standard C++ streams you would need to a) treat ' as whitespace and b) take an extra pass over the string "04001C0180000000000000000EE317BC" which has no separators between the values. Borrowing Jerry Co...
6,206,431
6,206,475
c++ ofstream.put(char) gives weird output
I'm just new to the forums and I am having problems with my c++ script. I need to output an array of string type to an output txt file. I have an array, converted it to chars and still problems. It gives you the first 2 lines, but the rest is either Ì or ¤. Another problem is the fact that I need to make an endl, put t...
Well, what is the problem to use the ofile in the loop with the same syntax, as before the loop? ofile << oBoard[i][j]; instead of ofile.put(oBoard[i][j]);
6,206,592
6,206,908
STL + typedefs vs. OOP, best practices?
I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like: typedef std::map<std::string, std::map<std::string, int> > CSVData; Obviously there are limits...
If this is for some one-off code: sure, use typedefs, why not? But code rarely is. And the problem with reusable code (or code that will, potentially, at some future point be reused) is: there are 1000 different ways of using it wrongly. Don’t artificially add reasons 1001–1255. Code should be easy to use, and hard to ...
6,206,678
6,206,718
Performance of operator| vs operators+
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this: uint64_t dostuff(uint64_t a,uint64_t b){ // the max values of the inputs are 2^32 - 1 // lots of stuff involving boolean operators ...
No performance difference on any modern computer. The two operators have different meaning though. If the bit is already set, | will do nothing, but + will clear the bit and all the following non-zero bits and set the next zero bit to 1.
6,206,875
6,206,912
How do I use C++ STL list without iterator?
I need to get to the items in the STL list. I believe those items are of type list_item or ListItem. I need 'next' and 'prev' of each item. how do I do that?
std::list does not support next or prev by itself. The iterator is used to go from element to element, and you cannot traverse a standard list without it.
6,206,892
6,206,995
Qt - unresolved overload function type
I am getting the following error when trying to build my app in Qt Creator: error (line 3): no matching function for call to ‘QGraphicsScene::QGraphicsScene()’ The source for this is simply (file name is gamscene.cpp): #include "gamescene.h" GameScene::GameScene() : QGraphicsScene(parent) { } I have googled around a...
We've derived from the QGraphicsScene class like so class ImprintTemplateScene : public QGraphicsScene { Q_OBJECT public: ImprintTemplateScene(QObject *parent = 0); ... }; Notice the parent is a parameter passed to the constructor. The constructor implementation looks like: ImprintTemplateScene::...
6,206,977
6,207,071
copying c++ abstract classes
Ok heres some code. #include <iostream> #include <deque> using namespace std; class A { public: virtual void Execute() { cout << "Hello from class A" << endl; } }; class B: public A { public: void Execute() { cout << "Hello from class B" << endl; } }; void Main() { deque<A *>...
The common pattern for handling that is through a virtual clone() method in the base class that will create a new object of the appropriate type: struct base { virtual ~base() {} // don't forget the virtual destructor virtual base* clone() const { return new base(*this); } }; struct der...
6,207,114
6,207,258
how to force sleep or any other type of timer to execute at particular time in c++?
I am doing socket programming in C and I want to do the following thing: pid = fork(); if(pid == 0){ //child process for(int m=0;m<2;m++){ j=0; for(i=0;i<len_neighbors;i++){ socket_des1[i] = get_socket_connection_client(hostname1, neighbor_socket[i],(char *) "udp"); //s...
I can only guess what is the problem (please add the child code creation to check), I think that when this code is executed by the first child the number of neighbors is 0, with the second the number will be 1, and so on. I would try with a sleep at the beginning so this gives enough time to the others children to fork...
6,207,216
6,207,334
Why does linking against static runtime libraries in Visual C++ 2008 still requires MSVCR71.dll at runtime?
I'm building a dll statically linked against the c runtime libraries. Why then does it require MSVCR71.dll at runtime?
msvcr71.dll is Visual C++ 2003's C runtime. If you're building with 2008, there's no reason there should be a reference to this DLL. My guess is that you depend on another DLL which was built with 2003, and which uses the dynamically linked runtime.
6,207,389
6,207,733
How to dynamically load a C# dll from a C++ DLL
I have a C++ application. This supports users' C++ plugin DLL's, it will dynamically load these DLL's and then be able to create and use the user's types dynamically. These user types derive from base types and interfaces defined in the main application's core library, so I hold user's objects as pointers to the base ...
Another way of doing this would be creating a C++/CLI project that hosts your C# classes and use it as a bridge in your C++ project. A few more links to this approach: Connecting c++ and c# code with a c++/cli bridge .NET to C++ Bridge The latest link has simple source code for the bridge
6,207,516
6,344,509
LPC1700 won't wake up from deep sleep
I have firmware running on LPC1754, 59 and 68 + FreeRTOS + CMSIS. I'd like to be able to put the microcontroller in the lowest power mode possible, but: "sleep" is not enough. Once the microcontroller is in "deep sleep", "power down" or "deep power down", I can't wake it anymore by pressing a button (EINT3). As far a...
From UM10360 - User manual, Rev. 2 — 19 August 2010 page 758: Remark: If the processor detects a connection to a debugger it disables the WIC. So it won't wake up!!! What a shame...
6,207,684
6,207,837
Qt: Storing a custom object in a collection by value
Let's say I have this class: class Bear { public: Bear (); Bear (Bear &other); // ... methods private: BearInfo* m_pInfo; }; Can I store Bear objects in a QList<Bear> by value? According to the documentation: Internally, QList<T> is represented as an array of pointers to items of type T. If T is it...
Use a QVector, the Qt Documentation states this: QList, QLinkedList, and QVarLengthArray provide similar functionality. Here's an overview: For most purposes, QList is the right class to use. Operations like prepend() and insert() are usually faster than with QVector because of the way QList stores its items in memory...
6,207,936
6,208,032
C++ typecasting vs implicit constructor
I'm implementing a c++-class representing a fraction. Here goes my code. class Fraction { public: Fraction(char i); Fraction(int i); Fraction(short i); Fraction(long int l); #ifdef __LP64__ Fraction(long long l); #endif Fraction(float f); Fraction(double d); ...
By definition the conversion operators are implicit. You can't make them explicit. The normal solution is named member functions to do the conversion. I think you could also create a specialized template method that would look just like a static_cast and call through to the explicit class method.
6,208,202
6,208,285
Can someone explain the parameter void(*pfn)(void*)?
I've come across this piece of code inline pthread_t CreateThread(void(*pfn)(void*), void* parg, bool fWantHandle=false) I don't understand this part void(*pfn)(void*) Can someone tell me what it means/is? This is btw not listed in books for beginners so if you want to mention to read books, it's not there. Afaik, v...
This is a function pointer (or a pointer to a function). void(*pfn)(void*) This is broken down as such: *pfn (the name of the pointer i.e. pointer to a function) (void *) (these are the parameters to the function ie. a simple pointer to anything) void (this is return from the function) So if you have a function like t...
6,208,339
6,208,641
Qt: Correct way to post events to a QThread?
In my Qt application, I have a main thread and a worker thread. The worker thread subclasses QThread and processes events via customEvent. Is this the correct way for the main thread to send events to be processed by the worker thread? QThread* myWorkerThread = // ... QApplication::instance()->postEvent (myWorkerThrea...
Your understanding is correct and is indeed very unintuitive :) A lot of the trouble comes from the documentation for QThread that suggests subclassing QThread. Although Qthread has its own event loop, only events and signals for QObjects created in the run() method (created in that thread) will be processed in the QT...
6,208,565
6,208,624
const char* vs char* (C++)
For the following program: int DivZero(int, int, int); int main() { try { cout << DivZero(1,0,2) << endl; } catch(char* e) { cout << "Exception is thrown!" << endl; cout << e << endl; return 1; } return 0; } int DivZero(int a, int b, int c) { if( a <= 0 || b...
Why are you throwing and catching strings anyway? You should throw and catch exceptions, e.g. std::runtime_error The answer to your question is that whenever you insert a string in quotes in the code it returns a null terminated const char* The reason your code doesn't work as above is because it's the wrong type, so t...
6,208,572
6,208,600
C++, 'coupling' of member pointers in multiple objects copied from the same original object
#include <iostream> #include <vector> #include <cstdlib> #include <cassert> struct s_A { bool bin; s_A(): bin(0) {} }; class c_A { public: s_A * p_struct; c_A(): p_struct(NULL) {p_struct = new s_A [16];} void Reset() { delete [] p_struct; p_struct = new s_A [16]; } }; in...
The particular source of your problem are these lines here: objects_copy.push_back(objects[ rand() % x ]); objects_copy[q].Reset(); The issue is that when you try pushing copies of the objects into objects_copy, you end up making a shallow copy of the objects in the objects vector. This means that the objects in the ...
6,208,574
6,208,953
convert opengl Window to std::size_t and back again works in Linux, but not OS X
I have successfully converted an OpenGL Window to an std::size_t variable and then converted it back to an OpenGL Window in Linux. However, when I try to do the same thing in Mac OS X it isn't working. Here's what I'm doing: /* our window instance(This is an X Window System Window!) */ Window window_; . . . . s...
void* would be a fine option if you can't provide GL type information to getInputMgr. I assume you are trying to hide OpenGL definitions from the rest of your code?
6,208,663
6,208,774
Can managed code perform computations as fast as unmamanged?
I've been interested in different chess engines lately. There are many open and closed sources project in this field. They are all (most of them anyway) written in C/C++. This is kind of an obvious thing - you have a computationally intensive task, you use C/C++ so you get both portability and speed. This seems like a ...
"Can" it? Yes, of course. Even without unsafe/unverifiable code, well-optimized .NET code can outperform native code. Case in point, Dr. Jon Harrop's answer on this thread: F# performance in scientific computing Will it? Usually, no, unless you go way out of your way to avoid allocations.
6,208,720
6,208,857
How to properly declare a self-referencing template type?
How do I declare a templated type that refers to itself? template <class T = Animal> class Animal { public: T getChild (); } With this, I get a compiler error concerning a missing type specifier. I tried to forward-declare Animal, without success. I am trying to impose a type constraint. A Lion can only have a Lio...
The usual way to do something like a linked list is: template <class T> class Linked { private: Linked<T>* m_prev; Linked<T>* m_next; } Does this work for you, and if not, what are you trying to accomplish that can't be done this way?
6,208,758
6,208,773
how compilers detect overflow in numbers while compiling?
Compiler deal with source code as strings so in C++ for example when it encourage statement like unsigned char x = 150; it knows from type limits that unsigned char must be in range between 0 and 255. My question is while the number 150 remain string what algorithm compiler use to compare digit sequence - 150 in this c...
Compilers handle it pretty much the easiest possible way: they convert the number to an integer or float as appropriate. There's no law that says the compiler can't convert from strings to some other representation as appropriate. But now, consider your original problem; what about if you took the digits and just buil...
6,208,990
6,209,053
My C++ class is having trouble linking to a function in another .cpp file
I asked the same question yesterday and the answer was not applicable. https://stackoverflow.com/questions/6194578/breaking-up-class-functions-into-multiple-cpp-files If I go into the class header, right click on the function and click "Go to Definition" and it takes me right to my function in my other .CPP file. It se...
inline means that the function effectively has internal linkage (that is, it must exist inside the translation unit where it is used). Either move the definition of the function into the header, or remove inline. (inline for modern compilers really means "use internal linkage" -- compilers will inline where it makes se...
6,209,067
6,209,095
Tuple templates in GCC
I first started C++ with Microsoft VC++ in VS2010. I recently found some work, but I've been using RHEL 5 with GCC. My code is mostly native C++, but I've noticed one thing... GCC doesn't appear to recognize the <tuple> header file, or the tuple template. At first I thought maybe it's just a typo, until I looked at cpl...
As long as it's just a pair you can use typedef pair<int,vector<string>> Code; But I don't think tuple is standard C++ (turns out it is included in TR1 and consequently also standard C++0x). As usual Boost has you covered though. So including: #include "boost/tuple/tuple.hpp" will solve your problem across compilers...
6,209,277
6,215,317
looking for Windows RAM-based shared memory solution in C++
I'm facing a situation where I need to pass up to several hundreds of megabytes of memory from one process to another. Right now I'm doing it via files and it's too slow. I guess that to make it quicker, those files should be written directly to RAM and be accessible from another process. No fancy synchronization requ...
I think that here is a fundamental misunderstanding: you think that, if you create a file mapping backed by the paging file, it will be as slow as actually writing stuff on disk. This is definitely not the case: the meaning of "backed by the paging file" in the documentation means that the shared memory in general resi...
6,209,940
6,210,057
C++ Cross Platform MP3 Decoder?
I have searched high and low, and cannot find any decent MP3 decoders =/ I need one that will compile under gcc/linux. The closest thing i could find was libmad, which has no documentation at all, and the only example I could find was the one on their home page, which is really complicated. Does anyone know where I can...
I have used MAD (MPEG Audio Decoder) in the past with great results, so I would not give up on it so quickly. MAD is specialy designed for good performance on CPUs without floating-point operations, which is desirable while developing applications for mobile devices for example. I would like to recommend you to take a...
6,209,990
6,210,002
populating map globally
I have declared the following map globally and trying to populate globally. 1: typedef std::map<unsigned short,std::pair<char,std::string>> DeviceTypeList; 2: DeviceTypeList g_DeviceTypeList; 3: g_DeviceTypeList.insert( std::make_pair ((unsigned short)SINGLE_CELL_CAMERA, std::make_pair('B',"Single Cell Ca...
Compiler is probably getting confused by the >> on line 1 (because it looks like a shift operator). Try inserting a space in there: typedef std::map<unsigned short,std::pair<char,std::string> > DeviceTypeList; [update] See Vlad Lazarenko's comment for why this will not actually solve your problem. Easiest fix is to ...
6,210,154
6,210,181
Accessing vector in class
If I have a vector as a private member in my class, what's the best way to access it? For example, take the following simple class class MCL{ private: std::vector my_vec; public: // Include constructor here and other member functions } What's the best way to access my_vec? Specifically, I would like t...
return it by const reference, or just by reference if you want to allow changing. const std::vector<T> & getVector() const { return vector; } usage: const std::vector<T> &v = myClass.getVector();
6,210,182
6,210,194
How to get char[] to work with std::map
EDIT after answered: < should be provided for std::map. For more information about best practice, go for James McNellis's answer. The code included in this question is poorly written. It is just because I am playing with SPOJ and the input data is strictly valid. The std::string approach is what I chose at first, but i...
You need to implement the < operator class id { public: char v [30]; bool operator<(const id &rhs) const{ return strcmp(v,rhs.v) < 0; } }; EDIT: As a side note your code is a very poor way of doing things. See some of the answers for an explanation why.
6,210,399
6,210,574
how do i build gcc on a mac?
I'd like to build the latest version of gcc on a mac. I have the latest xcode but I'm looking for some of the c++0x features that are in more recent versions (the lambda functions, etc). Are there any good step-by-step tutorials on doing this?
One option is to install MacPorts and install the gcc46 package: sudo port install gcc46 Another option is to download the source code and build it as follows: tar xzvf gcc-4.6.0.tar.gz cd gcc-4.6.0 ./configure make Note that GCC 4.6.0 requires as prerequisites GMP 4.2+, MPFR 2.3.1+, and MPC 0.8.0+. If ./configure f...
6,210,628
6,228,138
Profiling serialization code
I ran my app twice (in the VS ide). The first time it took 33seconds. I decommented obj.save which calls a lot of code and it took 87seconds. Thats some slow serialization code! I suspect two problems. The first is i do the below template<class T> void Save_IntX(ostream& o, T v){ o.write((char*)&v,sizeof(T)); } I call...
I'm glad you got it figured out, but the next time you do profiling, you might want to consider a few points: The VS profiler in sampling mode does not sample during I/O or any other time your program is blocked, so it's only really useful for CPU-bound profiling. For example, if it says a routine has 80% inclusive ti...
6,210,912
6,210,941
Assign constant char to character array inside structure in VC++
I want a linked list structure in my VC++ application My structure is:- struct xml_data { int id; char file_name[50]; char url_source[50]; struct xml_Data *next; }xml_data1; If I declare a variable like struct xml_data *var; const char* abc; I want to assign a value from a const char* variable to the...
After you've used new to allocate memory for the struct. var = new xml_data; Use strcpy to copy one to the other. strcpy(var->file_name,abc); include <cstring> and make sure there's enough room in the destination.
6,210,920
6,212,004
Hiding Combo Items In CComboBox
Is it possible to hide particular Items in the MFC Combo Box? I have a list which contains 5 items ALPHA-0, BETA-1, GAMA-2, DELTA-3, OMEGA-4 stored in the vector vector<string> mListItems; CComboBox m_List1; CComboBox m_List2; I am using this vector to populate the two combo boxes. In m_List1 it should populate a...
Combo boxes show whatever items you add in them. If an item was added, it will be displayed. So if you want to hide some items, you need to remove them from the combo. This can be done through DeleteString from CComboBox.
6,210,921
6,210,992
operator new inside namespace
namespace X { void* operator new (size_t); } gives error message as: error: ‘void* X::operator new(size_t)’ may not be declared within a namespace Is it a gcc compiler bug ? In older gcc version it seems to be working. Any idea, why it's not allowed ? Use case: I wanted to allow only custom operator new/delete for ...
@Sharptooth's Answer makes more sense if we consider this section from the standard: 3.7.3.1 Allocation functions [basic.stc.dynamic.allocation] [..] An allocation function shall be a class member function or a global function; a program is ill-formed if an allocation function is declared in a namespace scope other th...
6,211,030
6,211,168
How to append some MP3s in Qt?
How to append some MP3s in Qt by C++? Assume I have 1.mp3 and 2.mp3, now I want to join them by Qt. 3.mp3 = 1.mp3 + 2.mp3
AFAIK you can not do this simply in Qt. But I suggest you use mp3wrap, a nifty little command line tool to concatenate your mp3s. So, you create a UI, where you select the files, and then pass the parameters to this command line application and let it do its magic. You can execute commands using: system("command1;comm...
6,211,038
6,211,139
Indented trace in C++
I want to develop indented trace for our large C++ code base that will be perticularly helpful for developers to find the issues. I want to have indented trace functionality. E.g Consider following code:- void FunctionA() { TR_ENTER("Function A"); TR_PRINT("Dignostic message Function A"); FunctionB(); /...
You need to keep track of the call depth: class trace_entry; class trace_log { public: trace_log() : depth_(0) { } private: // noncopyable so we don't accidentally copy it trace_log(trace_log&); void operator=(trace_log); friend trace_entry; int depth_; }; class trace_entry { public: tr...
6,211,069
6,211,187
GCC inline assembly error: junk `(%ebp)+4' after expression
I'm trying to compile inline assembly (with -fasm-blocks) which works in MSVC, but GCC gives me the junk `(%ebp)+4' after expression error... Why won't it accept the syntax and how should I fix this? uint64_t _tmp = 100; _asm { //_tmp value may be changed //... cmp dword ptr _tmp, 100 // Ok jnae te...
You should change it to: cmp dword ptr [_tmp + 4], 50
6,211,172
6,211,228
GCC inline assembly error: asm-specifier for variable '%al' conflicts with asm clobber list
Sorry for so many questions, but I've encountered yet another cryptic error trying to compile the following inline assembly (with -fasm-blocks) which works in MSVC, but apparently not in GCC and wasn't able to deal with it: unsigned char testData = 128; __asm { // ... mov al, testData mov ah, al // error: ...
This has to be some bug in gcc (maybe __asm blocks have implicit clobbering). Anyway there are many workarounds: __asm { // ... mov ah, testData mov al, ah shl eax, 16 // ... }; or __asm { // ... mov al, testData mov ah, testData shl eax, 16 // ... }; or __asm { // ... ...
6,211,198
6,211,981
3.4.2 Argument-dependent name lookup from n3290 Draft
A point from ISO draft n3290 section 3.4.2 paragraph 1: When the postfix-expression in a function call is an unqualified-id, other namespaces not considered during the usual unqualified lookup may be searched, and in those namespaces, namespace-scope friend function declarations not otherwise visible may be found. The...
Consider a simple unqualified function call: foo(x); ADL means that foo is looked up not just in the enclosing scope, and the namespace that the call is in, but also the namespace of the type of x. e.g. if x is a std::vector<int> then namespace std is also searched. Thus: int main() { std::vector<int> x,y; swa...
6,211,245
6,211,914
Efficient Dictionary lookup
For my C++ application, there is a requirement to check if a word is a valid English dictionary word or not. What is the best way to do it. Is there freely available dictionary that I can make use of. I just need a collection of all possible words. How to make this lookup least expensive. Do I need to hash it.
With regards to the presence of a word list, it depends on the platform. Under Linux, /usr/share/dict/words contains a list of English words that might meet your needs. Otherwise, there are doubtlessly such lists available on the network. Given the size of such lists, the most rapid access will be to load it into a ha...
6,211,395
6,211,435
Is + operator overloaded for primitive types?
Already overloaded operators <<,>>,= etc are used many times. An example that i was thinking of is when we add strings say : string name = string("munish") + "kumar"; the + operator is overloaded in the string class. but when we add numbers like 1 + 2( doesn't seem like an overloaded operator call) I was just wonde...
Primitive types don't implement operator+ which is actually a function with a weird name. Addition for Primitive type is carried out by CPU instruction such as : addl %edx,(%eax) //this adds two integral values loaded at edx and eax You implement operator+ for user-defined types, and compiler generates lots of CPU ins...
6,211,429
6,211,511
Callback on memory access?
Does there exist a way to allocate some memory and have some sort of callback (be it pointer to a function or signal) when the memory is being accessed (either read or written to)? For example, if I said allocate 1mb of memory, I would like to have a way to call a function when any of that 1mb is being accessed. The pl...
Yes, there is. Use the mprotect(2) system call (see: http://linux.die.net/man/2/mprotect) to set read only or no access memory protection on the page and set a SIGEGVsignal handler that will be called when the memory has been accessed. Note that you will need to use mprotect in your signal handler to actually allow th...
6,211,575
6,211,604
Proper way (move semantics) to return a std::vector from function calling in C++11
I want to fill std::vector (or some other STL container): class Foo { public: Foo(int _n, const Bar &_m); private: std::vector<Foo> fooes_; } 1.Good looking ctor, expensive performance std::vector<Foo> get_vector(int _n, const Bar &_m) { std::vector<Foo> ret; ... // filling ret depending from arguments retur...
If you're using a C++0x-compatible compiler and standard library, you get better performance from the first example without doing anything. The return value of get_vector(_n, _m) is a temporary, and the move constructor for std::vector (a constructor taking an rvalue reference) will automatically be called with no furt...
6,211,926
6,212,017
Which standard does VS2005, VS2008 follow?
Do they both follow the C++03 released in 2003?
They both target C++03, yes. But they also both have areas where they fail to comply with the standard. (So does GCC, btw, before any fanboys on either side starts frothing at the mouth). But keep in mind that C++03 is basically a very small bugfix release, nailing down a few "common sense" things that sensible compile...
6,212,009
6,212,054
error C2027: use of undefined type GUITHREADINFO
during build with Visual Studio C++ I get this error: error C2027: use of undefined type 'rectAnalyzer::GUITHREADINFO' the function rectAnalyzer is the following: DWORD WINAPI rectAnalyzer(LPVOID param) { MSG msg; PARAM_PASSED *p = (PARAM_PASSED*) param; std::ostringstream ss; std::wstring str; PGUITHREADINFO g = (PGU...
Try using sizeof(GUITHREADINFO) instead of sizeof(struct GUITHREADINFO)
6,212,138
6,440,671
boost::interprocess message_queue performance - rather slow?
I need an ultra-fast MQ mechanism, where both sender and receiver are written in C++, on Windows platform. My current implementation using RCF-C++ for IPC is clocking at around 20,000 msg/sec over Windows Named Pipes. I am testing the perf of boost::interprocess Message Queues according to the demo app, and am measuri...
Daniel's answer is part of it, but there is a bigger issue here: boost::interprocess basically maintains the queue as an array in shared memory, and upon sending a message, the boost::interprocess:message_queue does a binary search based on the new message's priority to find where the message should be placed in the ar...
6,212,419
6,213,733
C/C++: Easily unzip to memory
I need to find a library that allows me to easily get a directory listing of all the files inside a ZIP archive and allows me to extract any given file inside the archive to memory (a buffer). Preferably, it should be a high-level library since my requirements aren't very complex (what I mentioned above is pretty much ...
While .zip uses zlib http://zlib.net compression, it alone is not sufficient to get a directory listing from a .zip file. You also need code that can read the .zip dictionary format. Check out Minizip http://www.winimage.com/zLibDll/minizip.html. It provides a code and simple zip/unzip command line executables. edit ...
6,212,476
6,212,493
What does #define macro() <...> do?
What does this line do? I doubt its a template or expression. (doing those divies and naming a member hpp is a bad idea) # define BOOST_PP_UPDATE_COUNTER() <boost/preprocessor/slot/detail/counter.hpp> Full file # /* ************************************************************************** # * ...
Apparently it does some auto-incrementing magic. Here's the documentation. I have no idea how it works. What I do know is that the magic is in counter.hpp itself; that the definition you posted has brackets in it is just so that you can write the vaguely user-friendly: #include BOOST_PP_UPDATE_COUNTER() to invoke said...
6,212,541
6,212,868
socket send part down but receive part Up , possible?
I am wondering if it is possible to have a socket with send which doens't work (because buffer of peer is full maybe) while receive part still working ? EDIT: In case of a peer which doesn't perform a half close connection, and which it is too long to process its receive buffer (so its receive buffer is full), can I ha...
Short answer: yes. If remote peer receives data at a slow rate (possibly due to slow data processing between recv calls) it will slow down transmission at a sending side: ACKs will be coming slowly and sending buffer will quickly get full which will cause your socket send operation to block or return error. On the othe...
6,212,619
6,212,709
Sorting std::unordered_map by key
How can I sort an unordered_map by key? I need to print an unordered_map sorted by key.
std::unordered_map<int, int> unordered; std::map<int, int> ordered(unordered.begin(), unordered.end()); for(auto it = ordered.begin(); it != ordered.end(); ++it) std::cout << it->second;
6,212,707
8,988,381
Java compiler for android phones
I have done a little googling but not found too much info on the subject so im asking here, Does any body know of a phone based java or c/c++ compiler so a dev could effectively use his phone to do some preliminary dev work (or just to play around with when bored on the tube :))
I just found terminal-ide ( https://market.android.com/details?id=com.spartacusrex.spartacuside&hl=en), and it is awesome if you are not afraid of the command line. Onboard java compiler.
6,212,892
6,212,926
How to read uptill a particular character in a file, without going through the file, character by character?
Want to detect the '\n' without going through each and every character of a text file. Any hints?
Something has to read all the bytes to check for that delimiter. Use one of the getline (or istream::getline) functions so that the library does the searching, not your code.
6,212,987
6,213,703
How to compare "4A4B4C" (string shows hex value) actual string is "JKL"
I am getting a string "4A4B4C4D4E4F".. it is equal to a string ("JKLMNO") How can I check this type of string in c++.. (one string shows the hexadecimal representation of another) hexadecimal value of J=4A, K=4B, L=4C
Alternatively this can be done using C++ strings and features rather than C-style strings: #include <iostream> #include <sstream> #include <iterator> #include <algorithm> #include <iomanip> #include <string> bool compareAscii(const std::string& string, const std::string& asciistr) { std::ostringstream result; re...
6,213,030
6,213,107
Does C++ calls member object 's overloaded operator?
#include <stdio.h> class InnerOne { int m_iDummy; public: InnerOne(int iDummy) { m_iDummy=iDummy; } InnerOne& operator=(InnerOne &obj) { printf("In InnerOne Operator=\n"); m_iDummy = obj.m_iDummy; return *this; } }; class OuterOne { ...
Yes. The compiler generated copy-assignment for OuterOne will invoke the operator= for InnerOne. As a sidenote, its better if you write InnerOne copy-assignment as: InnerOne& operator=(const InnerOne &obj) //^^^^ add this! const is necessary, or else your code wouldn't work for the following: const I...
6,213,045
6,213,232
CreateThread seems to behave like fork()
I have this function int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place code here. MSG msg; HACCEL hAccelTable; i...
You are not clearing the stringstream ss in the loop, so the output just accumulates: thread 0 thread 0 1 thread 0 1 2 thread 0 1 2 3 Add a ss.str("") after doing each output.
6,213,080
6,213,390
Multithread performance
I created very simple app to figure out how boost::thread works. I found result of this test suprising. 4 threads of execution finish computation 2 times faster than 1 thread. I expected 4x boost. Another question is why 8 threads did not bring any performance boost? I'm using boost 1.46.1 and VS2008. Full source code ...
You may have 4 cores in your Core i5 750 machine, but you still have single data bus. All of the used data (13107200 * 3 * sizeof(float) = 157 MB) must pass through this data bus. And then there is a resulting vector of "mere" 13107200 * sizeof(float) = 52 MB, which takes the same resource. All this is heavy on the cac...
6,213,341
6,213,367
How to move the file pointer to next character through "ifstream" without "getting" any character, just like "fseek" does?
seekg uses ios as the second argument, and ios can be set to end or beg or some other values as shown here: http://www.cplusplus.com/reference/iostream/ios/ I just want the pointer to move to the next character, how is that to be accomplished through ifstream? EDIT Well, the problem is that I want a function in ifstrea...
ifstream fin(...); // ... fin.get(); // <--- move one character // or fin.ignore(); // <--- move one character
6,213,350
6,213,369
Is there a way in c++ to make sure that class member function isnt changing any of the class data members?
Lets say that I have a class Dictionary { vector<string> words; void addWord(string word)//adds to words { /... } bool contains(string word)//only reads from words { //... } } Is there a way to make compiler check that contains isnt changing words vector. Ofc this is just an example with one class data member, I wo...
If you want the compiler to enforce this, then declare the member function const: bool contains(string word) const { ... } A const function is not allowed to modify its member variables, and can only call other const member functions (either its own, or those of its member variables). The exception to this rule is...
6,213,755
6,213,919
Application only runs if you run as administrator?
Edit: This problem only occurs on windows 7 and vista from what I've heard. I have a very simple app developed with an external graphics library. If I install this app into a program files directory and run it, it will crash immediately but it works fine normally, with exactly the same files. I have realised it is beca...
When a program cannot perform an operation, it (the operation) should fail gracefully. My guess is your application is attempting to do something that it cannot do as a normal user and then fails to check for a return code, and then subsequently crashes. You need to identify what it is your program is doing that it s...
6,214,018
6,214,065
To Inline an External Function Written in Assembly
I have a separate function written in assembly and want to call it in my C/C++ code. Is it possible to tell my compiler (MS Visual C++ 2010) to inline that module written in assembly into my C/C++ function? Note, I am not talking about using inline assembly code (__asm {}) in my C/C++ function. All assembly codes a...
Is it possible to tell my compiler … to inline that module written in assembly into my C/C++ function? No. The compiler doesn’t even see the assembly code – it’s in a different compilation unit. You can ask your linker to inline the function though. In order to do that, you need to enable link-time optimizations. The...
6,214,160
6,214,187
How to store a const char* in std :: string?
char *buffer1 = "abc"; const char *buffer2 = (const char*) buffer; std :: string str (buffer2); This works, but I want to declare the std::string object i.e. str, once and use it many times to store different const char*. What's the way out?
You can just re-assign: const char *buf1 = "abc"; const char *buf2 = "def"; std::string str(buf1); str = buf2; // Calls str.operator=(const char *)
6,214,334
6,215,084
Gracefully stopping an std::thread?
I have a worker std::thread and I want its main loop to check if some other thread tells it to stop looping and exit. What is a good cross platform way to do this? Does boost provide some event object for it? Is using just a bool considered thread-safe?
.. well it depends. What is the thread doing? Does it block on anything, I/O, sleep, or some other API? If it's just CPU-looping all the time and it does not matter about exactly when it stops and it stops and exits, then just use a boolean. There's no point, in this case, in locking up a 'stopAndExit' boolean. If t...
6,214,532
6,214,761
Opengl proper lighting problem
I have written the following program to display a teapot on a table in a room with 2side walls and a floor. #include <stdio.h> #include <glut.h> void wall1(float thickness) { glPushMatrix(); glTranslatef(100,100,0); glRotatef(90,1,0,0); glScalef(thickness,1,1); glutSolidCube(100); glPopMatrix(...
I was missing glEnable(GL_NORMALIZE); in the main function, and thus opengl was not rendering it properly! Alse @Christian's answer of using ambient only worked. :)
6,214,629
6,214,794
stdout and need to flush it C++
I have some C++ code that uses cout statements for debug purposes and for some reason I can't get all the data to print unless I do a std::cout.flush(); at the end. I don't quite understand why this flush operation is needed. Anyone have any insight?
To add to the other answers: your debugging statements should instead go to cerr, because: it writes to the standard error, which means that, running the application, you can easily separate the "normal" program output from the errors/debug information via redirection; most importantly, cerr by default is unbuffered, ...
6,214,668
6,214,689
C++ MFC Integer Textfields Always Set to 0?
I'm creating a preferences form in VC++ MFC, and I have several textfields that only accept integers. I'm new to MFC, so this is how I found to initialize them in some tutorial: CProgramDlg::CProgramDlg(CWnd* pParent /*=NULL*/) : CDialog(CProgramDlg::IDD, pParent) , m_nSampleValue1() , m_nSampleValue2() ... m_nSampleVa...
m_nSampleValue1() and m_nSampleValue2() are value-initialized. If its primitive types, then that means they will be zero-initialized. Is there a trick to getting the textboxes to just be empty without showing a 0? If its integral type, then I think that isn't possible without changing other part of the code (which p...
6,214,831
6,214,865
Enable incoming connections from specified IP-address only
I have a server application with a listening socket opened on a specific IP port. How can I allow the socket to enable incoming connections from just one specified IP address?
You'll have to either use some firewall software to restrict incoming requests to that port, or shut down accepted connections that you do not want to service (based on the socket address returned by accept). There might be libraries out there that do that for you, but the socket API doesn't have anything to do it auto...
6,214,845
6,214,988
Taking details from a map and saving it into another?
I have a map like this map<string, pair< pair<int, int>, string> > what is the easiest way to get only the two strings and save into another map like this map<string, string> ? I mean is there another way other than something like this?? map<string, pair< pair<int, int>, string> > info; map<string, pair< pa...
First, I'd define a proper type: struct Mapped { int someSignificantName; int anotherName; std::string yetAnother; }; There are almost no cases where std::pair is an acceptable solution (except for quick hacks and tests). Given that, you define a mapping functional object: struct Remap : std::unary_op...
6,214,921
6,215,972
opengl glDrawArray throws exception
I'm new to openGL and I need to directly use it for debuging perpose can anyone please tell me why in this code glDrawArray should throw exception (trying to access memory at 0x00000000) glEnableClientState(GL_VERTEX_ARRAY); float data[8]; data[0] = 10; data[1] = 10; data[2] = 10; data[3] = 20; data[4] = 20; data[5] ...
Perhaps you have enabled another array with glEnableClientState at another point in your program and didn't disable it. So glDrawArrays tries to read from another array that causes the problem. EDIT:: It could also be, that the code you showed us is not the real code and you call glVertexPointer at a completely differe...
6,215,092
6,215,360
Why basic_ifstream show me wrong results?
I have a binary file. There are 2288*2288 longitude float values stored in top half section, and the same number of latitude float values occupied the bottom half. I used the following code to load them into a float vector. It can run like a charm, but gave me incorrect results. With regard to my binary file, the float...
To make std::basic_ifstream works, you have to define your trait_type so that it provides everything expected by input stream, and I'm not sure that it will be possible. That will be far more than just a codecvt<float, char, mbstate_t> (which you seem to think is already present while the standard demand only the wcha...
6,215,287
6,215,505
Makefile multiple dependency lines for a single target?
To generate dependency files I can use something like this to generate dependency files: -include $(patsubst %.cpp,build/%.d,$(SRC)) build/%.o: %.cpp $(CC) $(CXXFLAGS) -c -o $@ $< $(CC) $(CXXFLAGS) -MM -MT $@ -MF $(patsubst %.o,%.d,%@) $< This generates everything and puts both the object and dependency files...
You should add one more pattern rule to express the dependency between the .cpp and .d files and use that rule to create the .d files (second line in the pattern rule of your question) instead of creating the .d files unconditionally. It might make sense to introduce another dependency between all .h and .cpp files and...
6,215,400
6,244,174
boost serialization and doubles
I am trying to serialize a class to a string using the boost serialization library and included in my class are several double member variables. Below is the code I'm using to serialize: #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/string.hpp> std:...
You could try forcing your stream to use scientific format for floating point before serialising to it: ss << std::scientific; It looks like the boost library sets the precision correctly, but doesn't appear to set the format. Alternatively, you can I think derive and override the logic for saving and/or loading float...