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,402,504
7,404,143
Multisampled render to texture in ios
I am attempting to render to a texture in ios with multisampling enabled and then use that texture in my final output. Is this possible? So far I have only gotten black textures or aliased images. The code I am using is: glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D...
Yes! I found what I was doing wrong. I wrongly thought that I could have the following: Framebuffer Multisampled colour render buffer attached to a texture Multisampled depth buffer But you cannot do this. D: You have to have the following: Multisampled framebuffer: Multisampled colour render buffer (Not attached to...
7,402,576
7,413,516
Get current working directory in a Qt application
I'm writing a program in C++ using the Qt library. There is a symbolic link in my home bin directory to the executable. I would like the current working directory of my program to be the directory in which I am with my terminal (ie. the result of the pwd command). I saw the QDir::currentPath() function, but it gives ba...
Thank you RedX and Kaz for your answers. I don't get why by me it gives the path of the exe. I found an other way to do it : QString pwd(""); char * PWD; PWD = getenv ("PWD"); pwd.append(PWD); cout << "Working directory : " << pwd << flush; It is less elegant than a single line... but it works for me.
7,402,720
7,403,258
Alternative to sqlite3_get_table
I have a function called isadded() and it was the cause of my program crashing. I run debugdiag and found this Function Arg 1 Arg 2 Arg 3 Source ntdll!RtlpWaitOnCriticalSection+df 00001484 00000002 00000000 ntdll!RtlEnterCriticalSection+a8 09e10c08 006310a5 09e10c08 sqlit...
You use a handful of commands to replace sqlite3_get_table. Here is the basic c/c++ intro tutorial that explains the process. You have to do more work, but there is much more control. Each one is very well documented in the function section of the sqlite3 reference. Update: As an alternative, you can use sqlite3_exec...
7,402,972
7,403,043
is it possible to have multiple classes inside php extension?
I would like to wrapp a .cc code that contains multiple public classes. Is it possible to do that ? how? Do I need to use multiple .cc files one for each class that i want to wrapp? THX
You want to call a C++ class from php? This is incredibly difficult. Usually you have to write a php module (a lot of work). Alternatively you could take a look at Thrift which would let you call your C++ code as a network service (sounds hard, but trust me it's easier than writing a php module).
7,403,210
7,403,423
Hashing floating point values
Recently, I was curious how hash algorithms for floating points worked, so I looked at the source code for boost::hash_value. It turns out to be fairly complicated. The actual implementation loops over each digit in the radix and accumulates a hash value. Compared to the integer hash functions, it's much more involv...
Why are you wanting to hash floating point values? For the same reason that comparing floating point values for equality has a number of pitfalls, hashing them can have similar (negative) consequences. However given that you really do want to do this, I suspect that the boost algorithm is complicated because when you t...
7,403,227
7,403,797
Where can I find information about C++/STL method Exception guarantees?
I was writing code with exception handling the other day, and I had a few questions about exceptions, their guarantees and throwables. Basically, say you have: class X { string m_str; X() : m_str("foo")//what if this throws? { ifstream b("a.in")//what if this throws? } And after running through all the articles I ...
If either of these throw class X { string m_str; X() : m_str("foo")//what if this throws? { ifstream b("a.in")//what if this throws? } Then the object you were creating will not exist. If an exception is thrown in the constructor of an object, then all fully created members are destructed (using the their destruct...
7,403,347
7,412,012
Semaphore for Multiple Users
What I want to achieve: I would like to count the instances of my application to a fixed number. if more instances of the application are started, it should only work as a "Viewer" Her is the code of the sample application boost named_semaphore example The problem: it works fine if all processe are started from only on...
I found the solution Looks like the docu for Boost isn't that bad :-/ http://www.boost.org/doc/libs/1_47_0/doc/html/boost/interprocess/permissions.html Just have to pass the permission and set it to "unrestricted" boost::interprocess::permissions permtest; permtest.set_unrestricted(); _getch(); boost::interprocess::nam...
7,403,677
7,403,751
Should I include member definitions in a class which delegates the implementation to a subclass?
Say I have an abstract class "Base", of which another abstract class "Subclass" extends. Base has a number of abstract member functions, and "Subclass" implements a number of them, but leaves it's own subclasses to provide the implementation of others. Should I include the signature of the member functions which I don'...
You don't need to specify the abstract method again in the intermediate class. It will be inherited by the intermediate class as pure and still require it to be overridden in a further child. Note that your intermediate class will still be abstract and you couldn't create instances of it.
7,403,741
7,403,877
What's the real use of using n[c-'0']?
I'm a novice in C and I came across the code like this : int n[10]; if(c>='0' && c<='9') ++n[c-'0'] In if loop why we have to use single quotes around 0, whats the use of it, why we can't define 0 as an integer straight away? And in the second line of code ++n[c-'0'], whats the use of using array like this, in sense w...
In C, '0' is an integer whose value represents the digit zero as a character, not the value 0, which would be the null character. Other answers have omitted this, but it's important to note that the C language mandates that the decimal digits have consecutive values, so that if c is a digit, c-'0' is the numeric value ...
7,403,843
7,403,893
Does a virtual keyword with operator()() make sense? (functors)
Consider I have a hierarchy defined as below class Strategy { public: virtual void Run(); }; class StrategyA : public Strategy { public: virtual void Run(); }; class StrategyB : public Strategy { public: virtual void Run(); }; I was wondering if I replace the Run() with operator() makes any sense and if t...
Yes. Its fully makes sense. Any operator overload is a function, after all. It adds syntactic sugar to the language. Sometimes, they're necessary, but often, it's just syntactic sugar. Note that you've to invoke it polymorphically (of course, if you want runtime-polymorphism), and there're two ways you can do that: us...
7,403,883
7,403,943
Derived class with non-virtual destructor
Are there any circumstances in which it is legitimate for a derived class to have a non-virtual destructor? A non-virtual destructor signifies that a class should not be used as a base-class. Will having a non-virtual destructor of a derived class act like a weak form of the Java final modifier? I am especially interes...
Are there any circumstances in which it is legitimate for a derived class to have a non-virtual destructor? Yes. A non-virtual destructor signifies that a class should not be used as a base-class. Not really; a non-virtual destructor signifies that deleting an instance of derived via a base pointer will not wor...
7,404,163
7,404,231
Windows handling CTRL+C in different thread?
Here is a simple application that handled CTRL+C signal both on linux and windows: #include <QtCore/QCoreApplication> #include <QDebug> #include <QThread> void SigIntHandler() { qDebug()<<"SigInt ThreadID: "<<QThread::currentThreadId(); qApp->quit(); } #ifdef __linux__ #include <signal.h> void unix_handl...
From MSDN topic HandlerRoutine: A HandlerRoutine function is an application-defined function used with the SetConsoleCtrlHandler function. A console process uses this function to handle control signals received by the process. When the signal is received, the system creates a new thread in the process to execute the fu...
7,404,178
7,404,222
Difference between <include.hpp> and "include.hpp"
I am new to C++. What is the difference between including the c++ header files using "" and <> I am trying to use some of the header files form an open source library. All header files in that library are included using <>. Now when I do the same in my header file, its failing at compile time.
<> looks firstly in the header path for the header file whereas "" looks firstly in the current directory of the file for the header.
7,404,191
7,404,416
Using class member name in a constructor
I know this as this will assign the constructor parameter to the class member: class A { public: some_type B; A(some_type B) { this->B = B; } } But what will this do: class A { public: some_type B; A(some_type B) : B(B) { } } Will thi...
Will this assign the parameter to itself or the parameter to the class member or do something else? It will assign the parameter to the class member. How are the names in the list after construct thing (I have no idea how its called) resolved? This is the initializers list, and though the example can lead to co...
7,404,300
7,404,371
Better way to use a pointer?
I'm trying to create a program that will display bar graphs with * the maximum number of * can be 40. I have everything working but had a question with the code. Is there a better way as you can see I have to go back to the original address twice using: p_bar_length = p_bar_length - size; Is there a better way to ...
Rather than incrementing the pointer, use the array index: p_bar_length[i] = (values[i] / largest) * MAX_SPLATS; or use pointer arithmetic: *(p_bar_length + i) = (values[i] / largest) * MAX_SPLATS;
7,404,484
7,404,538
Why assignment operator is used for deep copy and who calls it
During deep copy we are writing overloaded copy constructor and assignment operator. May i know why we have to write the overloaded assignment operator because we doing the same in overloaded copy constructor(except some check and return this). Who is calling assignment operator
Follow the Rule of Three: If you need to write an copy constructor for your class, You also should write the Copy assignment operator and Destructor. Copy Assignment operator and Copy Constructor both are called Copying functions. They basically help in getting a new copy of an object from an existing object. They b...
7,404,526
7,406,096
Zip several std::list iterators together
Using the boost library it is possible to zip together a known number of iterators using a zip iterator, but what about when the number of iterators to be zipped is not known until runtime? To expand a little bit, I have a list of lists that are all the same size, and I need to group together all the values at each eac...
Alright after spending almost 1/2 hour, I came up with this dynamic_zip_iterator class which can be further improved, to make it look like STL-like iterators. As of now, it's very specific, as I've hardcoded std::list in it which you can replace with std::vector or can make even more generic: Anyway, have a look at it:...
7,404,628
7,404,712
How to call a function defined in my exe inside my DLL?
I have some general purpose functions defines in my exe file like Log(char* str). This function takes a string as an input from the caller and writes it to the logfile defined for that application. Now I want to write DLL code which will include a function to upload a file to a server. The objective is to import the u...
Have a function in your DLL that the .exe can call, passing in a function pointer to your Log function. Inside the DLL, store that function pointer and use it when you need to log things. If there is more than one such function you need to pass to your DLL, consider using a struct to store all the relevant function poi...
7,404,769
7,404,783
Is RTTI (Run Time Type Information) used in static casting?
In OOP concept, is the RTTI (Run Time Type Information) is also used for static casting or it is used only for dynamic casting? If it is specific for dynamic casting then justify your answer and also please explain why no RTTI for static_casting. Whats the point in using RTTI for downcasting?
A static cast is a compile-time construct, whereas RTTI is a run-time phenomenon. This means that no, RTTI is not used for static_cast. I suggest you read this thread as it has a lot of great info.
7,405,042
7,428,115
Boost asio and thread, if i run two instances i get cpu at 100%
I created a console application that sends data on a network link. I used the boost library, both the thread and the asio ones; currently i'm running it under Windows. If I run a single application it works perfectly, but if I open two instances on two different consoles, the CPU load goes to 100%, if I close one of th...
Ok it seems I've tracked down the problem. First of all, the 100% CPU usage was due to the fact that each instance was using 50% of the CPU (I'm on a dual core PC). So I run all over the code and found out this. I had this in my code, inside the NetworkLink::handle_response function: socket->async_read_some( boost:...
7,405,606
7,406,514
Best way to parse a list of numbers
I have a problem in that I need to process a list of numbers, which will be in an English sentence. It could be in the following formats: items 1, 2 and 3 items 2 through 5 items 1 to 20 items 4 or 8 My initial instinct is to write a simple state machine to parse it, but I was wondering if there is any better (simpler...
If you have C++11, the following parser (AXE) will parse all your formats (I didn't test it): unsigned i; auto num = axe::r_unsigned(i); auto space = axe::r_any(" \t"); auto format1 = num % (*space & ',' & *space) & ~("and" & +space & num); auto format2 = num & +space & "through" & +space & num; auto format3 = num & +s...
7,405,608
7,405,665
Problem with reading from file causing infinite loop
Ok this program I am working on seems to be all ok except there is a problem. Here is the code #include <iostream> #include <fstream> using namespace std; /* Function Name: CalculateBinary CalculateBinary takes a number from the main function and finds its binary form. */ void CalculateBinary( long InputNum) { ...
That is the usual problem with such loops which you've written. The correct and the idiomatic loop is this: ifstream fin("binin.txt"); long InputNum; while (fin >> InputNum && InputNum >= 0) { //now construct the logic accordingly! if(InputNum > 1000000000) cout << "Number too large for this program ......
7,405,658
7,405,724
Store pointers or objects in classes?
Just a design/optimization question. When do you store pointers or objects and why? For example, I believe both of these work (barring compile errors): class A{ std::unique_ptr<Object> object_ptr; }; A::A():object_ptr(new Object()){} class B{ Object object; }; B::B():object(Object()){} I believe one differenc...
If you have a big object inside your A class, then I'd store a pointer to it, but for small objects, or primitive types, you should not really need to store pointers, in most cases. Also, when something is stored on the stack or on the heap (freestore) is really implementation dependent, and A a is not always guarantue...
7,405,740
7,405,776
How can I initialize base class member variables in derived class constructor?
Why can't I do this? class A { public: int a, b; }; class B : public A { B() : A(), a(0), b(0) { } };
You can't initialize a and b in B because they are not members of B. They are members of A, therefore only A can initialize them. You can make them public, then do assignment in B, but that is not a recommended option since it would destroy encapsulation. Instead, create a constructor in A to allow B (or any subclass o...
7,405,839
7,405,898
Are multiple-inherited constructors called multiple times?
Are multiple-inherited constructors called multiple times? And in what order are constructors called? Does this depend on the order in the inheritance list? Here is an example (it's only for making the situation clear, no real-life example). class Base {}; class DerivedBaseOne : public Base {}; class DerivedBaseTwo : p...
The way you write it, Derived has two distinct subobjects of type Base, and each gets their own constructor called from the respective DerivedBaseXXX constructor of which it is the subobject. The order of calls follows the order of declaration. By contrast, of you declare DerivedBaseXXX : virtual public Base, then ther...
7,405,973
7,406,011
invalid operands of types - c++
I have a class named ThreeDigits on c++ code. I overloaded the + operand, this way: ThreeDigits* ThreeDigits::operator+(const ThreeDigits &number) const { double result= getNumber()+number.getNumber(); ThreeDigits* new_result=new ThreeDigits(result); return new_result; } but when I write on the main function...
You are trying to sum pointers to objects instead of the objects themselves. To invoke the overloaded operator you must call it on objects, thus dereferencing the pointers. By the way, creating all those objects with new a terrible way to do C++; in C++, unlike Java/C#, you should use new only when you have to, and all...
7,406,000
7,406,029
argument as a synonym for parameter in c, and c++
why exactly is the term argument used interchangeably with the term parameter in regards to functions or methods? seems ridiculous to me and in fact undermines programming altogether, except for the fact that it works.
Using the terms interchangeably is incorrect. An argument is a value passed in a function call. A parameter is an object, local to the function, into which the argument value is copied. For example: void foo(int parameter) { /* ... */ } /* ... */ int argument = 42; foo(argument); The definitive reference for thi...
7,406,290
7,406,351
Why am I getting a bad file descriptor error?
I am trying to write a short program that acts like a client, like telnet. I receive from the user input like so: www.google.com 80 (the port number) and /index.html However, I get some errors. When I write some debug information, it says that I have a bad file descriptor and Read Failed on file descriptor 100 messag...
You have a buffer overrun in your code. You're attempting to allocate a bunch of character arrays together into a buffer than is only 5 bytes long: char get[] = "GET "; // 'get' is 5 bytes long char http[] = " HTTP/1.0\r\nHost: "; char end[] = "\r\n\r\n"; strcat(get, URI); // BOOM! strcat(get, http); strcat(get, str...
7,406,331
7,406,463
CFile writing question
In my MFC application, I am using CFile class to write data to file. I store a sequence of objects of class CParagraph using Write() method for each data member in order. I use then Read() method to read from file into memory. One of the CParagraph's members used to be of type int, but now I have to change it to size_t...
Yes. If anything in the file changes size, everything after it must be re-saved. It's common to save a "version" char as the first part of a file. Then, when you need to resize a variable (or change tons of things), you can change the version when saving. Then, while loading, you can check the version, and use the c...
7,406,343
7,406,454
Advance File Pointer to skip over number in a file
I was wondering If I could jump positions in a text file. Suppose I have this file. 12 8764 2147483648 2 -1 Whenever I try to read the third number it won't read because its larger than the max number for a 32 bit int.So whenever i reach the third number, it keeps reading the second over and over again. How can I jump...
Use std::getline instead of operator>>(std::istream, int) std::istream infile(stuff); std::string line; while(std::getline(infile, line)) { int result; result = atoi(line.c_str()); if (result) std::cout << result; } The reason you are experiencing the behavior that you are, is that when the std::is...
7,406,596
7,408,135
Is leaking std::thread undefined behaviour?
Reason why somebody would be interested in //... new std::thread (func,arg1,arg2); } is that std::thread destructor(unlike boost::thread) kills the thread. func finishes is some time. My question is this safe in cases: Case 1: lets say that function takes arg1, arg2 by value. Case 2: lets say that function takes ...
An std::thread object represents a thread, it is not a "real" thread, that is a concept managed by the OS. Therefore, here you're leaking a std::thread object because you don't delete it. The destructor is never called. But the thread it was representing will end when it's instructions will end, like any thread. If t...
7,406,810
7,408,290
QGraphicsView: Snake-Line and Line animation
I have two questions regarding the QGraphicsView Framework. The first question is regarding a special line: I wanted to ask whether it is possible to draw an Snake- or Wave-Line (like in the linked image)? I would be grateful for any solution, because I dont have any idea how to get the sinus-shaped line. Image: a sna...
For the first part of your question : Probably a couple of ways: a. Use QPainterPath and the cubicTo() method to create the "path", then use QGraphicsPath with the path you create. In order to do this, you'll need to approximate the sinewave using bezier curves. Some info on that here, and the QPainterPath documentatio...
7,406,980
7,406,986
const reference to non-const object
In the following, would there be a temporary object created before const reference is used to a non-const object? const int y = 2000; const int &s = y // ok, const reference to const object. int x = 1000; const int &r = x; // any temporary copy here? If no then, how does this work? const int z = 3000; int &t = ...
No. A reference is simply an alias for an existing object. const is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r.* This doesn't require a copy to be created. Given that const is merely an instruction to the compiler to enforce "read-only", then it shou...
7,407,088
7,439,161
KDevelop debugging warning: Failed to set controlling terminal: Operation not permitted
A while ago I changed my personal operating system to linux and my development enviroment to KDevelop. However debugging c++ projects is still not working as it should. My KDevelop version is 4.2.2 (I installed it through package management) Every time I hit the "debug button" the application is starting with the conso...
I also had this problem, but I use gdb in KDevelop sparsely enough that hadn't bothered me yet. Here's my log of trying to fix it: Grepping through the GDB 7.3.1 source code reveals that this message is printed when GDB tries to set its master TTY to a newly-created pseudo-tty (see gdb/inflow.c, lines 683-740). In part...
7,407,383
7,407,409
Cant send NULL to a function getting vector
I have this function: void RegMatrix::MatrixInit(int numRow,int numCol, std::vector<double> fill) { do something; } and i want to send this: MatrixInit(numRow,numCol,NULL); how can i pass NULL as vector?
You cannot pass NULL as vector, you could instead pass an empty vector like this: MatrixInit( numRow, numCol, std::vector<double>() ) Note that you would be better off taking the fill vector as const&.
7,407,534
7,407,582
Main function in .lib as startup function?
I want to do something like this: library.h #define main ClientMain libary.cpp #define main ClientMain extern "C" int main (int argc, char *argv[], char *envp[]); #ifdef WINDOWS int WINAPI WinMain() { // other code here ClientMain(0, 0, 0); } #endif client.cpp // platform independent code #include library.h int ...
You're compiling your Windows program as a console program. In that case, the expected entry point really is main, not WinMain. The latter is for GUI programs. Your program has a function named WinMain and a function named ClientMain, but no main. It's fine if you want your library to provide the main function, but you...
7,407,572
7,407,599
Getting the module size
Is there a way to get the size of a loaded module in c++ considering that I have the base DLL address?
Call GetModuleInformation().
7,408,049
7,408,124
copying an element from list<string>mylist to string mystr
list<string> mylist; mylist.push_back("random stuff"); list<string>::iterator it; it=mylist.begin(); string mystr; //and this doesn't work: mystr=*it; Let's say I have a list<string> mylist and it has 3 items. Since I can't work on the characters of each element I must copy what item I want to a simple string or a cha...
The code works great and outputs the correct result. Also, you can work with characters of each element like this: for (list<string>::iterator iter = mylist.begin(); iter != mylist.end(); ++iter) { char c = (*iter)[0]; //this is the first character. } You can cycle through the string with an iterator too even, s...
7,408,154
7,500,613
Compress array of data sent through sockets
We have a Server that sends some data to a client(both written using c++/MFC) using sockets The data is getting a little too big and I'm looking for solutions to compress it. Basically I need to compress some char Arrays I am not very familiar with MFC. I looked at zlib but I had a hard time getting anything compiling...
Is zlib a mandatory requirement of your project ? Otherwise, some other programs have simpler header file, which are easier to work with. For example, this one (tested with GCC and MS's VS) : int LZ4_compress (char* source, char* dest, int isize); int LZ4_uncompress (char* source, char* dest, int osize); Source code ...
7,408,187
7,408,211
C++ vector::erase problems with OpenCV code
I'm having troubles with a part of my OpenCV C++ code: double getVectorMedian( vector<double> values ) { size_t size = values.size(); double median; sort(values.begin(), values.end()); if( size % 2 == 0 ) { median = (values[size / 2 - 1] + values[size / 2]) / 2; } else { ...
void cleanSquares( const vector<vector<Point> >& squares ) squares is a const reference, you cannot erase from it. Drop the const, or take by value, according to your final intentions. I would also recommend using the erase( remove_if( ... ) ) idiom, if you feel comfortable with it.
7,408,388
7,408,486
Error while loading shared libraries
I am a C++ beginner. I have a c++ project that i built using the existing make files. I have a library that I linked from /usr/local/lib. Build is successful but when I run it, its complaining about the library that I linked form /usr/local/lib. If I copy that library to /lib64 and run my program, everything is fine. P...
As Oli explained, you can set LD_LIBRARY_PATH, but you can also install the library permanently, even if it doesn't live in one of the standard directories. Start with man ldconfig it's quite important you know how that thing works. by default (ie unless you do something) only libraries in the trusted directories (/...
7,408,407
7,408,487
Generate next largest or smallest representable floating point number without bit twiddling
Given an arbitrary finite floating point number, is there a way to determine what the next representable floating point number? For example, given 1.0f, by definition the next largest representable number is 1.0f + std::numeric_limits<float>::epsilon(). Is there a way to synthesize an epsilon for any value - not just 1...
In C++11, you use std::nextafter(). Lacking that, on a C99 system, you use nextafterf, nextafter, or nextafterl from the C math library (for types float, double, and long double, respectively).
7,408,421
7,408,442
No matching function - c++
I have the following constructor: RegMatrix(int numRow, int numCol, std::vector<double> fill); and inside one of my functions: RegMatrix RegMatrix::operator+(RegMatrix &matrix) I create: std::vector<ThreeDigits> fill; and then I return: return RegMatrix(1,2,fill); and it says I return (int,int,std::vector<ThreeDigi...
std::vector<double> is not the same type as std::vector<ThreeDigits>. You can fix this problem by either creating RegMatrix::RegMatrix(int, int, const std::vector<ThreeDigits>&), or by modifying the declaration of fill: std::vector<double> fill;.
7,408,470
7,408,755
Given a vector of points (possibly out of order), find polygon (not convex hull)
I currently have a vector of points vector<Point> corners; where I have previously stored the corner points of a given polygon. Given that, I know for sure that the points form a simple polygon that does not contain any self-intersecting edges. However, in the process of storing these vertices, the order in which they...
1. Heuristic to determine the shape There is no unique solution so there is no simple algorithm. You could try to somehow mimic your intuition. start by a random point and connect each point to its closest neighbor. Then connect the last point to the first one. start by selecting a point and its closest neighbor and c...
7,408,475
7,408,537
Is there a libraray/method for 80 column formatted text output?
Here is what I'm looking for. I'd like to find a library or method that formats output text, such that it word wraps at 80 columns (or user configurable), and allows user defined indentation. I know that I could create one, but I suspect that there is already a library available that does this. I've googled around and ...
Here it is, search harder next time ;) 2.2.4. Line-Wrapping Filters http://www.boost.org/doc/libs/1_47_0/libs/iostreams/doc/tutorial/line_wrapping_filters.html
7,408,574
7,408,627
Check if a BSTR is empty
I have a variant that contains a BSTR, but sometimes the BSTR is "" (empty), so how to avoid this? I have tried something like: variant.bstrVal != NULL But it didn't work.
Use SysStringLen: if (SysStringLen(variant.bstrVal) == 0) { ... }
7,408,692
7,425,762
G++ compiler: option -s is obsolete and being ignored C++
I'm trying to compile and strip a very simple programm in C++ with the g++ compiler (4.6.0 on Mac OSX). But while compiling i get an warning. source code: #include </usr/local/Cellar/gcc/4.6.0/gcc/include/c++/4.6.0/iostream> int main(){ std::cout << ("Hello World\n") ; } Terminal code: g++ hello.cc -Wall -std=c+...
The error message is from ld, not from gcc or g++. (The gcc and g++ commands are a drivers that invokes the compiler, the linker, and other tools.) gcc passes the -s option to the linker, as documented in the gcc 4.6.1 manual; apparently the MacOS port of gcc still does that. The GNU linker (GNU ld) still accepts the ...
7,408,785
7,459,672
Is there a way to play a system beep on Mac OS?
Is there a way to play a system beep on Mac OS using C++ and Xcode? I understand that I need to use a library. Is there a library that works across both the Mac and Windows platforms?
The cross platform way to play a beep is std::cout << "\007";. I had been trying to play it by passing in a char and then decrementing until 7. That didn't work. Explicitly outputting the code did work though.
7,408,816
7,409,015
Unit testing of the Base Class a good approach
I am unit testing some software in C++ which has base and derived classes. I was wondering if it is actually a good approach to test both the base as well as the derived classes or should one proceed to unit test only derived classes and leave the base class alone ?
It is generally best to test anything with an implementation. Consider breaking any implementation in the base up into smaller, dumb concrete objects and reusing them by composition. Those are easier to unit test than some weird object hierarchy. Then each derived object only needs to test that it is still valid, give...
7,408,930
7,413,568
What's wrong with this CreateWindowEx function?
Okay, so first a little overview of what I am tryna do.. I am trying to create 3 child window in a main parent window, and use EnumChildWindow and EnumChildProc to enumerate them, I want to create 3 child windows of same height as of parent but 1/3rd width, and align them one after the other.. So, I captured the WM_CRE...
My psychic powers suggest you need to pass in the WS_VISIBLE style to the CreateWindow call above for your child windows - so you can seem them. :) My development experience suggests the following: What is the return value of CreateWindowEx? Did you assign the return value to a variable. And if so, did you set a break...
7,409,017
7,409,223
OpenCV Video Editing?
I am using OpenCV and trying to apply a Gaussian Blur to an incoming video stream. I basically use cvQueryFrame to remove a frame, blur it and display the frame onto the screen. The thing is though, my video gets stuck on the first frame after I apply the blur....anyone know why? its basically showing one frame instead...
You are missing a call to cvWaitKey. This is the only way to tell OpenCV to process events and thus prevent the GUI from freezing. Try adding this line: cvWaitKey(10); after cvShowImage("Output",process);. Edit: here is the documentation for cvWaitKey
7,409,081
7,409,130
declaring sizes of vectors in a collection. c++
using namespace std; vector<vector<T> > vec_collection(3); vec_collection[0]=vector<T>(12); vec_collection[1]=vector<T>(3); vec_collection[2]=vector<T>(14); Suppose I have an empty collection of 3 vectors and after initialization, I want the first, second, and third vector to be of specific size 12, 3, and 14 say. I...
Your code in line of principle creates separated temporary vector instances that replace the existing zero-size ones, which in theory means that for every of those lines you have a constructor call (create the temporary), a copy-constructor call (copy it over the existing vector) and a destructor call (destroy the temp...
7,409,536
7,409,547
"no match for 'operator='" in c++, trying to make a linked list
I'm writing a C++ program using Code::Blocks. I want to make a doubly linked list. My plan is to make an node class called geoPoint with pointers north and south to other nodes. I've written a test function to create and link two nodes, then traverse them with a third node. Here's what I have so far: #include <iostr...
currentPoint is of type geoPoint. &currentPoint.north is of type geoPoint**. & is the address-of operator: you're taking the address of a geoPoint*, which stores the address of a geoPoint. If you want currentPoint to hold a copy of the geoPoint to which currentPoint.north refers, use the dereference operator *, as in *...
7,409,565
7,409,589
how to use reinterpret_cast to cast to a derived class pointer in c++
Here is my test example: struct base { virtual ~base(){} int x; }; struct derived: public virtual base { base * clone() { return new derived; } derived(): s("a") {} std::string s; }; int main () { derived d; base * b = d.clone(); derived * t = reinterpret_cast<derived*>(b);...
Even if b is here dynamically of type derived, you have to use dynamic_cast. This is what dynamic_cast is for, to dynamically convert a pointer of a base class into a derived class at runtime. reinterpret_cast takes the raw pointer and considers it as being of the derived type. However, because of the virtual inherita...
7,409,656
7,410,731
Calling ASM Function in C++
I asked a question yesterday, how to call a __fastcall function, it worked great. Now my final function i got to call is having some difficulties. Here is the ASM function. seg000:0043671F push 0AA2BAD1Bh seg000:00436724 lea ecx, [ebp+var_14] seg000:00436727 call ...
Solved ebx must of been used for key. Simple as that. void also must of been changed to int forgot about that. (most likely not to important)
7,409,675
7,409,883
Identifying / generating a waveform?
I would like to code something that could take some sort of input and identify it as a square wave, triangle wave, or some sort of waveform. I also need some way of generating said waves. I do have experience with C/C++, however, I'm not sure how I would approach simulating all of this. Eventually, I would like to tran...
Generating the waves is significantly easier than identifying them. I have a small project that does some wave generation. Here's an example from my project: float amplitude; switch (sound->wavetype) { case LA_SQUARE: amplitude = sound->theta > .5 ? 1.0 : -1.0; break; ...
7,409,687
7,409,841
Sharing an array with STL vectors
I would like to share the contents of an array of doubles a of size k with one or more STL vectors v1, v2...vn. The effect that I want from this shared storage is that if the underlying array gets modified the change can be observed from all the vectors that share its contents with the array. I can do that by defining...
This sounds to me like you want to alias the array with a vector. So logically you want a vector of references (which doesn't work for syntactical reasons). If you really really need this feature, you can write your own ref wrapper class, that behaves exactly like an actual C++ reference, so the users of your vn vector...
7,410,237
7,410,309
Constructor with default values & Different Constructors
I would like to do something like this class foo{ private: double a,b; public: foo(double a=1, double b=2){ this.a=a; this.b=b; } } int main(){ foo first(a=1); foo first(b=2); } Is such thing possible or do I need to create two new constructors? Here comes the 2. question: What is...
It's probably overkill for your example, but you might like to learn about the Named Parameter Idiom.
7,410,376
7,410,392
Does this cause memory problems?
Say I have the following: Foo* foo = new Foo(bar); //later on *foo = Foo(anotherBar); Since foo was allocated on the heap does this cause problems or will the memory from the temporary Foo be copied into the address of foo on the heap? Thanks
*foo = Foo(anotherBar); is no different than a regular assignment to an object of Foo type. *foo returns an lvalue of type Foo, and you are assigning to it. Short answer: it won't cause problems, the temporary will be copied into the heap Foo object pointed by foo.
7,410,382
7,410,483
How can I write a signature on C# for a wrapped C++ method having a pointer to a function it its arguments?
I'm writing a wrapper for a dll. The dll has a method whose signature resembles the following: unsigned long aMethod(void *anyParameter, void (*anotherMethod)(const char *, void *)) I've searching at google for a tutorial to give me insight on how to write the signature on C# so the framework can do the marshalling ...
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void AnotherMethodDelegate(string s, IntPtr anyParameter); [DllImport("dllname", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] uint aMethod(IntPtr anyParameter, AnotherMethodDelegate anotherMethod);
7,410,559
7,411,385
C++ - Overloading [] operators based on the side of assignment
I'm trying to write a dynamic array template in c++ I'm currently overloading the [] operators and I'd like to implement a different behavior based on which side of assignment they are used on. #include <iostream> ... template <class T> T dynamic_array<T>::operator[](int idx) { return this->array[idx]; } template...
Scott Meyers talked about this in one of the Effective C++ books. Basically the trick was to return a temporary const- or non-const proxy object from the index operators (operator[]() and operator[]() const), then overload the assignment and implicit conversion operators for that proxy class. Something like this: tem...
7,410,798
7,410,844
C++ Fatal Error LNK1120: 1 unresolved externals
What is causing this error? I google'd it and first few solutions I found were that something was wrong with the library and the main function but both seem to be fine in my problem, I even retyped both! What could be causing this? This might be helpful: MSVCRTD.lib(crtexew.obj) : error LNK2019: unresolved external sym...
From msdn When you created the project, you made the wrong choice of application type. When asked whether your project was a console application or a windows application or a DLL or a static library, you made the wrong chose windows application (wrong choice). Go back, start over again, go to File -> New -> Pro...
7,410,846
7,410,871
Using an icon on a dialog box window C++ Win32 API
I am trying to create a dialog box with an icon at the top like so. I am using a resource file to load the icon like so. IDI_ICON1 ICON ".\\usb.ico" I have tried setting the window icon using the following code. SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)IDI_ICON1); SendMessage(hwnd, WM_SETI...
Use LoadIcon and pass an icon handle to WM_SETICON. HICON hicon = LoadImageW(GetModuleHandleW(NULL), MAKEINTRESOURCEW(IDI_ICONMAIN), IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR | LR_DEFAULTSIZE); SendMessageW(hwnd, WM_SETICON, ICON_BIG, hicon);
7,410,888
7,410,897
Does temporary object creation depends on the C++ compiler?
Does temporary object creation depends on the compiler? In the code bellow, I call a function sending a char* but the function requires an Object reference. However, Object has a constructor that uses a char*.. So a temporary object is automatically created and send to the print function. class Object { string text...
When you declare such a constructor Object ( const char* value ) it means the compiler can do an implicit conversion. So no it is not a compiler dependent feature but it is by desing. The compiler is simply allowed to take your "hello" and pass it to the Object contructor before sending it to the print(const Object &...
7,411,144
7,412,575
multi_index_container
So I have a boost::multi_index_container with multiple non-unique indexes. I would like to find an elegant way to do an relational-database style query to find all elements that match a set of criteria using multiple indexes. For instance, given a list of connections between devices, I'd like to search for all eleme...
You might simply get some inspiration from relational databases... ... but first we need to demystify a thing about indexes. Compound Indexes In a relational database there are two types of indexes: regular indexes: an index on one column compound indexes: an index on multiple columns at once The two give different p...
7,411,515
47,368,753
Why does C++ require a user-provided default constructor to default-construct a const object?
The C++ standard (section 8.5) says: If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor. Why? I can't think of any reason why a user-provided constructor is required in this case. struct B{ B():x(42){} int do...
This was considered a defect (against all versions of the standard) and it was resolved by Core Working Group (CWG) Defect 253. The new wording for the standard states in http://eel.is/c++draft/dcl.init#7 A class type T is const-default-constructible if default-initialization of T would invoke a user-provided constr...
7,411,896
7,412,026
what is placement new operator in C++ and does java has it?
I heard about placement new operator of C++. I am confused what it is. However, I can see where it can be used under a question in stackoverflow. I am also confused whether we have this in java or not. So my question is very precise: What is placement new operator and do we have something like it in java? Note please,...
The following article explains the meaning of placement new in C++: http://www.glenmccl.com/nd_cmp.htm This term itself is relevant for overloaded new statement. Since Java does not allow to overload operators at all and specifically new operator the placement new is irrelevant for Java. But you have several alternati...
7,412,042
7,412,171
HDF5 C++ interface: writing dynamic 2D arrays
I am using the HDF5 C++ API to write 2D array dataset files. The HDF Group has an example to create a HDF5 file from a statically defined array size, which I've modified to suite my needs below. However, I require a dynamic array, where both NX and NY are determined at runtime. I've found another solution to create 2D ...
Well, I don't know anything about HDF5, but dynamic 2D arrays in C++ with a contiguous buffer can be simulated by using a 1D array of size NX * NY. For example: Allocation: double *data = new double[NX*NY]; Element access: data[j*NY + i] (instead of data[j][i])
7,412,185
7,412,202
What is the difference between catch(...) vs catch(CException *)?
CException is the base type of all exceptions thrown by VC++, so it should catch all the exceptions, right?
CException is not the base type for all extensions (it might be the base type of all exceptions that MFC code uses, but that's as far as it goes). In C++, you can throw anything; it doesn't have to be an "exception" subclass, and it does not even have to be an object. It's perfectly legal for example to write throw 42;...
7,412,224
7,415,152
NDK error with cstdlib
I am trying to build my first NDK library, and am getting an error when compiling: .../cstdlib:53: error: '::clearenv' has not been declared Can I not use the C standard library with NDK?
I solved it by changing <cstdlib> to <stdlib.h>. Not sure why that worked, though.
7,412,274
7,412,299
Why add void to method parameter list
I've seen methods with the following signature: void foo (void); They take no argument, however I'm wondering whether doing this is useful or not. Is there a reason why you would want to do it?
The C++03 standard says (emphasis mine): 8.3.5.2 The parameter-declaration-clause determines the arguments that can be specified, and their processing, when the function is called. [Note: the parameter-declaration-clause is used to convert the arguments specified on the function call; see 5.2.2. ] If the param...
7,412,498
7,418,634
Dubious error messages in Eclipse (CDT) while build succeeds
Using the Eclipse IDE for C/C++ Linux Developers (Version: Indigo Release) with g++ 4.1.2 (on Scientific Linux CERN 5 = RHEL 5), I currently work on a project where I make use of a Qt4 GUI as well as Apache's log4cxx framework and of some C++ standard classes. I have installed Nokia's "Qt Eclipse Integration for C++" ...
It's not Qt per se - it's the CDT Indexer and the Qt Eclipse Integration plugin fighting. I find that performing a clean sometimes 'resets' the includes list in CDT project settings (only does this with Qt integration plugin running), but because Qt uses the .pro file - the compilation succeeds but CDT's CODAN (which ...
7,412,699
7,412,718
Polymorphic plus sign in C++?
I understand how polymorphism and inheritance works in C++, but my problem is: how do you make operators polymorphic for the following specific example? Say I have a Foo class and two Foo instances, fooA and fooB. I want to redefine the plus sign operator so that "fooA + fooB;" does something specific to Foo instances ...
Example from http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/topic/com.ibm.xlcpp8a.doc/language/ref/cplr318.htm: #include <iostream> using namespace std; class complx { double real, imag; public: complx(double real = 0., double imag = 0.); // constructor complx operator+(const complx&) cons...
7,413,199
7,413,504
Generate a new element different from 1000 elements of an array
I was asked this questions in an interview. Consider the scenario of punched cards, where each punched card has 64 bit pattern. I was suggested each card as an int since each int is a collection of bits. Also, to be considered that I have an array which already contains 1000 such cards. I have to generate a new element...
There are 264 64 bit integers, a number that is so much larger than 1000 that the simplest solution would be to just generate a random 64 bit number, and then verify that it isn't in the table of already generated numbers. (The probability that it is is infinitesimal, but you might as well be sure.) Since most random...
7,413,247
7,413,307
cin.clear() doesn't reset cin object
I have the following loop. It should read numbers until EndOfFile, or the user input -999 int arr[100]; int index; for (index = 0; index < 100; index++) { cin >> arr[index]; if (!cin) { cin.clear(); index--; continue; } if (arr[index] == -999) { break; } } When the user input an invalid thing, such...
After calling clear, you must also somehow remove the invalid input from the stream. Here is one way: cin >> arr[index]; if (!cin) { cin.clear(); std::string ignoreLine; //read the invalid input into it std::getline(cin, ignoreLine); //read the line till next space index--; continue; } It's because when ...
7,413,301
7,413,347
Stack around the variable 'uChar' was corrupted
Here is the code which converts a hex string to byte array, it works fine but when the loop goes end and the complier reaches to the end of function it throws this error: "Stack around the variable 'uChar' was corrupted" void Cfsp::stringToHex(unsigned char hexArray[], LPCTSTR string) { int stringLength=strlen(stri...
The reason you get corruption is because you send sscanf_s an unsigned char * where it expects int *
7,413,331
7,413,460
OpenMP: conditional use of #pragma
I'm using OpenMP to improve my program efficiency on loops. But recently I discovered that on small loops the use of this library decreased performances and that using the normal way was better. In fact, I'd like to use openMP only if a condition is satisfied, my code is #pragma omp parallel for for (unsigned i = 0; i...
I think you should be able to achieve the effect you're looking for by using the optional schedule clause on your parallel for directive: #pragma omp parallel for schedule(static, OMP_MIN_VALUE) for (unsigned i = 0; i < size; ++i) do_some_stuff (); You might want to play around with different kinds of scheduling t...
7,413,362
7,413,496
Where to destroy thread and deadline_timer objects after timeout?
my question is about a running deadline timers which wait for some operations represented by the same function to finish: But i dont't know, where to free my thread and deadline object after a safe finish oder an interrupt by deadline time out. When can that happen? boost::asio::deadline_timer* mDeadline1; boost::asio:...
The timers as they stand are meaningless - only you know what they mean and what they are supposed to do - so you have to decide what to cancel. As to cleaning up, hold them in a scoped_ptr or shared_ptr and they will be automagically cleaned up when the scope/last reference is done.
7,413,482
7,413,734
cast stl::vector containing pointers to stl::vector containing constant pointers
Consider the following class: class SomeInfo { private: std::vector<someObj *> _myVector; public: const std::vector<const someObj*>& getInfoVector() const { return _myVector; } }; When I try to compile with gcc 4.1.2, it gives me the following error: error: invalid initialization of reference ...
What I would do in this situation is forget about returning a vector (or reference thereto). The caller can't make any changes, so doesn't need to see any particular container. Other answers explain why you can't refer to your vector as if it were a vector of const someObj*. For that matter, if in future you change you...
7,413,530
7,417,813
Exception when execute update() of an itk::writertype
I have an image in an “itk::image::Pointer salida”. I have checked that it has the correct pixelvalues. I want to save the image into a file, but in the last line, it gives me an exception and now I don’t know what to do: // Saving the result into a file salida = ui.imageframe->imagereader; writer = itk::ImageFileWrite...
Try catching the exception and see what it contains. I am not familiar with itk but looking at the API, the following should work: try { writer->Update(); } catch( itk::ExceptionObject& ex ) { qDebug() << ex.what(); } This should lead you to the source of the exception.
7,413,589
7,413,728
When and why do we need to use COM?
I want to know when and why to use COM? Please let me know in which situation I need to use com instead of normal DLL.
First, it's worth mentioning that COM is quite an old technology. It significantly predates .NET, which sometimes provide the same functionality. However, comparing to a plain DLL, it has a few advantages, for example: It doesn't have a functional interface, but an OO one. You create objects rather than call exported ...
7,413,643
7,413,752
Disable functions inside templated class
I'm trying to disable some functions inside a simple template class. The functions that should be removed depend on whether the template argument has certain typedefs. The example boils down to this: template<typename T> struct Foo { typename T::Nested foo() { return typename T::Nested(); } int bar() { return 1; } ...
You can use class template specialization. If you have several functions, then you can move each function to a base class, and specialize each base class.
7,413,799
8,391,774
Boost chrono run_timer undefined reference
I am trying to compile the run_timer_example.cpp example in the boost distribution (1.47.0) and I am getting this using the Intel compiler: $ icc -I/usr/local/include -L/usr/local/lib -lboost_system -lboost_chrono run_timer_example.cpp /tmp/iccUIv4Av.o: In function `main': run_timer_example.cpp:(.text+0x33): undefined ...
This example was there before the review and uses some interface that is not part of the reviewed Chrono library. I forgot just to remove it. Done in 1.48. Sorry for the disturbance.
7,413,820
7,416,304
boost ptime from sql server timestamp_t is off by minutes. What did I do wrong?
I have a SQL server database and I am pulling dates from it and converting the type of timestamp_t into Int64 as such: Int64 from_timestamp_t(dtl::timestamp_t& t) { // create a new posix time structure boost::posix_time::ptime pt ( boost::gregorian::date ( t.year, t.month, t.day), boost::p...
I'm not familiar with SQL Server 2005, but boost posix time has the seconds function if ticksFromEpoch is equivalent to one second. ptime time = epoch + boost::posix_time::seconds(ticksFromEpoch); However, the generic way to handle this is presented in the boost date_time documentation: Another way to handle this is ...
7,413,876
7,413,968
Does the vector.resize() method calls the default elements constructors when resizing?
I am trying the following code: struct _Struct2 { void *ptr; double dval; }; struct _Struct { float fval; int ival; std::vector<_Struct2> data; }; std::vector<_Struct> vec; int main() { vec.resize( 9 ); for ( int i = 0; i < vec.size(); i++ ) { _Struct &elem = vec[i];...
No it doesn't call default element constructor. std::vector never calls default constructors internally (it does in C++11, but not in earlier versions of the specification). The full signature for vector::resize looks as follows void resize(size_type sz, T c = T()); I.e. it has a second parameter (with default argumen...
7,414,256
7,415,072
How to get mouse pressed events in the root widget of a hierarchy in Qt
I have the following problem with Qt (no answer on this site seemed to address exactly this problem so I create my own question). I have an application with a MainWindow class which inherits from QWidget. At a certain point there is a table inside the main window and I want to catch all mouse pressed events outside tha...
You could do this by installing an event filter in the main window. Take a look at QObject::installEventFilter() in the Qt docs.
7,414,327
7,414,486
nested class or struct in a class
Code goes first: //.h file class A { public: A(); B makeB(int); //question 1 //protected: struct B { int _id; B(int id); } }; //.cpp file A::A() { cout<<"A ctor\n"; } B A::makeB(int id) //question 2 { return B(id); } 2 questions: 1.Should I put make...
This compiles fine: class A { public: struct B; A(); B makeB(int); //question 1 struct B { int _id; B(int id) {}; }; }; A::A() {} A::B A::makeB(int id) //question 2 { return B(id); }
7,414,498
7,415,055
compiling livemedia as dynamic library: undefined references to virtual functions
I am trying to compile the livemedia libraries as a shared object, so I get the following .so: libBasicUsageEnvironment.so libgroupsock.so libliveMedia.so libUsageEnvironment.so It seems to be good, but when I try to link against these libraries, I get a lot of errors of undefined reference to the virtual functions t...
It is not a compiler bug. It indicates that the function definitions are found in the library .so rather than the header, which further implies that you are not linking correctly.
7,414,770
7,415,947
Dispatch based on arguments of a non-member function
I was under the (possibly incorrect) assumption that non-member functions in C++ do not dispatch based on the type of its arguments. But after reading about iterator_category it seems I can call a function depending on the category type of its argument and the call also handles inheritance. For instance if I write only...
You are indeed using compile-time polymorphism, which dispatches based on the static type of the object. The iterator categories are chained by inheritance (not the iterator themselves), so that: InputIterator <- ForwardIterator <- BidirectionalIterator <- RandomAccessIterator (should be an OutputIterator too, but it ...
7,414,829
7,415,898
May a compiler report errors on unknown attributes? Even with scope?
In N3291 "7.6.1.(3/5) Attribute Syntax and semantics [decl.attr.grammar]" concerning how attributes are written in source code I read The use of an attribute-scoped-token is conditionally-supported, with implementation-defined behavior. and For an attribute-token not specified in this International Standard, the ...
C++17 adds an explicit statement that attributes not recognized by an implementation are to be ignored. Before C++17, all attribute behavior was implementation defined, so the implementation could do anything. Part of the purpose of the attribute specification is so that compiler makers will stop cluttering the languag...
7,414,833
7,414,884
How to communicate between C++ and PHP on Windows?
I've a project that has a program written in C++ (that always has to run) and a Apache web server with PHP on a Windows PC. Now I want to send parameters retrieved from clients in PHP to the C++ program and get an answer back, but I can't figure out how to do it. I've looked at exec() and shell_exec() in PHP, but they ...
Open a socket or use some other OS-provided interop mechanism. (I'd stick with TCP/IP sockets.)
7,414,838
7,414,863
returning address in C
Why this code is giving unexpected output. int * func(int *xp) { int y = 10 + *xp; return (&y); } void main() { int x = 10; int *xp = func(&x); printf("%d\n", x); printf("%d\n", *xp); } expected output: 10 20 Real Output: 10 1074194112
You are returning a pointer to a variable (y) that goes out of scope the moment you leave func. This is undefined behaviour. It is not entirely clear what you're trying to achieve, but there are several ways to fix this: return the int by value; modify *xp in place and don't return anything; take an additional int* pa...
7,414,890
7,414,999
To "if, if, if" or to "if, else if, else if, else"
I am writing some code for data analysis, and have to exclude samples based on some criteria. In practice I end up writing code such as: bool Test(SampleType sample) { if( ! SubTest1(sample) ) return false; if( ! SubTest2(sample) ) return false; if( ! SubTest3(sample) ) return false; return true; }...
Compiler generates the same code for both the versions. But the 1st version is better in maintainability aspect if you compare just with the 2nd version. The code exits when the return statement is encountered; so there is no use of keeping else in the upcoming if. It makes the developer understand the code better. Als...
7,414,983
7,415,204
How to use the ANSI Escape code for outputting colored text on Console
I read about ANSI-C escape codes here. Tried to use it in C/C++ printf/cout to colorize the text outputted to consolde but without sucess. Code: #include <iostream> #include <cstdio> int main() { int a=3, b=5; int &ref = a; ref = b; //cout << "\155\32\m" << a << b <<'\n'; //here it prints m→m 5, n...
I'm afraid you forgot the ESC character: #include <cstdio> int main() { printf("%c[%dmHELLO!\n", 0x1B, 32); } Unfortunately it will only work on consoles that support ANSI escape sequences (like a linux console using bash, or old Windows consoles that used ansi.sys)
7,415,326
7,415,403
Deprecated conversion from string constant to char * error
Possible Duplicate: C++ deprecated conversion from string constant to ‘char*’ I am having following code, though i didn't copy full code because it is huge. Following code is in template class, and i am getting warning as below. Because of warning in template i am not able to instantiate it and getting "instantiate...
If a function takes a char const *, it guarantees that it only reads whatever data the pointer points to. However, if it takes a non-const pointer, like char *, it might write to it. As it is not legal to write to a string literal, the compiler will issue a warning. The best solution is to change the function to accept...
7,415,722
7,417,026
How to use intel prefetch pragma when data hidden inside an object?
Intel helpfully provides a prefetch pragma; for example #pragma prefetch a for(i=0; i<m; i++) a[i]=b[i]+1; will prefetch a a certain number of loop cycles ahead, as determined by the compiler. But what if a is not an array but a class with [] overridden? If operator[] does a simple array access, can prefetch still ...
One way to find out is to try it and look at the assembly. And if anything else, just benchmark it with and without the pragma. However, I'm not sure if the prefetch pragma is what you want: The prefetch pragma is supported by Intel® Itanium® processors only. http://software.intel.com/sites/products/documentation/stu...
7,416,048
7,416,420
Where should I put the empty base class?
Does the order in which I list the base classes matter when one of them is empty and the other one is not? class Foo : normal_class, empty_class { ... }; class Foo : empty_class, normal_class { ... }; Does the order affect the compiler's ability to apply the empty base class optimization?
I don't think it matters - although I tend to try to put an empty base first anyway. There's an interesting note on multiple empty bases on the boost site: http://www.boost.org/doc/libs/1_38_0/libs/utility/operators.htm#old_lib_note
7,416,100
7,416,141
C++ overloading >> operator strange compile error
#include <iostream> #include <string> using namespace std; class phonebook { string name; string prefix; public: phonebook(string &name, string &prefix) { this->name = name; this->prefix = prefix; } friend istream &operator>>(istream &in, phonebook &book); }; istream &phonebo...
You cannot overload operator >> for streaming as a member function. Any operator that is defined as a member function takes its first argument as a reference to (const) Type, where Type is your class name - in this case, phonebook. You need to change istream &phonebook::operator>>(istream &in, phonebook &book) to ist...
7,416,227
7,416,291
Operating on different elements of std::vector in parallel
Say I have a std::vector<Object*>. The vector is large ( > 1000 elements) and each Object* needs to have extensive computation done on it. The for loop that runs each the computation on each element then, can be easily parallelized. In fact, I could process all 1000 elements in parallel for maximum speedup ("embarras...
1) Yes 2) You can use OpenMP to paralellize vector handling. If you are working with Microsoft VC++ 2010, Concurrency library has parallel_for and parallel_for_each algorithms.
7,416,251
7,417,949
Using decltype to cast this to const
I'm attempting to solve a problem in which decltype will greatly simplify things, but I'm running into an issue using decltype on *this and adding a const qualifier. The sample code below demonstrates the problem. #include <iostream> struct Foo { void bar() { static_cast<const decltype(*this)&>(*this).bar(); ...
Since the expression *this is not an id-expression (i.e. it doesn't name an entity, like a variable), then decltype(*this) gives the type of the expression *this. That type is Foo&, so adding a const qualifier and making a reference to that doesn't change anything: either it silently collapse to Foo& (following rules l...