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
4,835,359
4,835,408
fopen: is it good idea to leave open, or use buffer?
So I have many log files that I need to write to. They are created when program begins, and they save to file when program closes. I was wondering if it is better to do: fopen() at start of program, then close the files when program ends - I would just write to the files when needed. Will anything (such as other file ...
Well, fopen(3) + fwrite(3) + fclose(3) is a buffered I/O package, so another layer of buffering on top of it might just slow things down. In any case, go for a simple and correct program. If it seems to run slowly, profile it, and then optimize based on evidence and not guesses.
4,835,379
4,835,398
How to generate compiler warning "statement has no effect" in c/c++ code
For my compiler tests, I need to generate this warning "Statement has no effect" in my test code. How can I do this? Using VS cl.exe compiler
int main() { 5; // Statement has no effect return 0; } Edit 1 Tried on VC++ 2010 #include <iostream> #pragma warning(default:4555) int main() { 5; getchar(); return 0; } Output : warning C4555:main.cpp(6): expression has no effect; expected expression with side-effect NOTE: It seems VC++ 2010 h...
4,835,383
4,836,302
c++ List of classes without initializing them for use of static functions
I may be asking this in a odd way, but I'm not sure how else to ask. I want to have a list of classes, not objects. This way I can call static functions without have to create the object.
I would really prefer function pointers at this point: struct A { void SomeFunc(int); }; struct B { void AnotherFunc(int); }; typedef void (*Function)(int); std::vector<Function> vec; vec.push_back(A::SomeFunc); vec.push_back(B::AnotherFunc); for (Function f: vec) { f(2); } Note that a static function is m...
4,835,517
4,835,521
char to hex stream output in C++ using GCC 4.2.1
I have looked at this answer and can't get it to work for my situation. Please don't mark this as a duplicate as I can't get any of those answers to satisfy my situation. I am mallocing some memory and copying data into that memory. I want to be able to print out the values of each of the bytes in hex in the format 0xF...
Use unsigned char *aschar instead of (signed) char *aschar.
4,835,539
4,835,563
having "typedef void FuncCharPtr" in one class how to feed function that uses that typedef with non static functions?
So I have a class like: class IGraphElement{ // We should define prototype of functions that will be subscribers to our data typedef void FuncCharPtr(char*, int) ; public: // Function for adding subscribers functions void Add(FuncCharPtr* f) { //... } }; and another class like #i...
renderCastedData is a nonstatic member function. Its type is void (simpleRendererGraphElement::*)(char*, int) In order to call it, you need to have an instance of simpleRendererGraphElement for the this parameter. There are lots of solutions to this problem. One option would be to make Add a function template that ...
4,835,604
4,835,625
How would I keep track of a float from an external class?
Say I have some class I refer to in main that takes in a float like this: class SomeClass { SomeClass(float a) { } int someMethodDoingSomethingWith_a() { // perform something on _a } float _a; } In my main class, I will be constructing this SomeClass with a float value that will b...
Then define it like: class SomeClass { SomeClass(float & a) : _a (a) { } //.... float & _a; } int main() { float x; SomeClass inst(x); } Now, if you change x in main(), then _a in SomeClass will be updated accordingly. But note that this automatic change will be reflected only in in...
4,836,081
4,836,191
how to use Qwt in the Qt 4.7
I have downloaded the QWT & want to use that for creation of graphs & charts. I am using Qt 4.7 for creating application. How to use Qwt in my application. How do I add the header file & library to my application?
Okay, disregard the previous answer. It was correct for any "random" library that doesn't use any special setup, but it looks like that QWT is slightly different. After reading Johnny's comment I realized that QWT provides an easier and more correct way of configuring a project to use it: Install QWT according to the ...
4,836,238
4,836,262
How to open floppy with fstream
How to open floppy disc with fstream? I'm trying something like this: but it always returns error #include <iostream> #include <fstream> using namespace std; char a='k'; int main() { fstream stream; stream.open( "\\\\.\\A:", ios::binary ); if( stream.good() == false ) { cout <<"Error"; ...
You cannot use fstream to open a device - only a file within the filesystem contained on that device. You need to use operating system specific functionality to access a device. EDIT: To be clear, it might be possible to open the floppy device using fstream but this level of access to the system goes beyond the level ...
4,836,296
4,836,668
How to create this desktop recorder?
I want to create a desktop recorder that require very little HD space. It should capture the current display into a buffer, compare it to the previous state, and save only the rectangles that differ to the previous state. What API, function or library I have to use ?
Well if you want to save the differences from each frame to frame only you could simply use a substraction-method. Simply substract the color values at image(t+1) from image(t)... All parts that stay equal haven't changed... only the parts that are different will result in something non-zero. You can then extract the r...
4,836,344
4,840,478
std::vector<std::string> crash
This question is continuation of my question. Here is problematic code. a.h: #include <string> #include <vector> std::vector<std::string> foo(); a.cpp #include "a.h" std::vector<std::string> foo() { std::vector<std::string> v; return v; } and finally main.cpp: #include "a.h" #include <iostream> int main() { ...
In your previous question, you reference the GCC documentation here: http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt03ch17s04.html. That documentation states that the GCC libstdc++ "supports per-user recompilation", and defines it as follows: Per-use recompilation: The user must recompile the parts of his or he...
4,836,370
4,836,399
Ogre3D shows exception when starting program
I'm trying to write game using Ogre engine. I had a lot of problems - GCC didn't compiled program because it didn't found OgreMain_d and OIS_d... I created symbolic links (I'm using Linux) to libOgreMain.so.1.7.2 and libOIS-1.3.0.so and GCC compiled my program, but... the program shows error: OGRE EXCEPTION(6:FileNotFo...
Your hint is clearly in the error message. The example framework for Ogre expects certain files to be available, such as resource.cfg and even plugins.cfg. Make sure this is in the path, and that the media required by those resources is also available.
4,836,397
4,837,404
How to pass STL containers as arguments to BOOST_CHECK_EQUAL?
For example, say we have this class which we want to test: struct TestMe { vector<int> getSomething(); } And the test function is made of: ... vector<int> Expected; TestMe TM; ... Result = TM.getSomething(); BOOST_CHECK_EQUAL(Result, Expected); ... STL vector provides a free operator==, but it does not provide an o...
I think you should use BOOST_CHECK_EQUAL_COLLECTIONS, this tests each element and also prints where the mismatches are: BOOST_CHECK_EQUAL_COLLECTIONS(Result.begin(), Result.end(), Expected.begin(), Expected.end());
4,836,500
4,836,533
Boost Smart Pointers and non-POD types (C++)
In practicing with smart pointers and seeing how they can prevent memory leaks and aid memory management through RAII, I was doing the following: #include <boost/shared_ptr.hpp> #include <vector> #include <iostream> using std::cout; using boost::shared_ptr; class myobj { public: shared_ptr<int> a; myobj(...
First, anything in boost::detail is an implementation detail. Don't touch it unless you're developing code that will be a part of boost itself. Second, boost::shared_ptr is not directly capable of wrapping arrays. This is because arrays in C++ must be deleted with delete [], while boost::shared_ptr deletes with delete ...
4,836,509
4,836,597
Android NDK advantages and disadvantages
I am studying Android NDK. What are the advantages and disadvantages of NDK? Are there any good references to study Android NDK?
Have you read the official Android developer page regarding NDK? Quote: The Android NDK is a companion tool to the Android SDK that lets you build performance-critical portions of your apps in native code. It provides headers and libraries that allow you to build activities, handle user input, use hardware...
4,836,526
4,836,701
Check calling convention of pointer-to-function type
How to check at compile-time that function pointer has the __stdcall calling convention? Something like void foo() {} static_assert(is_stdcall<decltype(&foo)>::value, "foo() must be stdcall"); or at least must_be_stdcall<T>(); // compiler error or warning if not stdcall
MSVC has the C4440 compiler warning: // library code #pragma warning(push) #pragma warning(error: 4440) template<typename F> void must_be_stdcall(F*) { typedef F __stdcall* T; } #pragma warning(pop) // test code void __stdcall stdcall_fn() {} void __cdecl cdecl_fn() {} int main() { must_be_stdcall(&stdcall_fn);...
4,836,575
4,837,039
boost::ptr_container and std::vector<shared_ptr>
After reading timdays answer to this question I am curious about the difference between boost::ptr_container and a std::vector<shared_ptr>. I was under the impression that a boost::ptr_container had ownership over the pointers given to it, and upon release would call the destructors of all the pointers it contained reg...
You are right, the two are widely different. The first difference, as you noticed, is the ownership semantics. The ownership of items in a Pointer Container is NOT shared. In this regard, a boost::ptr_vector<T> is much closer to a std::vector<std::unique_ptr<T>>. But this is not the only difference! unless explicitly ...
4,836,863
4,837,048
Shared Memory or mmap - Linux C/C++ IPC
The context is Inter-Process-Communication where one process("Server") has to send fixed-size structs to many listening processes("Clients") running on the same machine. I am very comfortable doing this in Socket Programming. To make the communication between the Server and the Clients faster and to reduce the number ...
I'd use mmap together with shm_open to map shared memory into the virtual address space of the processes. This is relatively direct and clean: you identify your shared memory segment with some kind of symbolic name, something like "/myRegion" with shm_open you open a file descriptor on that region with ftruncate you ...
4,836,925
5,237,214
Fastest way to get pixel color in Python or C++?
I'm trying to add a blur effect to a transparent Tkinter widget I'm making. I made the widget partially transparent with this line (snippet) self.attributes("-alpha", 0.85) In order to add the effect I desire I need to get the RGB values of each individual pixel in the widget. Seeing as the widget is only partially op...
You may wish to take a look at the Python Image Library you could call something like this import Image im = Image.open("name_of_file.jpg") list_of_pixels = list(im.getdata()) print list_of_pixels[0] That would output the very first pixel in a RGB format like (255,255,255) It is pretty fast but it wont ever beat C++ I...
4,837,179
4,837,696
Getting a vertex_handle from an edge_iterator
I'm having quite some difficulty getting a vertex_handle for each of the end points of an edge in a Delaunay triangulation. Since I hammered my head against this for several hours I thought maybe one of you guys could help me out with this apparently trivial problem: #include <iostream> #include <CGAL/Exact_predicates...
Dereferencing an Edge_iterator will give you an Edge according to the documentation. Edge is definded as follows: typedef std::pair<Face_handle,int> Edge; Dereferencing the Face_handle will give you a Face. The two vertices that the edge joins can be accessed by: for(Edge_iterator ei=t.finite_edges_begin();ei!=t.fi...
4,837,285
4,837,310
dynamic library in C++
I have a C++ applicatoin which uses dynamically linked libary. I have placed application and library on target and application is running. Now i have changed some thing in library and made the library and replaced old library on target with new library. My questions is Does application takes new libarary with out reco...
Yes, but only if your new library is ABI compatible with the older one. You can find many info about it on the web. I'd suggest you to read this FAQ about binary compatibility.
4,837,376
4,837,405
Bind with 1 call of copy ctor
I need deferred call of some function with arguments. Have next test code: #include <functional> #include <boost/bind.hpp> #include <boost/function.hpp> struct test { test() { std::cout << "ctor" << std::endl; } test& operator=(test const& t) { std::cout << "operator=" << std::endl...
Use a lambda expression. int main() { test t; std::function<int()> f = [=](){ foo(t); }; f(); return 0; } Binding is exceedingly redundant due to the incredible ease etc of using lambdas. In addition, you did compile in Release mode with all optimizations on, right? You won't get only one copy construc...
4,837,399
4,837,506
C++: rationale behind hiding rule
What's the rationale behind the hiding rule in C++? class A { void f(int); } class B : public A { void f(double); } // B::f(int) is hidden If it is a meaningful feature I think it should also be possible to hide functions without defining new functions with the same name: something like this: class B : public A { hi...
It's an hairy question, but apparently the idea is that this hiding feature helps avoiding subtle bugs when making changes to a base class (that could otherwise "steal" calls that before would have been handled by the derived class). Still a change in a base class can influence the result of compilation of derived clas...
4,837,480
4,837,836
Objects with inheritance memory storage
Say that i have some classes like this example. class A { int k, m; public: A(int a, int b) { k = a; m = b; } }; class B { int k, m; public: B() { k = 2; m = 3; } }; class C : private A, private B { int k, m; public: C(int a, int b) : A(a...
In the introduction of Chapter 10, Derived classes, the C++ Standard mentions: The order in which the base class subobjects are allocated in the most derived object (1.8) is unspecified. So, in your example C objects each have a base class subobject of type A and a base class subobject of type B, but whether the A ba...
4,837,515
4,837,548
I want to ask you how it should look this code to C++
I want to ask you how it should look this code to C++: <?php for ($i = 1; $i <= 10; $i++) { $array[$i]="test".$i; } ?>
It would look something like this (a complete program). /* required headers */ #include <map> #include <cstdlib> /* code has to be inside a function; main is the start-point of the program */ int main() { std::map<int, int> array; for (int i = 1; i <= 10; ++i) { array[i] = i; } return EXIT_SUCCESS; } I us...
4,837,517
4,837,771
How does boost::unordered_map.emplace(Args&&... args) work?
According to the documentation it: Inserts an object, constructed with the arguments args, in the container if and only if there is no element in the container with an equivalent key. But the only objects which can be inserted into an unordered_map have type std::pair<Key const, Mapped>(because both a key and ...
See this SO article on emplace_back vs. push_back. Essentially, it allows an object to be constructed from the arguments passed into it without needing to create the object to be passed in first. It saves on overhead by removing a copy construction which normally happens as the result of creating objects to be insert...
4,837,549
4,837,705
Why is ostream::operator<< a global function for char parameters?
Acording to http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/ the operator<< method defined on e.g. streambuf is a member of ostream, but for char / char * it is a global function. What's the design decision behind this difference?
operator<< for streambuf* (or int which sounds a simpler case) and char could have been both implemented as member operators, or as non-member (free) operators. My guess is that it's due to retro-compatibility issues emerged while C++ was being defined: maybe older code was relaying on a member operator<<(int), and thu...
4,837,561
4,837,597
unsigned char pointer in C#?
In the middle of translating some code from C++ to C#, I found this, unsigned char *p = m_pRecvBuffer + 5; unsigned int noncelen1 = *p * 256 + p[1]; How do I translate this into C#? m_pRecvBuffer is a char-array, however I store it as a byte-array.
Something akin to byte[] p = new byte[m_pRecvBuffer.Length - 5]; Array.Copy(m_precvBuffer, p, m_pRecvBuffer.Length - 5); uint noncelen1 = p[0] * 256 + p[1]; But in that case I don't think you actually need to use an array copy. Just using uint noncelen1 = p[5] * 256 + p[6]; should be enough, I guess.
4,837,613
4,837,964
C++: How do I pass a function(without knowing its parameters) to another function?
I'm trying to create a function that will store and repeat another function given as a parameter for a specific amount of time or repeats given. But when you want to pass a function as a parameter you have to know all of its parameters before hand. How would I do if I wanted to pass the function as one parameter, and t...
dribeas' answer is correct as far as modern C++ is concerned. For the sake of interest, there's also a simple lo-tech solution from the C world that as far as it goes, works in C++. Instead of allowing arbitrary parameters, define the function as void (*func)(void*), and make "params" void*. It's then the caller's job ...
4,838,318
4,838,362
How to control Download rate/ Upload rate in file-transfer using socket programming
I am new to network programming and am trying to develop an application for rate controllable file transfer using socket programming in C++ for my networks' course assignment. I would like to know how to control the download rate/upload rate in file transfer. In fact, is there a way to measure the bandwidth of the host...
The most common method of rate limiting is to use a token bucket. Basically, you increment a counter at the rate you want to send, then when you send the data, you decrement that counter and only send as many bytes as the counter says is available.
4,838,369
4,838,374
basic c++ memory allocation and strlen
int _tmain(int argc, _TCHAR* argv[]) { char* myArr = new char[5]; cout << strlen(myArr) << endl; return 0; } why does it print out 12 (instead of 5)? edit: Adding myArr[5] = '\0'; fixes the problem. But it takes memory that isn't mine. Is that ok?
The memory is uninitialized. It has "random" data on the heap, so there just happens to be 12 non-zero bytes in it before the first zero (and it is reading past the allocated length). Allocated memory does not contain (from the application's standpoint) length information. If you put a 0 in the first byte, then the l...
4,838,397
4,838,614
my code in visual studio 2005 & 2008 & 2010 is work but in borland c++ 5.02 is not work,and have error
My code in visual studio 2005 & 2008 & 2010 works but in Borland c++ 5.02 is does not. The error is: Info :Compiling C:\Program Files\BORLAND C++ 5.02\BIN\noname00.cpp Error: noname00.cpp(85,26):Qualifier 'amaliat' is not a class or namespace name Error: noname00.cpp(85,28):Function call missing ) Warn : noname00.c...
void HESAB::variz(int mab,TARIKH date) { x[index].add(mab,amaliat::VARIZenum,date); index++; } void HESAB::bardasht(int mab,TARIKH date) { x[index].add(mab,amaliat::BARDASHTenum,date); index++; } I think it's complaining about the amaliat::VARIZenum syntax. Try specifying just VARIZenum.
4,838,739
4,838,767
C++ Reading a txt file?
Hi Iam using ubuntu (Linux), using g++ compiler. I have a very weird situation, yesterday my code was working fine, I didn't do anything, but today, its not working. Here is my code: ifstream file; file.open("users.txt", ios::in); if(file.is_open()){ int counter = 0; string readLine; file.seekg(0, ios::end...
file.seekg(0, ios::end); will seek to the end of the file. You need to seek back to the beginning before you start reading ie. is.seekg(0, ios::beg);
4,838,982
4,839,019
C++ help with error : cannot convert parameter 1 from 'float' to 'float [][2]
and I was doing a program, that isn't so important. Apparently, I cant send parameters to a float function. the code look something like this float myfunction(float array[1][2]) { // ... return 0; } int main() { float array[1][2]; int foo = 0; // assigning values to the array foo = myfunction(array[1][2]); return 0; ...
A couple of things. First, a function prototyped float myfunction(float array[1][2]) is confusing (you), since what it actually mean is: float myfunction(float array[][2]) or float myfunction(float (*array)[2]). The function accepts a pointer to (one or more) array(s) of two floats. Second, the error you get is because...
4,839,181
4,839,739
Is there a #define associated with the SubSystem
I'm creating main with a macro and need to be able to check the selected SubSystem at compile time, /SUBSYSTEM:WINDOWS or /SUBSYSTEM:CONSOLE, in order to generate the appropriate main function. Is there a #define I can check that accomplishes this?
If you are trying to make things easy for users of your library (or whatever it is), you could just generate both WinMain and main from your macro. The linker by default sets console apps to start at main, and win32 apps to start at WinMain. The other "main" function will be ignored. (Presumably the rest of the code do...
4,839,204
4,839,339
how to memory map a huge matrix?
Suppose you got a huge (40+ GB) feature value (floating-point) matrix, rows are different features and columns are the samples/images. The table is precomputed column-wise. Then it is completely accessed row-wise and multi-threaded (each thread loads a whole row) several times. What would be the best way to handle this...
Memory mapping the whole file could make the process much easier. You want to lay out your data to optimize for the most common access pattern. It sounds like the data is going to be written once (column-wise) and read several times (row-wise). That suggests the data should be stored in row-major order. Marking the mat...
4,839,257
4,839,571
Is it necessary to define move constructors from different classes?
Consider the following: struct X { Y y_; X(const Y & y) :y_(y) {} X(Y && y) :y_(std::move(y)) {} }; Is it necessary to define a constructor like the second one in order to take full advantage of move semantics? Or will it be taken care of automatically in the appropriate situations?
Yes, but no. Your code should just be this: struct X { Y y_; X(Y y) : // either copy, move, or elide a Y y_(std::move(y)) // and move it to the member {} }; If you ever say in design "I need my own copy of this data"*, then you should just take the argument by value and move it to where it needs to b...
4,839,591
4,839,691
Resource File VS2010: Images missing when copying product
I am creating a c++ dll which includes some images in the png format using VS2010. This works fine as long as I keep the dll on my developer machine. When I try to copy the dll to another machine the images are missing. When I compile my project, a file called app.res is placed in the build directory. If I look into t...
The linker embeds the .res file in the DLL. Verify this with File + Open + File, select your DLL, you can browse the embedded resources. There is otherwise no mechanism to make embedded resources disappear when you copy the DLL, they are firmly embedded.
4,839,616
4,839,779
Segfault with Embedded Structs and virtual functions
I have structs like this: struct A { int a; virtual void do_stuff(A*a) { cout << "I'm just a boring A-struct: " << a << endl; } } struct B { A a_part; char * bstr; void do_stuff(B*bptr) { cout << "I'm actually a B-struct! See? ..." << bptr->bstr << endl; ...
You're mixing a C idiom (embedded structs) with C++ concepts (virtual functions). In C++, the need for embedded structs is obviated by classes and inheritance. virtual functions only affect classes in the same inheritance hierarchy. In your case, there is no relationship between A and B, so A's doStuff is always goi...
4,839,623
4,840,312
Getting pixel color in C++
I would like to get the RGB values of a pixel at different x, y coordinates on the screen. How would I go about this in C++? I'm trying to create my own gaussian blur effect. This would be in Windows 7. Edit What libraries need to be included for this to run? What I have going: #include <iostream> using namespace s...
As mentioned in a previous post, you want the GetPixel function from the Win32 API. GetPixel sits inside gdi32.dll, so if you have a proper environment setup, you should be able to include windows.h (which includes wingdi.h) and you should be golden. If you have a minimal environment setup for whatever reason, you coul...
4,839,626
4,839,671
Element count of an array in C++
Let's say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])? I can thing of only one case: the array contains elements that are of different derived types of the type of the array. Am I right and are there (I am almost positive there must be) other ...
Let's say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])? One thing I've often seen new programmers doing this: void f(Sample *arr) { int count = sizeof(arr)/sizeof(arr[0]); //what would be count? 10? } Sample arr[10]; f(arr); So new...
4,839,639
4,839,661
No matching function for call (expects reference to pointer instead of pointer)
I get the error from xcode (3.2.4)/gcc(4.0): /Users/admin/scm/audacity/mac/../src/toolbars/DeviceToolBar.cpp: In member function 'void DeviceToolBar::ShowInputDialog()': /Users/admin/scm/audacity/mac/../src/toolbars/DeviceToolBar.cpp:817: error: no matching function for call to 'DeviceToolBar::ShowComboDialog(wxChoice*...
The problem is not the first parameter; its the second. You're passing in a temporary wxString, but the function is expecting a reference. C++ will automatically convert a temporary to a const reference, but it cannot convert it to a reference. You need to make ShowComboDialog take a const reference as its second pa...
4,839,655
4,839,995
C++ Multi dimensional array from external file question
I'm trying to get a contiguous line with values separated by "&" to load into a multi-dimensional array. Here's the way I'm trying to do it - Everything checks out in the code, except the string "str" which contains my separated values in the format "value1, value2, value3, etc..." just loads that whole string into ar...
Because code and data are different things. Your code is compiled before it runs. It sounds as if this is what you expect: The string contains the text "foo, bar, baz". The statement string[] whatever = {str}; is run. Since "str" contains "foo, bar, baz", you want it to have the same effect as if the line of code were...
4,839,735
4,839,769
How to create a mp3 player?
Possible Duplicate: Building a simple mp3 music player I want to create simplest mp3 player in C or C++. What function or API do I have to use ?
If you just want to write a C or C++ program which plays an mp3 file, you might want to look here: How to play MP3 files in C?. If you are looking to write something more complex (say a full GUI application to select and play mp3s, including elements to play/pause, jump to a part of the song (and see what part is playi...
4,839,820
4,839,856
How to open a generic file?
I need a way to open a generic file with the default application for that file. For example: if the file is an HTML file, then it will be opened with Internet Explorer; if the file is an image (JPG, BMP, etc.), then it will be opened with "Paint"; if the file is an MP3 file, then it will be opened with Windows Media Pl...
Use the ShellExecute function: http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx EDIT: or ShellExecuteEx
4,840,028
4,840,081
Advantages of a 64 bit system
From a developer perspective i am trying to understand , what is the selling point of a 64-bit system ? I understand that more registers are at your disposal , more memory can be allocated to a process , but i cannot understand what makes a developer's life easier. Any examples ? From a performance perspective are ther...
When you have 64-bits of address space to play with, you can adopt certain designs that would be very hard with less of an address space. For example, a friend recently pointed out to me that address space for thread stacks can get to be a problem with thousands of threads on a 32-bit system. But on a 64-bit system, th...
4,840,051
4,840,073
(mingW) Why does g++ not recognise my class definition when compiling a python extension?
So I am working on a small python extension using the SWIG library. I use 3 commands to compile the extension. the first 2 ones use gcc, and the final one g++, giving a python extension as a result. My problem is that after gcc compiles the code with no errors, g++ starts to complain it can not find one of my class def...
It looks like the compiler is finding the declaration just fine, but not the definition. In other words, you've prototyped the constructor, but you haven't implemented it anywhere. From the compiler output it doesn't seem like you're linking in your .cpp file containing the implementation, which is likely the cause o...
4,840,058
4,840,071
Packaging source files from around my computer
I'm writing an application in C++ for a university assignment and I need to compress the source files in a zip file and email them to my supervisor for assessment. The problem is I have a 'toolbox' in a separate directory that contains a custom namespace that contains a lot of functions and classes I've found myself re...
There probably is, but the easiest thing to do is write a short script that copies everything into a temporary directory, then zips that directory.
4,840,110
4,841,801
trouble calculating offset index into 3D array
I am writing a CUDA kernel to create a 3x3 covariance matrix for each location in the rows*cols main matrix. So that 3D matrix is rows*cols*9 in size, which i allocated in a single malloc accordingly. I need to access this in a single index value the 9 values of the 3x3 covariance matrix get their values set according ...
Rather than the answer (which I haven't stared hard enough to find), here's the technique I usually use for debugging these sorts of issues. First, set all values in your destination array to NaN. (You can do this via cudaMemset -- set every byte to 0xFF.) Then try uniformly setting every location to the value of the r...
4,840,441
4,840,469
Can I Access a calling function's name programmatically?
I'm hoping to add a little functionality to a Log File system for a project I'm working on. For my LogError() calls, I would like to include the function the error occurred in. I'm wondering if there's a way that I can access the name of the function that called LogError() so I can programmatically access that inform...
You could add an argument for the function name, and pass in the __FUNCTION__ macro: http://msdn.microsoft.com/en-us/library/b0084kay%28v=vs.80%29.aspx And you could also define a macro that will automatically replace ...log...() with ...log...(__FUNCTION__).
4,840,492
4,842,000
Peak Filter has clicks and pops
OSStatus MusicPlayerCallback ( void * inRefCon, AudioUnitRenderActionFlags * ioActionFlags, const AudioTimeStamp * inTimeStamp, UInt32 inBusNumber, UI...
As per hotpaw2's answer, here's the plot of your filter's response: from pylab import * import scipy.signal as signal def biquad_peak(omega, gain_db, bandwidth): sn = sin(omega) cs = cos(omega) alpha = sn * sinh(log(2) / 2 * bandwidth * omega / sn) gain_sqrt = 10.0 ** (gain_db / 40.0) # feed-forwa...
4,840,704
4,840,719
Embedded structs and correct function calls
You're given two structs. One of type 'A', another of type 'B'. The one of type 'B' has a struct of type 'A' in it. So something like this: struct A { void print_stuff(A * a){ puts("From A"); } }; struct B { A a_part; char * s; void print_stuff(B * b){ printf("From B\n\t%s\n", b->s); ...
You could make print_stuff a function pointer, but then you need to manually hook it up to the correct function. In this case though, you're just replicating C++ inheritance mechanisms so it's pointless. The A object can't automatically know where it's contained, or if it's contained at all. So the bottom line is, just...
4,840,819
4,840,961
C++ Template Specialization with Constant Value
Is there a straightforward way for defining a partial specialization of a C++ template class given a numerical constant for one of the template parameters? I'm trying to create special constructors for only certain kinds of template combinations: template <typename A, size_t B> class Example { public: Examp...
I think this might work: #include <iostream> template <typename A, size_t B> class Example { public: Example() { Construct<B>(identity<A, B>()); } A foo() { return foo<B>(identity<A, B>()); } private: template <typename A, size_t B> struct identity {}; template <s...
4,841,032
4,857,854
PropertySheet tabs close on click
I am making a PropertySheet control with the Windows API, and for some reason tabs are closing when I click on them. For instance, if I add 4 tabs: Then if I click on any of those tabs except the active one (in which case nothing happens), it becomes: And if I click on the inactive tab it disappears, leaving only on...
It was because you must have at least 1 control in the dialog template.
4,841,086
4,843,903
How do I fix eroded rectangles?
Basically, I have an image like this or one with multiple rectangles within the same image. The rectangles are completely black and white have "dirty" edges and gouges, but it's pretty easy to tell they're rectangles. To be more precise, they are image masks. The white regions are parts of the image which are to be "l...
If the bounding box that contains all non-black pixels can do what you want, this should do the trick: int boundLeft = INT_MAX; int boundRight = -1; int boundTop = INT_MAX; int boundBottom = -1; for(int y=0;y<imageHeight;++y) { bool hasNonMask = false; for(int x=0;x<imageWidth;++x) { if(isNotMask(x, y))...
4,841,282
4,841,442
boost::shared_ptr semantics (copying)
I just wanted to have a fresh pair of eyes that the below code is correct in that: The pointers contained in the object trifoo (stored in a ptr_vector) are the shared pointers f, g, h. Also, what is the result of the shared_ptr copy in the constructor of trifoo; is this the correct method of 'sharing' shared_ptr, ensur...
The code seems to be technically correct. Semantics of copying a shared_ptr, however it is done, is that the reference count of the referred-to object is increased. It just works. Nothing to worry about. Some style issues, though: Passing shared_ptr by reference, or declaring it const, is meaningless. That's because i...
4,841,377
4,841,389
stringstream::in syntax error
I am trying to use a stringstream to do something like this (I simplified my code to pinpoint the error): Token.h #include <stdio.h> #include <vector> #include <sstream> using namespace std; class Token { public: static stringstream ss (stringstream::in | stringstream::out); static void set_input_string(std::st...
You cannot initialize non-integral values in the class definition. You should have: // Token.h #include <cstdio> // thisis the C++ header #include <vector> #include <sstream> // don't do this, especially not in a header file - function-scope at best // using namespace std; class Token { public: static std::string...
4,841,449
4,841,470
How to reference .cpp files without including them into the solution in Visual Studio?
I'm trying to compile this code: extern "C" { #include <lua.h> #include <lualib.h> #include <lauxlib.h> } #include <luabind/luabind.hpp> #include<iostream> int main(){ lua_State*pL=lua_open(); luabind::open(pL); lua_close(pL); return 0; } But I don't have a .lib of luabind, so I use the source with the ...
Compile the lua cpp files into a static library. Add the directory where you put those under "linker | input | additional library directories".
4,841,546
4,841,584
SAFELY get path to running executable in windows API
Hey, I'm trying to get the path to a dll located in the same folder as my exe file. The way to go seems to be to use one of either QueryFullProcessImageName() or GetModuleFileName() to get the path to the running executable and then use string manipulation to make it a path to the required library instead. Unfortunatel...
In practice you can use Windows API MAX_PATH as your buffer size, perhaps add 1 for extra safety. In theory a Windows path can be much larger. As I recall MAX_PATH is like 270 or thereabouts, while in the NTFS file system a path can be up to around (roughly) 32767 chars. However, for that large size it has to be handle...
4,841,792
4,842,470
How to make my C++ class event system be a template class limited to an array of types?
I want to use memcpy within class template. So my template will be limited to any link to C POD (structure) and char* (and ofcourse structures can be declared in other independent classes). I want any class to be able to subscribe its function (if it has respectful input args) to cast event. So my class now looks like:...
Your problem has been addressed by the boost::signals library. If you are interested in the inner workings you can try to implement something similar using the boost::function and boost::bind libraries. You can research the Modern C++ Design for details about the inner workings of functor templates, or just google&ask ...
4,841,983
4,842,280
GNU/Linux: getting value of option 15 of DHCP without using `getnameinfo`
My GNU/Linux machine is connected to a DHCP. I want to retrieve the value of the option 015 of DHCP (DNS Domain Name), but without using getnameinfo, since it is using DNS in order to retrieve domain name. How can I do that with C/C++?
My dhclient writes a pile of lease information into /var/lib/dhcp3/dhclient-[uuid]-[iface].lease files. I haven't got a clue what the uuid in those filenames represents, but it does report the different options from the dhcp server.
4,841,988
4,842,024
How to access the protected member if we cannot modify the class?
The third party library's class contains a protected member. How can I access it if we cannot modify the code of the third party library?
A protected member can only be accessed by the class itself, subclasses, or friend classes and methods. The only way to access the protected member is to subclass the class, then use your subclass to expose the protected member. Eg: class parent { /* Other members */ protected: int foo(); } class child : pub...
4,842,056
4,842,120
Do static members of a class occupy memory if no object of that class is created?
Say I have a class and I have a static member in it, but I don't create any objects of that type. Will the memory be occupied for the static variable? If it would be occupied, what is the point of putting it in a class?
No. Static members don't belong to the instances of class. They don't increase instances and class size even by 1 bit! struct A { int i; static int j; }; struct B { int i; }; std::cout << (sizeof(A) == sizeof(B)) << std::endl; Output: 1 That is, size of A and B is exactly the same. Static members are more...
4,842,091
4,842,101
Why are the static members of a class the same for all objects?
Why don't we have different copies of static variables for the different objects?
Because they would be instance members then. The primary characteristic of static members is that they're shared by all the instances of the class.
4,842,213
4,842,253
How exactly an access violation exception is triggered
Sometimes bugs can cause memory access violation exception. How exactly this exception is triggered? What mechanism works behind the scenes? Does it need support from the CPU (starting at what CPU?) / from the OS (starting at what version?) / from the compiler (starting at what version?) Edit: One specific scenario I ...
Memory access violations are a large topic :) The Protection of Information in Computer Systems (from 1973 :) lays out of a mechanism of segments, where processes are allocated a base and a bound; any attempt to access memory outside the range base:base+bound meant the program had done something silly and should be kil...
4,842,290
4,842,324
Dynamic Arrays in C++
I'm trying to find the size of an array, and sizeof isn't working properly presumably because my array is a pointer, not an actual array (then again, I'm probably wrong). I'm new to C++, but not to programming. Here's my function: int getSizeOfPointerArray(int a[]){ int n=0; while(true){ if(!a[n]){ ...
When you allocate an "array" with new, you're just being given some arbitrary memory location that isn't currently being used by anything else. That memory (and its surroundings) are most likely filled with random junk, and probably not zeros. Writing known non-zero values to p[0], p[1] and p[2] will not affect the j...
4,842,365
4,842,454
Indirect call of virtual function from Destructor
Let me make this disclaimier : I have clear understanding of virtual function call in Constructor or Destructor. In the below code I am trying to avoid virtual destructor ONLY FOR EXPERIMENTAL purpose. Now my question is: In main the call to Destroy fun calls the right virtual function. I am expecting any call to Destr...
In a destructor, the dynamic type of this is that of the current class, not the original dynamic type of the object. See e.g. http://www.artima.com/cppsource/nevercall.html.
4,842,411
4,842,431
Sending array through sockets
I am trying to send an array using send(): char* packet = new char[3]; packet[0] = 0; packet[1] = 1; packet[2] = 2; And I am trying to print it like this: char temp[3]; Recv(temp, 3); for(unsigned int i = 0; i < 3; i++) { cout << temp[i] << endl; } But I only get 2 strange characters an the screen. What could be ...
When you use couture to print out the characters, it's treating them as characters and not numerical values. Since you sent 0, 1, and 2, which are all low-order ASCII values, the system can render them with whatever glyphs it wants, or perhaps not at all. In this case, I'd guess that the characters are mapping to a n...
4,842,434
4,842,474
Is Memory Layout for a class successive?
When we declare object of a class is its memory layout successive(One after the other)?If its successive than does padding occurs in it (like structure padding)?Please help me out with the concepts of memory layout for a class Thanks in advance.
When we declare object of a class is its memory allocation successive(One after the other)? The Standard doesn't give any such guarantee. Object memory layout is implementation-defined. Usually, memory address for data members increases in the order they're defined in the class . But this order may be disrupted a...
4,842,472
4,842,528
Can we turn such structure into typed class/function?
So in structure like struct RenderCastedDataFunctor { simpleRendererGraphElement* obj_; RenderCastedDataFunctor(simpleRendererGraphElement* obj) : obj_(obj) { } void operator()(char* castedChar, int castedCharLength) { obj_->renderCastedData(castedChar, castedCharLength); } }; ca...
can we turn simpleRendererGraphElement* into abstract type and make its function name we use in structure (renderCastedData) abstract too? Very very good idea. You should do this. Make the class abstract by making it's functions virtual, and then define a concrete class (deriving from this abstract class) whi...
4,842,508
4,842,526
How can I determine a file's creation date in Windows?
How can I get the date of when a file was created? I am running Windows.
Use stat function see here #include <sys/stat.h> #include <unistd.h> #include <time.h> struct tm* clock; // create a time structure struct stat attrib; // create a file attribute structure stat("afile.txt", &attrib); // get the attributes of afile.txt clock = gmtime(&(attrib.st_mtime))...
4,842,570
4,842,621
Data Structure with inheritance. Problems initializing
I need make a class, let's say FineStack, who should declare a structure able to manage different kind of Fines ( LightFine, SeriousFine ). The superclass for both is Fine. The question is, do I really need templates? I thought it was not necessary, so this is what I thought: -> declare Fine *fines; ( kind-of array of ...
I would like to point you in the right direction and not just give you the whole shebang. If this doesn't help, please ask about what's troubling you: Although Fine cannot be instantiated, you can point to it, so: Fine* f1 = new LightFine(); Fine* f2 = new SeriousFine(); are both legal, because LightFine is-a Fine and...
4,842,881
4,842,904
How to print the directory tree?
Is there a way to print the directory tree with all files contained ?
Yes, use the FindFirstFile and FindNextFile api. Use these recursively (or even better, using a stack) to find the entire directory structure. MSDN example
4,842,901
4,842,963
C++ - statement cannot resolve address for overloaded function
When I types the following as a stand-alone line: std::endl; I got the following error: statement cannot resolve address for overloaded function Why is that? Cannot I write std::endl; as a stand-alone line? Thanks.
std::endl is a function template. Normally, it's used as an argument to the insertion operator <<. In that case, the operator<< of the stream in question will be defined as e.g. ostream& operator<< ( ostream& (*f)( ostream& ) ). The type of the argument of f is defined, so the compiler will then know the exact overl...
4,842,952
4,842,955
Code optimization; switch versus if's
I have a question about whether to use 'case' or 'ifs' in a function that gets called quite a lot. Here's the following as it is now, in 'ifs'; the code is self-explanatory: int identifyMsg(char* textbuff) { if (!strcmp(textbuff,"text")) { return 1; } if (!strcmp(textbuff,"name")) { return 2; } if (!strcmp(tex...
You can't use switch statements for strings because they are pointers and are not evaluted at compile time. You are stuck with using a bunch of if statements. However for the sake of performance, I believe switches perform better when there are more conditions to check but the difference will be so minute it wouldn't m...
4,843,078
4,843,102
limit the size of a std::set
I have a short question about the std::set container. Right now I am feeding my set using the pushback function. Of corse the set becomes larger and larger for every push_back. I am only intrested in the latest 30 elements or so... The older elements can be deleted. So my idea is to limit the size of the set to 30 elem...
You'll need to build a LRU structure yourself. One way to do this would be to have a std::map and std::list pointing to each other's iterators. That is: struct lru_entry { std::list<lru_entry *>::iterator lru_iterator; std::map<your_data, lru_entry *>::iterator map_iterator; }; std::list<lru_entry *> lru; std:...
4,843,169
4,848,781
can't read utf8 strings from MySQL DB by an odbc client
I have a DB with utf8 default charset, and a table that contains strings with non-ascii characters. I can read the data correctly by the mysql client program and the isql odbc client program (see examples below). However, when I read the table in my C++ client using the libodbc++ odbc wrapper, I get garbage. Curiously...
Well, found the guilty - it's the libodbc++ library, as the edit says. Going to write to the authors. The solution would be to replace it with the MySql C++ connector. They both are modeled after JDBC, so the change is not big. Hope I will not be changing the DB soon...
4,843,304
4,843,444
Why is my power operator (^) not working?
#include <stdio.h> void main(void) { int a; int result; int sum = 0; printf("Enter a number: "); scanf("%d", &a); for( int i = 1; i <= 4; i++ ) { result = a ^ i; sum += result; } printf("%d\n", sum); } Why is ^ not working as the power operator?
Well, first off, the ^ operator in C/C++ is the bit-wise XOR. It has nothing to do with powers. Now, regarding your problem with using the pow() function, some googling shows that casting one of the arguments to double helps: result = (int) pow((double) a,i); Note that I also cast the result to int as all pow() overlo...
4,843,559
4,843,799
C++ fixed size arrays vs multiple objects of same type
I was wondering whether (apart from the obvious syntax differences) there would be any efficiency difference between having a class containing multiple instances of an object (of the same type) or a fixed size array of objects of that type. In code: struct A { double x; double y; double z; }; struct B { doubl...
Typically the representation of those two structs would be exactly the same. It is, however, possible to have poor performance if you pick the wrong one for your use case. For example, if you need to access each element in a loop, with an array you could do: for (int i = 0; i < 3; i++) dosomething(xvec[i]); Howeve...
4,843,569
4,843,576
C++ std::string usage with !=, <, and >
What are the examples on usages of std::string class with !=, >, and <?
s1 != s2 returns true if s1 is not equal to s2. It's case sensitive! s1 < s2 returns true if s1 comes before s2 if they're arranged in dictionary order. If string s1 ="Nawaz" and string s2 = "nawaz", then s1 < s2 will return true. s1 > s2 returns true if s1 comes after s2 if they're arranged in dictionary order. As ...
4,843,768
4,843,826
Using QString get strange characters in the output
int a=0; while (a<2) { //infos.stops is point to one array, called abc[10] output = output + QString::fromStdString(*infos.stops)+ "." ; infos.stops++; a++; } ui->showMsg->setText(output); The problem is infos.stops did show, but some funny characters appear like: I have uploaded all my source code...
Try using output = output + QString::fromStdString(*(infos.stops))+ "." ;
4,843,772
4,843,952
enumerating child windows
A couple of weeks ago someone here helped me out with writing a class that enumerates all main windows. Today I tried to modify that class in order to enumerate all child windows of a specific parent window. Here is the header file: #include "TChar.h" #include "string.h" #include "windows.h" #include "Winuser.h" #inclu...
Instead of calling EnumWindows, which enumerates over all top-level windows on the screen, you can call EnumChildWindows to enumerate child windows of a given parent window. To do this, you can add an overload of enum_windows to your Handles class: Handles& enum_windows(HWND hParentWnd) { stuff.clear(); ...
4,843,806
4,843,828
WinAPI: Create a window with a specified client area size
I was wondering how can I create a window using Win32 API with a specific client area size. When trying to create a window using the following piece of code, the entire window is 640x480, with the window's chrome taking some of the client area: HWND hWnd; WNDCLASSEX WndClsEx; ZeroMemory(&WndClsEx, sizeof(WNDCLASS...
You can use the AdjustWindowRect or AdjustWindowRectEx function to calculate the window size given a desired client area size.
4,843,910
4,843,942
Editing a 10gb file using limited main memory in C/C++
I need to sort a 10gb file containing a list of numbers as fast as possible using only 100mb of memory. I'm breaking them into chunks and then merging them. I am currently using C File pointers as they go faster than c++ file i/o(atleast on my system). I tried for a 1gb file and my code works fine, but it throws a segm...
There is a special class of algorithms for this called external sorting. There is a variant of merge sort that is an external sorting algorithm (just google for merge sort tape). But if you're on Unix, it's probably easier to run the sort command in a separate process. BTW. Opening files that are bigger than 2 GB requi...
4,844,009
4,844,198
how to print a whole row from an array?
I wrote a program which shows the data about 5 students I want to know how to show the student name registration number and marks who obtained highest marks in the array. The program is like that: #include "stdio.h" #include "conio.h" struct student { char name[30]; char reg[10]; short int marks_dbms; ...
Thats a simple one. int maxDbmsMarks = 0; int maxMarksIndex = 0; for(int i = 0; i < 5; i++) { if(a[i].marks_dbms > maxDbmsMarks ) { maxDbmsMarks = a[i].marks_dbms; maxMarksIndex = i; } } printf("Student with the maximum dbms marks :\n"); printf("Name : %s, Reg : %s, dbmsMarks: %d, progMarks ...
4,844,163
4,844,826
C++: Problem while overloading same operator in 2 different classes
First of all thank you very much for your clues. I'm having a particular problem while trying to finish an assignment. I'm pretty sure is something wrong with namespaces, includes, header files and all this stuff, but don't really know what's going wrong. The point is this: I need two different classes (let's say Car ...
As others have pointed out, you can't just declare these as friends: Car &operator+(const Car &c); CarShop &operator+(const Car &c); Even if you could compile and link it, it just wouldn't work. And you can't link because they have the same signatures (the return type isn't included in the signature). You have two cho...
4,844,273
4,844,343
Is it possible to prepend data to an file without rewriting?
I deal with very large binary files ( several GB to multiple TB per file ). These files exist in a legacy format and upgrading requires writing a header to the FRONT of the file. I can create a new file and rewrite the data but sometimes this can take a long time. I'm wondering if there is any faster way to accomplish ...
There's no general way to do this natively. Maybe some file-systems provide some functions to do this (cannot give any hint about this), but your code will then be file-system dependent. A solution could be that of simulating a file-system: you could store your data on a set of several files, and then provide some fun...
4,844,445
4,844,473
How is the Win32 API used in C++ to minimize a window to the system tray?
Pretty much a self-explanatory title. I'm writing an application in C++ with the Win32 API, and I'd like to know how to minimize to the system tray. I can find all kinds of articles online about minimizing to the system tray in C#, Python, even Visual Basic, I think, but for the life of me I can not find a single artic...
All you need is the Shell_NotifyIcon function. You ought to be able to work it out from MSDN, but if you need more help I'm sure there are a million places on the web that give samples. Now that you know the name of the API, web search will fill in the gaps.
4,844,533
4,844,757
Using #define for library configuration
I'm working on a C++ maths library in which I want to be able to configure at compile time using defines. One of the configurations is defining the precision. In code it looks like this: #ifdef MYMATH_USE_DOUBLE typedef double Real; #else typedef float Real; #endif That works fine. If someone wants to then use...
Usually, the best practice is to run "configure" script, that creates one file with all defines. And this file is included in all headers. For example, if you compile OpenSSL from sources, "configure" creates e_os.h (as far as a remember the name), that is included practically in every header.
4,844,611
4,844,622
C++: Initialization Lists / Naming conventions
The following code works on my machine, but is it good practice / guaranteed to work? struct MyStruct { MyStruct(int x, int y, int z) : x(x), y(y), z(z) { } int x; int y; int z; }; Specifically, is x(x) guaranteed to do what I want? (that is, does the variable in an initialization ...
Yes, that is guaranteed to do what you expect. The only thing that can exist "outside" the parentheses in an initializer list are member variables. And inside the parentheses, the usual rules apply; local variables hide member variables. As to whether it's good practice, well, consider what happens if you accidentally...
4,844,651
4,853,386
Boost::python Exposing C++ functions using and returning templates
I need to build python bindings for a C++ codebase. I use boost::python and I ran into problems trying to expose classes containing functions using and returning templates. Here is a typical example class Foo { public: Foo(); template<typename T> Foo& setValue( const string& property...
This may not be related to your problem directly but I would not trust function signature casting with templates like that. I would have wrapped it like this: class_<Foo>("Foo") .def("setValue", &Foo::setValue<double>, return_value_policy<reference_existing_object>()) .def("getValue", &Foo::getValue...
4,844,669
4,844,721
why there are no multimethods in c++?
I read many article about how to implement multimethod in c++: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1529.html http://www.codeproject.com/KB/recipes/mmcppfcs.aspx http://lambda-the-ultimate.org/node/2590 http://parasol.tamu.edu/people/peterp/omm/ why there are no multimethod in c++? why do not they...
Straight from the horse's mouth: "I rejected multi-methods with regret, because I liked the idea, but couldn't find an acceptable form under which to accept it." Bjarne Stroustrup, The Design and Evolution of C++ (p297) And later: "Multi-methods is one of the interesting what-ifs of C++. Could I have designed and ...
4,844,830
4,854,219
GLEW and openGL deprecation
I am using openGL and glew to check the extensions. Say I wanted to check if I could use multitexture extension: GLEW_ARB_multitexture will return true if I can use it. BUT arb_multitexture was deprecated in openGL 3.0. Will it still return true? What about in 3.1 where it was removed? Thanks.
It'll return true if your context exports the extension, which it will if it's not "forward-compatible" or "core profile", or possibly if it supports the "GL_ARB_compatibility" extension. The bottom line is, if GLEW_ARB_multitexture is true, you can use the functionality. Any higher-level logic (like only using shader...
4,844,842
4,845,019
Boost::Signals for C++ Data copying
Recently I had a class that looked like class IGraphElement{ typedef void FuncCharPtr(char*, int) ; public: void Add(FuncCharPtr* f) { FuncVec.push_back(f); } void CastData(char * data, int length){ for(size_t i = 0 ; i < FuncVec.size(); i++){ char* dataCopy = new char[l...
You are doing one mistake: you assume that the function you're calling will free the resources (the char* pointer) you give it. You should do something like: void CastData(char * data, int length){ for(size_t i = 0 ; i < FuncVec.size(); i++){ char* dataCopy = new char[length]; memcpy(dataCopy, data,...
4,844,886
27,344,958
How can I loop through a C++ map of maps?
How can I loop through a std::map in C++? My map is defined as: std::map< std::string, std::map<std::string, std::string> > For example, the above container holds data like this: m["name1"]["value1"] = "data1"; m["name1"]["value2"] = "data2"; m["name2"]["value1"] = "data1"; m["name2"]["value2"] = "data2"; m["name3"]["...
Old question but the remaining answers are outdated as of C++11 - you can use a ranged based for loop and simply do: std::map<std::string, std::map<std::string, std::string>> mymap; for(auto const &ent1 : mymap) { // ent1.first is the first key for(auto const &ent2 : ent1.second) { // ent2.first is the second ...
4,845,192
4,845,213
Does new set pointer to NULL if it throws std::bad_alloc?
I know doing a new(std::no_throw) will set pointer to NULL if it failed. I also know that a normal new will throw a std::bad_alloc exception if it failed. Will the normal new also set the pointer to NULL if it throws? Or should I set it to NULL in the catch() block?
In C++ a bad new will throw an exception (unless you use std::nothrow) and the pointer will not be assigned so it'll be whatever it was before the new call was made. However, you may be interested in this article which talks about forcing new to return null on failure as you mentioned in your question.
4,845,198
4,845,893
Fatal error: "No Target Architecture" in Visual Studio
When I try to compile my c++ project using Visual Studio 2010 in either Win32 or x64 mode I get the following error: >C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\include\winnt.h(135): fatal error C1189: #error : "No Target Architecture" My preprocessor definitions say WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefini...
Use #include <windows.h> instead of #include <windef.h>. From the windows.h wikipedia page: There are a number of child header files that are automatically included with windows.h. Many of these files cannot simply be included by themselves (they are not self-contained), because of dependencies. windef.h is one of th...
4,845,338
4,845,461
Bugs in a Decimal Multiplier
I am writing a decimal multiplier in C++. The multiplier is implemented by taking two integers represented as vectors of digits. Each vector stores its digits in reverse order, for easier representation by powers of ten. For example, 3497 = 3 * 10^3 + 4 * 10^2 + 9 * 10^1 + 7 *10^0 and is stored in a vector as {7, 9, 4,...
You're not clearing out the carry before (or after) the inner loop. // iterate through decimal vectors for(i = 0; i < a.size(); ++i) { ... } // append carry if relevant if(c != 0) { p.push_back(c); // add this line c=0; } Also, in add you probably want: // compe...
4,845,410
7,770,651
error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
I don't know what's wrong with it.. I can't find where the error is, commenting out the implementation doesn't resolve the error either. Header File #ifndef MAIN_SAVITCH_SEQUENCE_H #define MAIN_SAVITCH_SEQUENCE_H #include <cstdlib> // Provides size_t namespace main_savitch_3 { class sequence { public: ...
Even if your project has a main() method, the linker sometimes gets confused. You can solve this issue in Visual Studio 2010 by going to Project -> Properties -> Configuration Properties -> Linker -> System and changing SubSystem to Console.
4,845,504
4,845,529
How to make typedef on void function that could be property of any class?
When we do typedef void FuncCharPtr(char*, int) ; vector<FuncCharPtr*> FuncVec ; void Add(FuncCharPtr* f) { FuncVec.push_back(f); } we do not allow to pass as FuncCharPtr types like void (someClass::*)b(char*, int); void (someOtherClass::*)b(char*, int); and we want to keep links to functions from both classes ...
You can't use a function pointer for this. The class type is a part of the type of a pointer to a member function, so there is no one type that would work. The best way to accomplish what you want to do is to use the function class and the bind function from Boost, C++ TR1, or C++0x. You can maintain a std::vector<s...
4,845,653
4,845,764
TrackPopupMenu : Window disabled after menu dissapears
I have added a popup menu to my app, and it is activated with this code: HMENU contextMenu; int CALLBACK WinMain(...) { HMENU hContext = LoadMenu(GetModuleHandle(NULL), MAKEINTRESOURCE(IDR_CONTEXT_MENU)); contextMenu = GetSubMenu(hContext, 0); } case WM_RBUTTONDOWN: { POINT pt; pt.x = GET_X_LPARAM(lPar...
Why are you showing your menu in WM_RBUTTONDOWN handler? It should be WM_CONTEXTMENU instead, and you must keep in mind it may be generated by the keyboard, and contain no coordinates. Or at least use WM_RBUTTONUP inetead.