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
7,718,418
7,718,469
Arranging elements in a vector by their status
Let's have simplified class: class A { bool val_; public: A() : val_(true) {} bool isNew() const { return val_; } void setDirty() { val_ = false; } }; and the vector of objects of such class: vector<A> coll; coll.push_back(A()); coll.push_back(A()); coll.push_back(A()); coll.push_back(A()); coll[1...
You can use Partition algorithm from standard library for that: bool MyPredicate(A& a) { return a.isNew();} ... // bound is iterator pointing to the first element for which predicate returns false vector<A>::iterator bound = partition(coll.begin(), coll.end(), MyPredicate); Or, as Christian Rau suggested solution with...
7,718,420
7,755,199
Variadic templates, compiler apologies
I had asked the similar question before , understood that i can make it work by partially specialization. But to understand variadic templates basics i modified the code such like this. template<typename T, typename... args> struct counter{ static const int value= 1+ counter<args...>::value; }; template<typename T> st...
The second version avoids the bug because the primary template is declared as template<typename...>, i.e. it's variadic. The key to the bug is in the error message: "sorry, unimplemented: cannot expand 'args ...' into a fixed-length argument list" (emphasis mine). Thus counter<Args...>::value will work on that second c...
7,718,471
7,718,946
C++ Search Windows Registry
I'm trying to search the registry for keys in a particular group(Local-> Windows -> Uninstall) so I can eventually uninstall these applications programatically. I am having problems getting the key name so I can open it. Here is what I have tried: void Uninstall::uninstallProgram(string appName) { HKEY currentKey...
It seems that you just forgot to request KEY_ENUMERATE_SUB_KEYS access right. Also it's possible that I do not understand exactly what are you trying to do but AFAIK Uninstall folder have different location. HKEY currentKey; TCHAR name[1024]; DWORD dwSize = 1024, dwIdx = 0; long result; result = RegOpenKeyEx(HKEY_CURRE...
7,718,508
7,718,531
Order of evaluation of arguments using std::cout
Hi all I stumbled upon this piece of code today and I am confused as to what exactly happens and more particular in what order : Code : #include <iostream> bool foo(double & m) { m = 1.0; return true; } int main() { double test = 0.0; std::cout << "Value of test is : \t" << test << "\tReturn value o...
The evaluation order of elements in an expression is unspecified (except some very particular cases, such as the && and || operators and the ternary operator, which introduce sequence points); so, it's not guaranteed that test will be evaluated before or after foo(test) (which modifies it). If your code relies on a pa...
7,718,689
7,718,779
#include .h or .cpp file?
So I have this weird looking problem: my very basic program generates an error message (undefined reference to 'foo::foo(int)') when i import the .h file of a separate class. However, when I change the import file to .cpp, it all works. Now, I've read a little, and seen a few video tutorials, and they all say the same...
You need to compile both main.cpp and foo.cpp and link the 2 resulting object files together.
7,718,949
7,719,053
How to make a linked list in using structs?
I've seen a few topics about linked lists, and I've read enough to glean how to do it generally, but I want to make sure I'm not wrongly interpreting the information I've gathered. Let's say I have: struct element { int val; element *next; }; The element *next is a pointer to an element, which will be...
With singly-linked lists, the efficient way to add new elements is putting them at the beginning of the list. For your design, this would be: element newHead; newHead.next = &list; You'll notice that newHead is now the first element, and list no longer represents the whole list. This leads to a more functional progr...
7,719,187
7,719,209
Using char as array index in C?
I have this code: int main(){ char vector[52]; char i; /* initialize the vector */ for (i ='a'; i < 'z'; i++){ vector[i] = i - 'a' + 1; } // vector is like vector['a'] = 1, vector['b'] = 2 .. vector['z'] = 26 for (i ='A'; i <= 'Z'; i++){ vector[i] = i - 'A' + 27; } // vector is like vecto...
Because 'Z' is not equal to 'z'. 'Z' is equal to 90 and your vector only has 52 elements. Your highest index is 51 so you are basically going out of bounds! For example when you are doing this for (i ='A'; i <= 'Z'; i++) { vector[i] = i - 'A' + 27; } This is what your first iteration looks like: vector[65] =...
7,719,373
7,719,398
Initialise reference variable as a class member
I am trying to convert a function from a camera SDK I am using to a class, so I can call the different parts of the function separately (initialisation, capture image, clean up). A problem I am having is that some variables in the function are defined as: type& var = type::init(); This doesn't work when I do: class my...
References are not assignable. When you have a reference as a class member object, you need to initialize it in the constructor. For that, you use the constructor initialization list: class myClass { public: myClass( type& some_var ) : var( some_var ) {} private: type& var; };
7,719,715
7,719,725
friend function of a class
Can I make a function that is not member of any class be a friend of a class?If so could someone point me out to the syntax? I used this page as reference .On that it only has a function that is part of another class being made a friend.
Yes, you can. The syntax for this should be obvious from the example you pointed out: friend return_type free_function(args);
7,719,748
7,720,004
C++ stack implementation (homework)
SOLVED: I cannot for the life of me figure out why I get an error when trying to initialize the stack here: #include "stack.h" #include "linkList.h" Stack::Stack() : m_top(0), m_size(0) { m_stack = new List(); // cannot assign m_stack this way. How do i initialize here? } The syntax error according to Intellisen...
This error : 1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup Usually happens when your project is wrongly setup. I guess that you are writing a console app but you have selected as type of project something else than a console app.
7,719,772
7,720,497
Garbage character from query under 32-bit OS, fine in 64-bit
C++, OLEDB, running a query that returns 2 columns: an int and a varchar(50). So I want to put it in struct OutputData { int intID; wchar_t* lpszName; } outputData; So, I bind m_oleDBUtils.CreateDBBindings(true, &pRowsetBindings[0], 1, offsetof(OutputData, intID), 4, DBTYPE_I4, 0, ...
Switch to client-owned memory and /Zp1 fixed it.
7,719,865
7,720,717
How to play sound file in a Windows 8 Metro app using WinRT?
The WinRT API surface in Windows 8 seems to have the ability to load and save Playlists, and capture audio. What I'm looking for is somewhat simpler: does WinRT have the ability to play audio from a file? If not, what's the recommended API for native code (C++) to play audio from a file in a Windows 8 metro app?
If you're in a WWA, you want to use the HTML tag to play audio. In xaml, you want to use a MediaElement. If you're using low level C++, you want to use the MediaFoundation APIs.
7,719,905
7,719,938
allocation of a pointers to fixed size arrays
I have 2 doubts regarding basics of pointers usage. With the following code int (*p_b)[10]; p_b = new int[3][10]; // ..do my stuff delete [] p_b p_b is pointing to an array of 3 elements, each having fixed-size length of 10 int. Q1: How to declare p_b if I want that each element be a pointer to a fixed array size?...
p_b is pointing to an array of 3 elements, each having fixed-size length of 10 int. How to declare p_b if I want that each element be a pointer to a fixed array size? Does your first sentence not completely cover that question? Is per my original code sample above, how to call new so that p_b points to a unique fixe...
7,719,947
7,719,959
C++ Basic function program wont compile with a screen worth of errors
This program is giving me a full screen of errors when i try to compile it with g++ but i didnt even start the hard part. Just printing instructions. What is wrong here? /* Samuel LaManna CSC 135 Lisa Frye Program 2 Functions (Shipping Charges) Calculate the shipping and total charge for shipping spools of wire */ #in...
Here's one problem: << endl < endl; It should be: << endl << endl;
7,719,961
7,720,040
Why won't this do-while loop break out once the condition is not met?
what's up, I've got another issue with this huge project I'm working on. The project is for school, but this isn't the entire piece. For more information on the project you can look here. So I have to take input from the user in the following format: p 11:45 12:15 It will always start with either a p or an s and will h...
Your code (with a couple tweaks to make it compile) is working fine for me. Could you post the input you are sending to it that causes the program to fail?
7,719,978
7,719,994
Finding max value in an array
If I have an array, e.g. 10, 4, 7, 8 The value of the maximum element is 10 How can I find this value? Here's my attempt: int highNum = 0; int m; int list[4] = {10, 4, 7, 8}; for (m = 0 ; m < size ; m++); { if (list[m] > highNum) highNum = list[m]; cout << list[m]; } cou...
You have a semicolon after your for statement: for (m = 0 ; m < size ; m++); { This should be: for (m = 0 ; m < size ; m++) {
7,720,174
7,720,180
No match for operator>>
it says there is a problem with this function. It should get input from the user for number of spools to be ordered and then output the input it recieved. (thinking of adding a confirmation dialog if there is time). /********************************************/ // Name: inspools / // Descrip...
You have your arrows backwards in this line: cout >> spoolnum >> " spool(s) of wire will be shipped" >> endl; it should be: cout << spoolnum << " spool(s) of wire will be shipped" << endl; And your return statement needs to return something: return spoolnum;
7,720,312
7,720,473
How do I reference a dylib?
I have an application written in platform-independent C++ which has been primarily developed on Windows. I'm now trying to get it up and running on a Mac but I seem to be lost in how to link to the Mac version of a third-party library I'm using. I added the library's include and lib folders to header and library search...
Add a copy-files build phase that copies the dylib into the Frameworks folder inside the app bundle. (When you Get Info on a copy files build phase, Frameworks is one of the destination choices.)
7,720,327
7,720,340
Standard C++ data structure with multiple "indexes"
Is there standard structure or library in C++ (or C++11) that is something like like a set, but that could have more than one key. i.e. a set of std::pair that can be looked up fast by either a or b. So you could do something like this: std::string a = "hello"; std::string b = "world"; x.insert(a, b); x.get<1>("hell...
I'm not sure what your definition of "standard C++" is, but Boost.MultiIndex works with any standard C++ compiler.
7,720,332
7,720,356
C++ Ask user if input is correct error
Im trying to add code so if the user mistypes they can go back in the program and retype the input but im not sure if the code i found and used is correct. here it is in my function: /********************************************/ // Name: inspools / // Description: Ask for and get number of ...
You said you searched for loops, but I don't buy it. I imagine you are pretty new at programming. I'm going to give you the answer but not without some explanation first. How While Loops Work From Wikipedia: In most computer programming languages, a while loop is a control flow statement that allows code to be exec...
7,720,349
7,720,670
How can I restrict access to an unmanaged dll to only a specific 3rd party (denying access to all others)?
I created an unmanaged C++ DLL that I'd like to provide to a 3rd-party. The DLL will be distributed publically but I don't want anyone else to be able to call methods in the DLL. What's a good way to restrict access? FWIW - the DLL will be used on both Mac and Windows.
Ultimately, you can't stop somebody who's determined, but you can do a few things to make life difficult for unauthorized users. The obvious would be to encrypt (at least most of) the code in the DLL. Have a single entry point that the user has to call to get (for example) a table of pointers to the real functions. Whe...
7,720,360
7,721,985
Has anyone had any luck compiling this .NET binding for Mapnik?
So I'm trying to build this library that is a .NET binding for Mapnik http://mapnik.org. I ran the "../ext/install.cmd" file successfully but I think that only builds the boost library for c++. When I run the visual studio solution for it afterwards it still has like 900 errors! Mostly in 1 class for text rendering. h...
On systems older than Windows 7 patching can not be run if there are spaces in "Program Files" folder name. You can patch mapnik and ICU sources manually applying Mapnik.patch on MapNik folder and icu_vs2010.patch on icu one. If sources were changed previously they should be reverted before patching. After patching rer...
7,720,419
7,720,429
making dynamic array using Type** &x
With respect to the following code snippet for making a dynamic array template <class Type> void Make2DArray(Type** &x,int rows, int cols) { x=new Type*[rows]; for (int i=0;i<rows;i++) x[i]=new Type[cols]; } How to understand the usage of Type** &x, why it has two **
Type** is a pointer to a pointer. Type**& is a reference to a pointer which points to a pointer. ** will allow you to make an array of an arrays. This can be used for 2d arrays - x[][] will work.
7,720,628
7,720,643
How do I pull a reference from a pointer?
Forgive me as my C++ is very rusty. But I am in a bind. I am trying to make a custom list that have methods to return the front most, and back most items. ElementType& front() throw(string*) { if (empty()) throw new string("Empty Vector"); else return(first) } My main problem is that I don't have the...
If first is a pointer to your element, *first will give you a reference to it.
7,720,668
7,720,754
Fast multiplication/division by 2 for floats and doubles (C/C++)
In the software I'm writing, I'm doing millions of multiplication or division by 2 (or powers of 2) of my values. I would really like these values to be int so that I could access the bitshift operators int a = 1; int b = a<<24 However, I cannot, and I have to stick with doubles. My question is : as there is a stand...
You can pretty safely assume IEEE 754 formatting, the details of which can get pretty gnarley (esp. when you get into subnormals). In the common cases, however, this should work: const int DOUBLE_EXP_SHIFT = 52; const unsigned long long DOUBLE_MANT_MASK = (1ull << DOUBLE_EXP_SHIFT) - 1ull; const unsigned long long DOUB...
7,720,960
7,721,056
Difficulties with templated functions in templated classes
I'm running into an issue while trying to write a recursive template member function for iterating through tuples. In the following code: #include <cstddef> #include <iostream> #include <string> #include <tuple> template <typename... P> class A { public: typedef std::tuple<P...> tup_t; tup_t tup; }; template <ty...
The types have to match in both the declaration and definition of __func. So in the class definition you must declare __func as: template <size_t x> typename std::enable_if<(x > 1)>::type __func(const char* delim); (This is equivalent to using std::enable_if<(x > 1), void> as the second template parameter defaults to ...
7,721,026
7,721,062
Programmatically Ignore Cout
Does anybody know if there is a trick to toggle all the cout << functions to not print out visible output? I am trying to hack together some code written by me and some other people to put together a demo. I would rather not redirect the output to a file and would like a solution that had some measure of compatibility ...
You can change cout's stream buffer. streambuf *old = cout.rdbuf(); cout.rdbuf(0); cout << "Hidden text!\n"; cout.rdbuf(old); cout << "Visible text!\n"; Edit: Thanks to John Flatness' comment you can shorten the code a bit: streambuf *old = cout.rdbuf(0); cout << "Hidden text!\n"; cout.rdbuf(old); cout << "Visible te...
7,721,184
7,721,284
Is sizeof(*ptr) undefined behavior when pointing to invalid memory?
We all know that dereferencing an null pointer or a pointer to unallocated memory invokes undefined behaviour. But what is the rule when used within an expression passed to sizeof? For example: int *ptr = 0; int size = sizeof(*ptr); Is this also undefined?
In most cases, you will find that sizeof(*x) does not actually evaluate *x at all. And, since it's the evaluation (de-referencing) of a pointer that invokes undefined behaviour, you'll find it's mostly okay. The C11 standard has this to say in 6.5.3.4. The sizeof operator /2 (my emphasis in all these quotes): The size...
7,721,244
7,721,300
c++ template function specialization - wrong number of template arguments?
Okay, so I'm just learning about templates. Anyways, I'm probably (most definitely) doing something wrong, but here's the problem: My first template function is declared like this: template<typename T> std::ostream& printFormatted(T const& container, std::ostream& os = std::cout) { //... } Then I'm supposed to imp...
Assuming your uses of key and value are meant to be placeholers, you cannot declare template parameters inline with the keyword typename. That is to say, Foo<typename T> is always invalid -- but not to be mistaken with Foo<typename T::bar> which is different altogether. The syntax for specialization looks like: // Decl...
7,721,303
7,721,313
Use enum inside struct inside class?
I have wrapped a struct around an enum to get a scoped enum. E.g.: namespace Xyz { struct SortDirection { enum Enum {ASC, DESC}; }; class MyClass ... This works fine. Now I'm trying to define the same type of enum/struct combo but this time inside the class: class MainDialog { public: ...
Try struct SomeType { // Note the open brace
7,721,335
7,721,419
Is it possible to pass Javascript objects to ActiveX (and use them)?
I want to pass JavaScript objects (JSON and function objects) into my ActiveX control. Ideally, I could manipulate JavaScript objects (e.g. reading or modifying JSON) and perform JavaScript function calls from within the ActiveX control (using C++). Is any of this possible, or do I have to settle for passing strings? F...
Wow, I'm aparently not very bright today because I just wrote up an answer completely missing the part where you said the npapi plugin code was an example =] so, to answer the correct question, yes you can. The type in ActiveX that closest correlates to NPObject is IDispatch (or IDispatchEx). Rather than having a GetP...
7,721,383
7,721,420
On C/C++, basically what things are compiler-dependent?
What tasks, features, executions vary with compiler? I know this code is compiler-dependent- #include <stdio.h> #define PRODUCT(x)(x*x) int main() { int i=3,j,k; j=PRODUCT(i++); k=PRODUCT(++i); printf("\n%d %d",j,k); } Following gives garbage in some, while fixed values in others- #include <stdio.h> int main() { int i...
If you want the full list, you'll need to look to the standard document. In the C standard there are two types of 'compiler-dependent' issues defined: Implementation-defined behavior: The behavior may vary from compiler to compiler, but the compiler must provide some sort of consistent behavior, and must document this...
7,721,784
7,721,855
Convert/extract ints from a char array
I got a cstring, originating from a call from gzread. I know the data is blocks, and each block is consisting of an unsigned int, char, int and unsigned short int. So I was wondering what the standard way of splitting this cstring into the appropriate variables is. Say the first 4 bytes, is a unsigned int, the next byt...
If you pack the struct (read up on __packed__ attribute), you can rely on the order and that the members are non-aligned. Hence, you could read into a struct directly. However, I'm not sure about the portability of this solution. Otherwise, use pointer magic and casting like so: char *buffer; int a = *(reinterpret_cast...
7,721,923
7,722,128
calling QMetaObject::invokeMethod() with variable amount of parameters
I´m porting FitNesse´s Slim-server at the moment and I´m kinda stuck right now. What I´m getting are strings like these: ("id_4", "call", "id", "setNumerator", "20") ("id_5", "call", "id", "setSomethingElse", "10", "8") Where "setNumerator" and "setSomethingElse" are the names of methods that should be invoked and "20...
If you look at the function definition, you'll see there is just one version : bool QMetaObject::invokeMethod ( QObject * obj, const char * member, QGenericArgument val0 = QGenericArgument( 0 ), QGenericArgument val1 = QGenericArgument(), QGenericArgument val2 = QGenericArgument(), QGenericArgument val3 = QG...
7,722,004
7,725,602
Underlying mechanism in firing SQL Queries in Oracle
When we fire a SQL query like SELECT * FROM SOME_TABLE_NAME under ORACLE What exactly happens internally? Is there any parser at work? Is it in C/C++ ? Can any body please explain ? Thanks in advance to all.
Short answer is yes, of course there is a parser module inside Oracle that interprets the statement text. My understanding is that the bulk of Oracle's source code is in C. For general reference: Any SQL statement potentially goes through three steps when Oracle is asked to execute it. Often, control is returned to t...
7,722,021
7,722,079
Named int vs named float
From here I've got the mixed feelings that something is not right. Is it true that named int isn't lvalue but named float is?
The comment in the link says "integer, pointer and member pointer template parameters aren’t lvalues" (emphasis mine). It does not say that named integer variables are not lvalues - they are. If there were such a thing as floating-point template parameters, then they wouldn't be lvalues either; but named floating-point...
7,722,087
7,747,921
Getting the coordinates of points from a Boost Geometry polygon
I have a simple DLL doing some calculations with Boost Geometry polygons. (Mostly intersections and differences.) Since the DLL will be most likely called from C# code, and from Delphi and who knows from where else, I should convert the result into arrays that everything can handle. UPDATE: I had simplified and somewha...
I found a few things that needed to be fixed: One issue I see is in your templates. Be sure to put spaces! boost range works on containers or ranges that hold begin, end pairs Iterators represents something like a pointer to an object. Getting the size of the iterator will not do what you want. You need to either use ...
7,722,359
7,722,399
Pattern for storing multiple types of struct in a C++ std::<vector> container
I have a data structure which represents a train, which can be made up of many types of car, for example the train engines, a grain car, a passenger car, and so on: struct TrainCar { // ... Color color; std::string registration_number; unsigned long destination_id; } struct PowerCar : TrainCar { // ... ...
The standard solution to this is called double-dispatch. Basically, you first wrap your algorithms in separate functions that are overloaded for each type of car: void routeCar(PowerCar *); void routeCar(CargoCar *); Then, you add a route method to car that is pure virtual in the base-class, and implemented in each of...
7,722,836
7,841,555
Can I use $1 in regex_replace?
From reading the FCD for regex_replace (28.11.4) I can only guess that the function can also use parts of the original string for replacing? I can not test it with my gcc, is this correct? using namespace std; regex rx{ R"((\d+)-(\d+))" }; // regex: (\d+)-(\d+) cout << regex_replace("123-456", rx, "b: $2, a:$1"); // "b...
Table 139 in the C++ 2011 FDIS lists two constants that can be used to affect the rules used for the format string in regex_replace, format_default and format_sed. format_default is described as using "the rules used by the ECMAScript replace function in ECMA-262, part 15.5.4.11 String.prototype.replace." This standard...
7,722,972
7,723,048
Invalidating deleted pointers?
template<typename T> someclass<T>& operator=(const someclass<T>& other) { typename std::vector<T *>::const_iterator rhs; typename std::vector<T *>::iterator lhs; //identity test //this->data is std::vector<T *> for(lhs = this->data.begin(); lhs != this->data.end(); lhs++) { delete *lhs...
The solution to this problem is to write code that does not contain any deletes. Use shared_ptr where possible. When you have a container that owns polymorphic objects, you can also use Pointer Container.
7,723,626
7,724,475
Need to determine a matrix to align two triangles
I need to determine a matrix representing the transform required to align two known-to-be-congruent triangles in 3D. I've previously tried asking about taking a different approach but I've been hitting a lot of snags with it so I'm now looking at trying different ideas. Is anyone able to direct me to how I can just cr...
1st. think of a "basic" triangle. XYZ when X = (0,0,0), Y = (1,0,0) and Z where ever, depending on the angles. 2nd. for each triangle find the way to move it to this "basic". for DEF it's, move D to A using basic move action. rotate around z until E is in xz plan, rotate around x until F is in xy plan in the x+ side. i...
7,723,794
7,724,050
How to concatenate strings in the function m_stream in C++?
I'm writing a logger for my program in C++. I have this piece of code: void Log::Write(char* logline) { time_t rawtime; struct tm * timeinfo; time ( &rawtime ); timeinfo = localtime ( &rawtime ); m_stream << asctime (timeinfo) << logline << endl; } This is a log Tue Oct 11 13:07:28 2011 I want a d...
Your problem is asctime(): http://www.cplusplus.com/reference/clibrary/ctime/asctime/ The string is followed by a new-line character ('\n') and the terminating null-character. As the returned string is a C string, you could replace the \n with a \0: char * str = asctime(timeinfo); str[strlen(str) - 1] = '\0'; AS long...
7,723,887
7,723,956
Inline struct declaration
I was interested to note that C++ (VSVC++ 2008 specifically) lets me declare a struct inline in a method. e.g: MyClass::method() { struct test{ int x;}; test t = {99}; } My question is, how does this declaration work internally, and specifically does it have any negative performance implications?
how does this declaration work internally? Exactly like a declaration at namespace scope, except that the name is only visible within the scope of the block it's declared in (in this case, the function body). UPDATE: as @Nawaz points out, there are one or two extra restrictions that apply to local classes: they canno...
7,723,983
7,727,662
MFC LoadStringW Is not not loading Japanese string properly from the string table
In my MFC application, character set is set to "Multi-byte", I am trying to load a Japanese string stored in string table using LoadStringW function to load the string from the string table but it always reads junk characters. Do you see any problem in my approach? I don't want to change character set to Unicode. One ...
Make sure you save the resource file utf-16 format, not ANSI. Visual Studio can handle those files just fine. To save it like that, open the file in Visual Studio as text. Then in the file menu, choose Advanced Save Options and then in the dialog specify Unicode - Codepage 1200. Then save the file again. After that, yo...
7,724,000
7,899,387
How to hide/collapse main menu in a win32/mfc application
I always been interested on how we can accomplish this (hide/show the main menu using the alt key), and now some applications do this very often. One that really please me is the visual studio 2010 with this plugin: http://visualstudiogallery.msdn.microsoft.com/bdbcffca-32a6-4034-8e89-c31b86ad4813?SRC=VSIDE (firefox al...
The SetMenu function lets you add/remove the menu from the window. It does not destroy the menu. Note that most applications which have the dynamic menu hide/show behavior are not really showing a menu. They're showing a custom control that looks like a menu.
7,724,369
7,724,387
omitting else keyword
Is there any real difference between these two methods? Method 1: bool IsNumOverFive(int num) { if(num > 5) { return true; } else { return false; } } Method 2: bool IsNumOverFive(int num) { if(num > 5) { return true; } return false; }
As far as the computer is concerned, there is no difference between the two versions. Given that both are correct, what's important is that whoever is reading the code finds it easy to read. I happen to prefer a third version: bool IsNumOverFive(int num) { return (num > 5); } Others may have different preferences....
7,724,370
7,724,400
Virtual templates members of class workaround
Let's say that I want to implement some classes for containers. All of them should implement such functions like insert, remove etc. So I write some interface: template <class T> class ContainerInterface { public: virtual void insert(T element) = 0; template<class Predicate> virtual void remove(Predicate p) =...
You can use type erasure with function objects. But luckily, the appropriate facilities already exist! For example, in your case, you could use boost::function<bool(const T&)> or std::function<bool(const T&)> (with TR1/C++11 support) as your predicate type! virtual void remove(std::function<bool(const T&)> p);
7,724,448
33,799,784
Simple JSON string escape for C++?
I'm having a very simple program that outputs simple JSON string that I manually concatenate together and output through the std::cout stream (the output really is that simple) but I have strings that could contain double-quotes, curly-braces and other characters that could break the JSON string. So I need a library (o...
Caveat Whatever solution you take, keep in mind that the JSON standard requires that you escape all control characters. This seems to be a common misconception. Many developers get that wrong. All control characters means everything from '\x00' to '\x1f', not just those with a short representation such as '\x0a' (also ...
7,724,569
7,725,055
Debug vs Release in CMake
In a GCC compiled project, How do I run CMake for each target type (debug/release)? How do I specify debug and release C/C++ flags using CMake? How do I express that the main executable will be compiled with g++ and one nested library with gcc?
With CMake, it's generally recommended to do an "out of source" build. Create your CMakeLists.txt in the root of your project. Then from the root of your project: mkdir Release cd Release cmake -DCMAKE_BUILD_TYPE=Release .. make And for Debug (again from the root of your project): mkdir Debug cd Debug cmake -DCMAKE_BU...
7,724,669
7,727,412
where to declare constructor of class in visual studio 2010 winforms project c++?
I need to call methods of class by pressing buttons, but I don't want to create new object every time. Besides, class creates list, so I do not want to create list again.
If your ArrayList will be used only inside the form class, make it a member of the class and initialize it in the form constructor: public: Form1(void) { InitializeComponent(); myList = gcnew ArrayList(); } protected: ArrayList^ myList; As Konrad has pointed out, using Generics is pref...
7,725,095
7,730,622
OpenCV getMinFilter_GPU
The getMinFilter method takes (int,int,cvSize), how is OpenCv expecting me to pass a 2D image in an int? srcType – Input image type. Only CV_8UC1 and CV_8UC4 are supported. dstType – Output image type. It supports only the same type as the source type. gpu::getMinFilter_GPU(int srcType, int dstType, const Size& ksize, ...
Actually getMinFilter_GPU function does not do any any filtering. It just returns a special "processor" object which is able to do filtering. Convenient way to use gpu filtering functions in OpenCV is: Create a filter object (returned by getMinFilter_GPU and many other functions); Create an engine object (for example ...
7,725,139
7,725,351
priority_queue, iterator and ordering
Consider a std::priority_queue where N elements have the same priority. Now consider some pop()s and push()s of elements with any priority, so that the resulting queue consists of all those N elements mentioned above plus M new elements, where all the N+M elements have the same priority. Does a following pop() guarante...
I don't think there is any such guarantee. According to to sgi's docs, it depends on the underlying data structure. I think most common implementations use a heap. Pushing and popping any item on a heap simply updates the elements in it in such a way that there is no node where its children are larger than the parent...
7,725,467
7,725,611
C++ Templates variadic but static
I am training my template skills in C++ and want to implement a vector class. The class is defined by the vector dimension N and the type T. Now I would like to have a constructor that takes exactly N variables of type T. However I can't get my head around how to tell the variadic template to only accept N parameters. ...
A variadic constructor seems appropriate: template<typename T, int Size> struct vector { template<typename... U> explicit vector(U&&... u) : data {{ std::forward<U>(u)... }} { static_assert( sizeof...(U) == Size, "Wrong number of arguments provided" ); } T data[Size]; }; This e...
7,725,584
7,725,752
qFastSin and qFastCos (Speed, safety and precision)
Recently I found two mathematical functions in qmath.h named qFastSin and qFastCos. These functions are inline and uses look-up tables to calculate the value of sin and cos: inline qreal qFastSin(qreal x) { // Calculating si would be more accurate with qRound, but slower. int si = int(x * (0.5 * QT_SINE_TABLE_S...
They are not part of the public API, not supported, not documented, and subject to change. Qt only documents what it supports and it only supports what it documents. It's good like that. It looks like a simple linear interpolation so accuracy depends on QT_SINE_TABLE_SIZE and also how close to a sample point the input ...
7,725,812
7,726,354
In the context of file-handling in C++ console application; max characters displayability without horizontal scrolling?
My professor today was teaching us File handling in C++. He made a very simple program which would read two lines from a text file and display those on the screen using fin.getline() function. He chose the size of the array which was storing the read line to be of 80 characters. He then proceeded to explain that it MUS...
I think you can conclude that your professor hasn't worked on a computer since the late 1980's/early 1990's, at least. A very long time ago (when I was learning C), lines of the screen were 80 characters (because punch cards were 80 characters); it was a hardware constraint, and there was nothing you could do about it...
7,725,821
7,725,867
Using boost::shared_ptr with WSACleanup
I would like to use a boost::shared_ptr in order for WSACleanup() to be called when my function goes out of scope, like this: void DoSomething() { WSAStartup(...); boost::shared_ptr<void> WSACleaner(static_cast<void*>(0), WSACleanup); } This does not compile, Error 1 error C2197: 'int (__stdcall *)(void)' :...
From the docs: "The expression d(p) must be well-formed" (i.e. WSACleanup(static_cast<void*>(0) must be well-formed.) One possible solution: boost::shared_ptr<void> WSACleaner(static_cast<void*>(0), [](void* dummy){WSACleanup();});
7,726,213
7,726,341
Partial template specialization - passing types as arguments?
I'm a trying to write a wrapper around calls of the form typeid()==typeid() to prevent passing pointers / pointer types as arguments (an error easily made and difficult to detect). So where now the call would be typeid(ClassA)==typeid(arg), I would like to replace it with safesametype(ClassA, arg) or something similar....
Just swap the template parameters. template <class TestType, class ArgType> bool instanceof(const ArgType& object) { // checks here return typeid(TestType) == typeid(object); } Call as: instanceof<ClassA>(arg)
7,726,329
7,726,393
What is the purpose of const pointer to void
Do you find it strange that pthread_setspecific needs const void pointer but pthread_getspecific returns non-const void pointer? void *pthread_getspecific(pthread_key_t key); int pthread_setspecific(pthread_key_t key, const void *value); The link.
Meh, just another const-unsafe C interface. In truth, though, it's quite impossible to create a const-safe version of this. If both functions are consistent, then either people who want to store pointers-to-const must cast away const when storing the pointer, or people who want to store pointers-to-non-const must cast ...
7,726,345
7,726,464
Valgrind doesn't detect any memory leaks. How safe is that?
I have run my code through valgrind with these results: ==4492== Memcheck, a memory error detector ==4492== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al. ==4492== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info ==4492== Command: ./mem ==4492== Parent PID: 4455 ==4492== ...
You need to distinguish between memory leaks (memory that was allocated, but you lost all references to) and memory hogs (memory that was allocated, that you keep references to, but forgot to deallocate). The later one can not be detected by valgrind, since valgrind doesn't know you did not want to use it anymore. To ...
7,726,384
7,726,461
variables vs long algorithms
what are the differences between using these two algorithms. I've always wondered how I should be optimising things.How do they differ memory and speed wise? Is one better than the other? Aside from code clarity I mean. this is the first version I had: bool Intersects(BoundingSphere boundingSphere) { D3DXVECTOR3 v...
The two algorithms will, under proper optimization options, compile down to exactly the same code. Since the first is far more readable, it is undoubtedly the better of the two. The correct way to optimize this code is not to get rid of the variables (the compiler can do that for you), but to get rid of the sqrt operat...
7,726,386
7,726,435
How to easily time a block of C# code?
I need a simple way (and compact if possible) to execute a block of C# while counting time. Something similar to this C++ code: elapsed = time_call([&] { for_each (a.begin(), a.end(), [&](int n) { results1.push_back(make_tuple(n, fibonacci(n))); }); }); where time_call is: // Calls the p...
TimeSpan TimeAction(Action blockingAction) { Stopwatch stopWatch = System.Diagnostics.Stopwatch.StartNew(); blockingAction(); stopWatch.Stop(); return stopWatch.Elapsed; } Usage: var elapsed = TimeAction(() => { //Code to time }); Based on your sample code (and usage of GetTickCount) ...
7,726,455
7,726,519
Clearing an std::vector needs an assignment operator. Why?
In my application I need to store a small collection of temporary data. In this temporary data I want to store a reference to another class and since it can't be a nullptr, I use a reference. Is use a vector to store the data (I don't have too much data so vector is fine). Filling the vector, and iterating over it wor...
Any class put in a vector requires a copy assignment operator (or at least a move assignment operator in C++11). It's just a quality of implementation issue when you actually get the error.
7,726,762
7,726,897
Finding all occurrences of a character in a string
I have comma delimited strings I need to pull values from. The problem is these strings will never be a fixed size. So I decided to iterate through the groups of commas and read what is in between. In order to do that I made a function that returns every occurrence's position in a sample string. Is this a smart way to...
vector<int> findLocation(string sample, char findIt) { vector<int> characterLocations; for(int i =0; i < sample.size(); i++) if(sample[i] == findIt) characterLocations.push_back(sample[i]); return characterLocations; } As currently written, this will simply return a vector containing t...
7,726,777
7,726,972
Extending 'isalnum' to recognize UTF-8 umlaut
I wrote a function which extends isalnum to recognize UTF-8 coded umlaut. Is there maybe a more elegant way to solve this issue? The code is as follows: bool isalnumlaut(const char character) { int cr = (int) (unsigned char) character; if (isalnum(character) || cr == 195 // UTF-8 || cr =...
Your code doesn't do what you're claiming. The utf-8 representation of Ä is two bytes - 0xC3,0x84. A lone byte with a value above 0x7F is meaningless in utf-8. Some general suggestions: Unicode is large. Consider using a library that has already handled the issues you're seeing, such as ICU. It doesn't often make se...
7,726,788
7,728,037
double(?) definition of template member operators
if I look into < complex> header from msvc 2008, I find that each operator definition is doubled with _Other type template operation, like for example _Myt& operator+=(const _Myt& _Right) { // add other complex this->_Add(_Right); return (*this); } template<class _Other> inline _Myt& operator+=(const complex<_O...
The first case also catches a right-hand-side that's convertible to _Myt. class MyComplex { // ... public: operator std::complex<double>() const; operator std::complex<float>() const; }; std::complex<double> i; i += MyComplex(1,1); // Unambiguously uses the first form.
7,726,864
7,948,726
tbb: parallel find first element
I have got this problem: Find the first element in a list, for which a given condition holds. Unfortunately, the list is quite long (100.000 elements), and evaluation the condition for each element takes in total about 30 seconds using one single Thread. Is there a way to cleanly parallelize this problem? I have lo...
ok, I have done it this way: Put all elements into a tbb::concurrent_bounded_queue<Element> elements. Create an empty tbb::concurrent_vector<Element> results. Create a boost::thread_group, and create several threads that run this logic: logic to run in parallel: Element e; while (results.empty() && elements.try_pop(e...
7,727,015
7,727,471
Translate and explain some C++ bit operations to C#
Can you help me with the translation to c# of this 3rd part API method: I also didnt understand everything that is happening at the bit operations.. inline void SetBits(unsigned long& aValue,unsigned int aData,unsigned int aPosition,unsigned int aLength) { unsigned int datamask; // data mask, before aPosition shi...
As an example to explain the code (in 8-bit, for the sake of simplicity), lets say aValue = 01101001, aData = 00100110, aPosition = 3 and aLength = 4: datamask = (1L << aLength) - 1; creates a mask with the aLength (4) rightmost bits set to one: datamask = 00001111. aValue &= ~(datamask << aPosition); clears the aLen...
7,727,261
7,727,297
Locking a mutex vs accessing disk
Which is generally more efficient between locking a mutex and doing disk reads in C++? If it depends on the system I'm running, what's a good way to check this? Would doing 1 million locks vs 1 million disk reads work?
Generally, the mutex operations would be far faster than disk reads. That's because their intended purpose requires maximum speed. In fact, I would hazard to suggest that any memory operation is likely to be faster than a disk one. Of course, there may be bizarre edge cases where the disk information is cached in memor...
7,727,462
7,727,522
CppUnit, very simple test code crashed, why?
I am learning CppUnit, and my code coredumped when calling TestRunner::run(). That's line 34 in the below code. I can not see anything wrong. It is almost identical to the sample code in the CppUnit cookbook. #include <iostream> #include <cppunit/TestCaller.h> #include <cppunit/TestSuite.h> #include <cppunit/ui/t...
Given that the signature for the function is: CppUnit::TestSuite * MyFixture::CreateSuite() shouldn't you be returning something (suite would be my first guess)? By not returning anything, the line: runner.addTest(MyFixture::CreateSuite()); is going to add a very dodgy pointer to your runner. And the reason you're p...
7,727,588
7,727,648
Is it possible to save the current viewport and then re draw the saved viewport in OpenGL and C++ during the next draw cycle?
I want to know if I can save a bitmap of the current viewport in memory and then on the next draw cycle simply draw that memory to the viewport? I'm plotting a lot of data points as a 2D scatter plot in a 256x256 area of the screen and I could in theory re render the entire plot each frame but in my case it would requ...
What you can do is render the scene into a texture and then first draw this texture (using a textured full-screen quad) before drawing the additional points. Using FBOs you can directly render into a texture without any data copies. If these are not supported, you can copy the current framebuffer (after drawing, of cou...
7,727,605
7,727,903
compiler optimisation
I just learned that the compiler cleverly replaces calls to functions and variables by essentially replacing them with the code they represent. With this in mind would the second method in fact be better below (due to clarity) and in fact run just as fast as the first one? //check to see if sphere intersects the box bo...
First of all, this is not an accurate sphere vs. box check. It's essentially a broken (it won't report an intersection when the sphere center is contained in the box!) box vs. box-around-a-sphere test . Look for Arvo's algorithm if you want to do this right. But back to your question: if there's measurable speed differ...
7,727,656
7,728,147
QGraphicsPolygonItem drawing a open(not closed) polygon
I am using a QGraphicsPolygonItem and I have noticed that it always connects the end-point with the start-point. I know that the polygon terms means exactly that, and what I am looking for is "polyline" or "polygonal chain". I didnt found nothing like that in QGraphicsItem subclasses. How do I draw a polygonal chain in...
You can use QPainterPath and use lineTo method to input yors polyline points, then just use QGraphicsPathItem to make it graphics item. Alternatively you also might think about combining several QGraphicsLineItem into one QGraphicsItemGroup, but that's more difficult as you need to pay attention to aligning lines toget...
7,727,754
7,731,553
How do I enumerate resolutions supported via TWAIN
I have to enumerate DPI's supported by scanner via TWAIN interface. // after Acquire is called... TW_CAPABILITY twCap; GetCapability(twCap, ICAP_XRESOLUTION) if (twCap.ConType == TWON_ENUMERATION) { pTW_ENUMERATION en = (pTW_ENUMERATION) GlobalLock(twCap.hContainer); for(int i = 0; i < en->NumItems; i++) { ...
The code you shown takes just the lower byte of the resolutions, and then converts it to integer (the pointer points to chars, so the line fetch just a char and then converts it to integer). You must specify that the pointer points to TW_UNIT32 values BEFORE reading the value. The number 44 for instance, is the lower b...
7,727,758
7,728,115
find overlapping rectangles algorithm
let's say I have a huge set of non-overlapping rectangle with integer coordinates, who are fixed once and for all I have another rectangle A with integer coordinates whose coordinates are moving (but you can assume that its size is constant) What is the most efficient way to find which rectangles are intersecting (or i...
Personally, I would solve this with a KD-Tree or a BIH-Tree. They are both adaptive spatial data structures that have a log(n) search time. I have an implementation of both for my Ray Tracer, and they scream. -- UPDATE -- Store all of your fixed rectangles in the KD-Tree. When you are testing intersections, iterate thr...
7,727,921
7,727,945
File redirection not working if I SetCurrentDirectory to C:\Program Files in 32 bit app on Win7 64 bit, should it not navigate to (x86) folder?
Here is my test code below. //This correctly prints C:\Program Files from 64 app on 64 bit Win7 and //C:\Program Files (x86) 32 bit app on 64 bit Win7 system("echo %PROGRAMFILES%\n"); BOOL ret = SetCurrentDirectory("C:\\Program Files\\"); char szFolder[512] = {0}; GetCurrentDirectory(512, szFolder); //folder is prin...
This is quite simple. The Program Files directory is not subject to file redirection. You probably would be best using the CSIDL_PROGRAM_FILES and CSIDL_PROGRAM_FILESX86 CSIDL values but you'll have to work out for yourself whether you need the x64 or x86 folders.
7,728,231
7,731,390
Notifying parent process to resume working
I'm creating a child process and loading a 3rd-party program. After loading, the child process is doing some IO operations that I have no control on. In a perfect world, the child process would finish his magic-IO-mambo-jumbo and the parent process will initialize a unit that depends on a successful magic. How can I ma...
You're looking for some kind of interprocess communication. This is going to be os-specific, although there are more compatible wrappers like boost.interprocess. In particular, you're going to want some sort of synchronization mechanism: http://www.boost.org/doc/libs/1_47_0/doc/html/interprocess/synchronization_mecha...
7,728,297
7,728,353
operator function in C++ and compile error relating to it
there are probably several ways I will expose my ignorance with this question :) First, I think this is C++ code, but the extension of the file is .C (so maybe it is C?) Anyway, I am trying to compile a program called Sundance (Sentence UNDerstanding ANd Concept Extraction) which is a Natural Language Processing tool. ...
That compiles fine for me. You are on a 64-bit machine, where size_t is larger than int. Explanation: you can historically convert a pointer an int struct Foo {}; int main () { Foo * f = new Foo (); std :: cout << (int)f; // Prints 43252435 or whatever } If you want an integer which is the same size as a poin...
7,728,356
7,728,581
How to check if map could be created, if I don't use exceptions?
I want to use map in C++, but I don't use exceptions. After using map<int, int> my_map in a function, how can I check if it managed to allocate memory internally (I understand that with exceptions any new inside that can't allocate memory will throw an exception)?
Whether or not you use exceptions, the standard containers will (if they are using their default allocators) throw std::bad_alloc if a memory allocation fails. If you don't catch this, then your program will terminate - so there is no way to check for success without catching the exception in this case. If you really w...
7,728,405
7,728,779
How can I declare a friend function in a namespace that takes an inner class as a parameter?
Consider this code: namespace foo {} class A { class B { }; friend int foo::bar( B& ); }; namespace foo { int bar( A::B& ) { } } G++ 4.4.3 tells me: friendfun-innerclass.cpp:21: error: 'int foo::bar(A::B&)' should have been declared inside 'foo' But I can't declare: namespace foo { int b...
Can't be done the way you want to, because you would have to forward declare a nested class (which you can't) in order to provide a prototype for foo::bar. As a first attempt to get around this problem, I would probably resort to making foo::bar a function template. That way the compiler will resolve the types after A...
7,728,478
7,728,728
c++ template class; function with arbitrary container type, how to define it?
Okay, simple template question. Say I define my template class something like this: template<typename T> class foo { public: foo(T const& first, T const& second) : first(first), second(second) {} template<typename C> void bar(C& container, T const& baz) { //... } private: T first; T sec...
Traits solution. Generalize not more than needed, and not less. In some cases that solution might not be enough as it will match any template with such signature (e.g. shared_ptr), in which case you could make use of type_traits, very much like duck-typing (templates are duck typed in general). #include <type_traits> ...
7,728,680
7,728,770
C++ Function with one input and one output not getting input
its function subtotalspool. It says i cant use it as a function somewere inside int main and it says in function subtotalspool that the varriable spoolnumber wasnt declared. I put "int spoolnumber" in the function declaration for subtotalspool. is there something im missing? EDIT for code change /**********************...
Your variable spoolnumber is only defined on the scope of the function main. You either need to call spoolnum() in your subtotalspool() function, or pass that variable into the function to operate on it appropriately. EDIT To pass a variable to a function, you need to change its signature. For instance, int subtotalspo...
7,728,737
7,728,846
Derived class in C++
I have a homework problem that asks: Desgin a derived class GraduateStudent from base class Student. It adds a data member named Advisor to store the name of student’s thesis advisor. Provide constructor, destructor, accessor, and modifier functions. This class overrides the year function to returns one of two strin...
The student class you were "given" is not really written correctly to properly allow for overriding of the year function. A general use case scenario (where you hold student objects in a container won't work properly). So, to fix (properly): // Generally, poor practice to have a using namespace // directive in a heade...
7,728,878
9,070,500
Project dependency in Eclipse CDT
I'm using eclipse for the first time. I'm a seasoned VisualStudio user, so I'm trying to find similar functionality in eclipse. I have two projects, A and B. Project A spits out libA.a when it's done compiling. Project B links against libA.a. Here is my problem. I compile project A then project B, everything is fine. ...
One can work around this problem by using the touch command. In Eclipse, as part of C/C++ Build/Settings is the tab 'Build Steps'. In the pre-build steps command line, enter touch filename. filename is any file in your application. This could be the file with main(). This could be a special file just for this workaroun...
7,729,162
7,729,230
Conversion of float numbers to a formatted string
I'm trying to convert a double number to a std::string, the conversion should print either in the decimal format with 2 decimal digits or in the exponential form: 1 -> 1.00 0.1 -> 0.10 0.01 -> 0.01 0.015 -> 1.5e-2 10 -> 10.00 100 -> 100.00 15000 -> 1.5e4 I tried to use the boost::format function with the %g type, but...
Choose scientific or fixed depending on the size of the number. It's that easy. Cheers & hth.,
7,729,211
7,729,525
Creating 3D Models for a Game using Blender and Bloom Effect in Graphics
I am creating a game that requires heavy use of 3D Models. I started using Blender for creating models. Here are some models which I came across while developing a model I need to create a model of a Cube with Horizontal Grooves/Depressions and impart glow to those Grooves. I went through a blender tutorial which des...
I can only try to help you with your second question, since I'm not experienced with blender. A Bloom effect is a graphical effect to visualize strong light sources. It is often implemented as a shader. The wikipedia article is actually quite interesting. You should be able to find tons of tutorials for both OpenGL and...
7,729,290
7,731,380
Netbeans Remote C++ Development "No rule to make target" Error
When creating a simple Remote C++ Development application in Netbeans, I get the following error: gmake[2]: Entering directory '/path/to/project' gmake[2]: *** No rule to make target '/path/to/project/cpp/file' gmake[2]: Leaving directory '/path/to/project' BUILD FAILED (exit value 2, total time: 1s) To reproduce thi...
The problem is, I was using absolute paths for my project. Lesson learned, when developing remote projects using Netbeans, you can not use absolute paths unless the locations of the projects on both machines match exactly. To configure Netbeans to use relative paths, click the "Tools" option in the menu bar and select ...
7,729,646
7,729,819
using struct keyword in variable declaration in C++
I have a feeling this may be related to C syntax, but I started my programming life with C++ so I am not sure. Basically I have seen this: struct tm t; memset( &t, 0, sizeof(struct tm) ); I am a bit confused with this syntax, as normally I would expect the above to instead look like this: tm t; memset( &t, 0, sizeof(t...
The simple answer is that the struct keyword there is present to restrict the lookup of the identifier tm to only user defined class types. It is probably left for compatibility with C, where it is required. Contrary to what others say, there is no such thing as auto-typedef, nor do C and C++ differ with respect to how...
7,729,686
7,730,134
Convert GetTickCount() vxWorks to Linux
I am porting some vxWorks code to Linux. I looked at this answer and it recommends CLOCK_MONOTONIC. Is that a suitable replacement for the following define: #define GetTickCount() ((1000.0 * (double)tickGet())/((double)sysClkRateGet()))) ?
GetTickCount is a windows API described thus: Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days Yes, CLOCK_MONOTONIC is the correct POSIX clock to use. Here is untested code for you: double GetTickCount(void) { struct timespec now; if (clock_gettime(CLOCK_MONOT...
7,729,693
7,729,884
Save/Open Common Dialog boxes in win32 without MFC
How do you create the deafault Save/Open dialog boxes using pure unmanaged Win32 API ? Following the guide here, the following code is executed when WM_CREATE message is handled in the message loop of the main window: Ive included <Commdlg.h> also. OPENFILENAMEA ofn; char Buffer[300]; fill(...
the following code is executed when WM_CREATE message is handled Look in the Output window and observe the first-chance exception notification for 0xc0000005, an AccessViolation exception. There's a backstop in the Wow64 emulator that swallows exceptions while WM_CREATE is being dispatched. The exception is caused b...
7,729,725
7,729,869
How can you tell (programmatically) if large fonts are in use on a Windows 7 PC
I need to identify whether or not large fonts are in use on Windows 7 from within an app written in C++. Any assistance would be appreciated.
In MFC: void CTestFontDlg::OnBnClickedButton1() { CDC* pDC = GetDC(); int nRes = GetDeviceCaps(*pDC, LOGPIXELSY); } Normal font size = 96 (100%), medium (125%)= 120...
7,730,076
7,730,174
variables as opposed to class calls
I have recently learned that if you have a reference to a class as a function parameter, it is better practice and more efficient to store certain needed pieces of information as local variables rather than accessing the classes members every time you need them in the function. so... void function(const Sphere& s) { ...
Whoever told you this probably thought that the second version was likely to be faster. I think this is bad advice, for two reasons: It may or may not actually be faster. This depends on the compiler, on what exactly the code is doing etc. Even if it is faster, this screams premature optimization. One should micro-opt...
7,730,077
7,730,109
c++ vector; remove_if only removing a single value?
I'm supposed to implement a function that erases a range of values from containers. So eraseRange(v, 1.5, 24); for example would delete any value greater than 1.5 and less than 24 from the container v. And my function works perfectly for lists, where I use: container.erase(remove_if(container.begin(), container.end()...
There are several overloads of erase. One overload, the one you are using, takes a single iterator and erases the element pointed to by the iterator. The other overload, which you should be using, takes a range (a pair of iterators) and erases all of the elements in the range: c.erase(remove_if(c.begin(), c.end(), rg),...
7,730,088
7,730,171
C++ setw moving whole line not just the needed part
I am trying to use setw to clean up the output of my program. I want the empty spaces in between "total number of spools to be ordered" and the output. EDIT this is what im going for: and this is what I get here is what I have so far: UPDATED CODE /********************************************/ // Name: results ...
You can also do cout << left << setw (45) << "Total number of spools to be ordered is: " << spoolnumber << endl << endl; to choose which side the padding goes. The default is left. EDIT: using stringstream stringstream ss; ss << "$" << spoolnumber I think you can fix the right end by adding another setw. So: cout <...
7,730,211
7,730,244
C++ class method, returns vector<subclass>
I'm having a bit of trouble with a method I'm trying to write for a class. I have class symbol and class terminal. class terminal extends class symbol, but one of the methods of class symbol needs to return a vector. E.g.: #ifndef SYMBOL_H #define SYMBOL_H #include "terminal.h" #include <vector> using namespace st...
Avoid circular dependencies by using Forward Declarations. class terminal; class symbol { std::vector<terminal> first(); // ... }; There is a speculation of this approach being Undefined as per C++ standard. @Ben Voight points out: C++03 standard Section 17.6.4.8 says: "In particular, the effects are undefined...
7,730,502
7,730,517
Will main() catch exceptions thrown from threads?
I have a pretty large application that dynamically loads shared objects and executes code in the shared object. As a precaution, I put a try/catch around almost everything in main. I created a catch for 3 things: myException (an in house exception), std::exception, and ... (catch all exceptions). As part of the shared ...
Will main() catch exceptions thrown from threads? No When a thread throws an exception, it is not caught by main. Is this the standard behavior? Yes, this is standard behaviour. To catch an exception originating in thread X, you have to have the try-catch clause in thread X (for example, around everything in the th...
7,730,540
7,730,595
C++ Design (behavior in base class, private member supplied in derived class)
I have 6 classes which all perform the same actions. I would like to move common behavior to a common [base] class. There are actions to be performed on 6 separate objects. The six objects are located in derived classes. Intuitively, the private member objects would be accessed through the child (derived class) in the ...
If they are introduced in the derived classes, then the base class cannot directly access them. How would the base class know that all derived classes have a specific member? You could use virtual protected methods like so: class my_base { protected: virtual int get_whatever(); virtual double get_whatever2(); p...
7,730,697
7,730,972
What is a platform independent way of getting unique value of current instance (e.g. pid) in C++
I would like to get a some kind (doesn't matter whether it's a process id or anything) of a unique integer value of current instance in C++ in a platform independent manner (that means no #if #else macro switch). time based value would not be reliable since two instances can start at the same time. Is there any way of...
Long story short, the answer is no, not without using platform-specific functionality. [C++03] The C++ language itself does not provide any mechanism to do this. In fact, C++ itself knows nothing about processes or interprocess communication. Without using platform-specific functionality -- either hand-rolled by you,...
7,730,874
7,731,106
In the declaration "std::vector<X> f();", is "std::vector<X>" an instantiation?
The C++ Language Standard states the following concerning template components in the Standard Library: The effects are undefined...if an incomplete type is used as a template argument when instantiating a template component, unless specifically allowed for that component (C++11 §17.6.4.8/2). Does the following cause ...
§ 14.7.1\1 Implicit instantiation [temp.inst] Unless a class template specialization has been explicitly instantiated (14.7.2) or explicitly specialized (14.7.3), the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined...
7,730,960
7,731,346
Tree Construction with pointers
I'm trying to create a function that inserts a key struct into a tree. The function sets the root correctly, but does not set the branches when called again with another key. Here is the code: tree.h: class tree{ key *tree_root; public: tree(); //Constructor void treedestroy(key *root); //Tree d...
I'm not entirely sure about your approach here, but to help get you on your feet, it would help to use a function signature of: void insert(key*& root, key *newkey, int disc); This passes the root pointer by reference, which means that changes made inside the function will "stick" to the variable you passed in. Your f...
7,731,002
7,733,858
Remove module of library from linking
I have made lib in Visual Studio. Lib have two modules: A.cpp and B.cpp. In separate project i link to this library but i want to disable one of modules of this lib i.e B.cpp.
You may not have to split up your lib. The necessary contents of lib is only linked in if there are unresolved symbols remaining from your executable (exe/dll). Unnecessary contents is generally speaking not linked in. For example: suppose your lib contains 2 obj-files ,a.obj from a.cpp and b.obj from b.cpp. a.cpp con...