question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
6,656,336 | 6,656,382 | spaces are not printing when reads the input file | I am trying to read each 'char' of the input file and write in the output file until finds the '?' as the end of file . Every char is written in output file except the spaces between words. I dont know what's wrong in this code??
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inf... | Try using noskipws on read...
infile >> noskipws >> ch;
The noskipws tells the input stream to not skip whitespace which it does by default.
|
6,656,380 | 6,657,990 | Boost 1.46.1, Property Tree: How to iterate through ptree receiving sub ptrees? | First of all I shall say that I think I got how it should be done but my code will not compile any way I try. I based my assumption on this official example of empty ptree trick. There you can find next line:
const ptree &settings = pt.get_child("settings", empty_ptree<ptree>());
Which shows that it is (or should be... | The property tree iterators point to pairs of the form (key, tree) of type ptree::value_type. The standard loop for iterating through the children of the node at path therefore looks like:
BOOST_FOREACH(const ptree::value_type &v, pt.get_child(path)) {
// v.first is the name of the child.
// v.second is the chi... |
6,656,393 | 6,656,486 | why does ptr_fun find this ambiguous even when template parameters are given? | So, here is some basic code which illustrates my question:
#include <functional>
int func(int x) {
return x;
}
int func(int x, int y) {
return x + y;
}
int main() {
std::ptr_fun<int, int>(func);
}
We have 2 overloads for a function with a different number of parameters. Then I attempt to turn the single... | Its because when you call a templated function, you don't have to specify any template parameters that can be inferred by the type of the function arguments. As a result, calling std::ptr_fun<int, int> doesn't actually specify which of the std::ptr_fun overloads you calling, and it relies on the function you pass as a... |
6,656,490 | 6,656,668 | Split array of chars into two arrays of chars | I would like to split one array of char containing two "strings "separated by '|' into two arays of char.
Here is my sample code.
void splitChar(const char *text, char *text1, char *text2)
{
for (;*text!='\0' && *text != '|';) *text1++ = *text++;
*text1 = '\0';
for (;*++text!='\0';) *text2++ = *text;
*text... | For A, using internal libraries:
void splitChar(const char *text, char *text1, char *text2)
{
int len = (strchr(text,'|')-text)*sizeof(char);
strncpy(text1, text, len);
strcpy(text2, text+len+1);
}
|
6,656,579 | 6,656,648 | How to wait for input from the serial port in the middle of a program | I am writing a program to control an Iridium modem that communicates with a satellite. After each AT command is sent, the modem sends a reply back (depending on the command) to indicate the command was successful.
Right now I have it implemented so that the program just waits 10 seconds between the transmission of eac... | Use select or poll on the file descriptor corresponding to the serial port, which will return when the descriptor is ready for reading.
Something like this:
int fd = fileno(stdin); /* If the serial port is on stdin */
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
struct timeval timeout = { 10, 0 }; /* 10 seconds */
int... |
6,656,835 | 6,656,877 | mmap slower than getline? | I face the challenge of reading/writing files (in Gigs) line by line.
Reading many forum entries and sites (including a bunch of SO's), mmap was suggested as the fastest option to read/write files. However, when I implement my code with both readline and mmap techniques, mmap is the slower of the two. This is true for... | The real power of mmap is being able to freely seek in a file, use its contents directly as a pointer, and avoid the overhead of copying data from kernel cache memory to userspace. However, your code sample is not taking advantage of this.
In your loop, you scan the buffer one character at a time, appending to a string... |
6,656,967 | 6,882,031 | Using RtAudio with Core-Audio, the probeDeviceOpen function fails | I am trying to write a C++ program which plays real-time processed audio. I have decided to use RtAudio but cannot make the test programs play audio.
I am using Mac OS X, so I compiled with ./configure --with-core and make. After compiling the files in the test directory, I ran ./audioprobe to return this list.
Compile... | Are you on Lion (10.7)? I am seeing the same problem, on older systems (10.6.x) RtAudio work fine for me.
Perhaps you can downgrade to RtAudio 4.0.6, this worked for me on Lion, but there's still a bug lurking around with device names which got fixed in 4.0.8.
|
6,657,026 | 6,657,097 | How to pass normal param as well as template param in a template function in C++? | I have a template function (as follows) in a namespace called myNamespace:
template <typename setX>
void getRandomItems(NaturalNumber size, setX &random, setX &items)
{
assert(size <= items.size());
//set of randomly selected indices for items
set<NaturalNumber> index;
NaturalNumber r, i;
while(in... | setX is not a set of NaturalNumbers so the iterators aren't compatible when you say it = index.begin(). You could possibly make it an iterator of set<NaturalNumber> instead, I can't quite make out what you really want to do here.
Also I noticed that in your inner loop you don't do any checks to make sure sit doesn't ru... |
6,657,048 | 6,657,175 | How can I find the number of terminal columns from a C/C++ program? |
Possible Duplicate:
Getting terminal width in C?
On Linux and OS X, my shell reports $COLUMNS has the width of the terminal window -- and resizing the window will adjust this shell variable.
But in my C/C++ program, getenv("COLUMNS") doesn't seem to find the variable.
Anybody have an explanation? Or an alternate su... | Perhaps something like this:
#include <sys/ioctl.h>
#include <stdio.h>
int main()
{
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
printf("lines %d\n", w.ws_row);
printf("columns %d\n", w.ws_col);
return 0;
}
Taken straight from: Getting terminal width in C?
|
6,657,130 | 6,657,156 | Sizeof() on a C++ array works in one function, but not in the other | I'm trying to learn more about arrays since I'm new to programming. So I was playing with different parts of code and was trying to learn about three things, sizeof(). How do I find the length of an array, and also how do I put arrays into functions (as a parameter)?
My code is:
#include <iostream>
using namespace std... | This
void arrayprint(int inarray[])
Is equivalent to this:
void arrayprint(int *inarray)
So you are getting the size of an int pointer on your machine. Even if your question is about C++ and your function looks a bit different, it boils down to this C FAQ entry.
So, inside main n_array is actually a true honest array... |
6,657,139 | 6,659,285 | Neutral Resource-Only DLL | I have an mfc resource only dll's with strings and menus, but i want to have icons and bitmaps only in the main application (MFC exe), i don't want to have the same bitmap/icons in the n resource only dll's, only in the main application.
Is this possible? and if is, how we can accomplish this? (i try to use the neutral... | MFC has a pretty elaborate system for searching the resources of a wide range of extra DLLs beyond the resource DLL you declare (see AfxFindResourceHandle in dllinit.cpp). I suggest putting your language-neutral resources in a separate DLL and treating it like an extension DLL.
Martyn
|
6,657,190 | 6,657,402 | std::map< MyClass, std::vector<MyClass> > Segment fault. Oddness | SOLVED:
Thanks figured it out thanks to dominic hamon.
It all boils down to trying to call a function on a kinda null object. It could use parts of the object but not others.
I had no idea that this could even happen.
Question
I have experienced an odd segmentation fault with a
std::map< IntVector3, std::vector<IntVec... | Using a string to achieve a comparison function is (a) massively inefficient, and (b) broken. It will not provide you a strict-weak ordering, which is what is required for std::map. In particular, it is not going to be transitive, i.e. if a < b and b < c, it won't necessarily give you that a < c. This is going to to... |
6,657,412 | 6,657,509 | FFmpeg extracting current frame time stamp | I need to extract frames in certain interval of the video, (eg from 40 sec to 50 sec).
Working in c++.
First I am getting position where I need to start reading
static double t = 10 ;//time in seconds
int64_t timestamp = t * AV_TIME_BASE; //destination time
av_seek_frame( pFormatContext , -1 , timestamp + pFormatConte... | Try to find frames per second and then use that number to calculate exact time of each frame as
frame_absolute_time = frame_number / FPS
|
6,657,475 | 6,657,687 | netmask conversion to CIDR format in C++ | I have to convert 2 DWORDs, IP address and a network mask to CDIR format...
So I have 2 DWORDs corresponding 1.1.1.1 and 255.255.255.255 and I want to come up with string
1.1.1.1/32
Any thoughts on this?
Thanks
| Since there are a small and fixed number of valid netmasks (32, to be exact), the fastest way is probably to just build a map of masks to prefix length once at init time, and the conversion is just a lookup in the map.
|
6,657,588 | 6,659,357 | Trying to create a class that contains an array of structs, that are predefined | I have a class called CoolMenuItems
class CoolMenuItems
{
public:
CoolMenuItems();
~CoolMenuItems();
struct MenuItemOne
{
int id;
uint32 type;
uint32 subtype;
String name;
};
struct MenuItemTwo
{
uint32 subtype;
String name;
};
}
This is... | Can you modify your code like this
class CoolMenuItems
{
public:
CoolMenuItems();
~CoolMenuItems();
struct MenuItemOne
{
int id;
uint32 type;
uint32 subtype;
String name;
};
struct MenuItemTwo
{
uint32 subtype;
String name;
};
std::vector... |
6,657,832 | 6,657,856 | CString format with Unicode returns wrong character | I'm trying to format a CString using the following code:
const wchar_t * wch = L"μ";
CString str;
str.Format(_T("%c"), wch[0]);
However, instead of str having the value of "μ" it actually is set to "¼". When I debug it, it recognizes wch as "μ".
Further, if I do:
const wchar_t * wch = L"μ";
CString str;
str.Format(_T(... | I believe you need to use a "long" char or string format specifier -- so %lc for the wchar_t and %ls or %S for the string.
|
6,657,858 | 6,657,961 | C++ how to set a fixed decimal precision for a float | I have an API call which returns a double. The double's decimal length can variate from many decimal places to a few (it all comes down to the state of an actuator). This double represents the current position on the range radius of an actuator.
I am not interested in such a detailed number, because it adds alot of noi... | Can't you just round it.
float round(float num, int precision)
{
return floorf(num * pow(10.0f,precision) + .5f)/pow(10.0f,precision);
}
|
6,657,869 | 6,769,105 | Stanford CS106B C++ libraries in XCode 4 | I'm trying to use the Stanford CS106B C++ libraries, like simpio.h and genlib.h. I'm using XCode 4 (this is a beta version btw) and Mac OS X 10.6. I installed the libraries, but they don't seem to be showing up when I try to create a new project in XCode. Is there something different I should be doing with XCode 4 to g... | Yes, multiple versions of Xcode work fine together. During the install, after the "Select a Destination" screen, you see a screen with the packages that will be installed. Click "Developer" folder to change to a custom location for each different Xcode version. The other tools (system and UNIX) cannot be moved.
Afte... |
6,658,252 | 6,658,263 | for loop integrated in the argument field of an if statement in c++ | I am working on solving a mathematical problem.
What I am trying to do is to have an if statement that compares variable n to a set of variables i 1 through 10. Is there any way to do it in c++?
here is what I am trying to do:
int smallPos(int n){
if (n%for(int i=1;i<=10;i++)==0) {
return n;
}
This... | What you want to do is this:
int smallPos(int n)
{
for (int i = 1; i <= 10; ++i)
{
if (n % i != 0) // check if n % i == 0, if not, then we shouldn't return n.
{
return -1; // or whatever you want to return when not ALL the remainders are 0.
}
}
return n; // If we ge... |
6,658,590 | 6,658,623 | c++ template specialization method question | I'm new to C++ and I'm trying to use template but I got problems.
What I'm trying to do is: try to calculate square of a number using template, and the number may be basic data types like int, float, as well as complex numbers. I also implemented a complex class using template, and the codes are as follows:
template <t... | It appears that you're trying to partially specialize function templates, which isn't actually possible in C++. What you want instead is to simply overload the function like this:
template<typename T>
T square(T num) // Overload #1
{
return num * num;
}
template<typename T>
Complex<T> square(Complex<T> num) // Ov... |
6,658,689 | 7,801,187 | clapack.h or Template Numerical Toolkit in Visual Studio 2008 | I want to use the lapack library clapck, but how could I use it in Visual Studio 2008, in a C++ project...
Also I was reviewing Template Numerical Toolkit
Have you done something similar, what do you recommend to use with Visual Studio C++ project?
Can you post a simple example with the headers that must be included?
| TNT is easy enough.
#include "cmat.h"
#include "lu.h"
/*******************************
* PURPOSE: Solves a linear equation in the form of Ax = b.
*****/
using namespace TNT;
void matrix_solve(double V[9], double xb[3])
{
Matrix<double> A(3, 3, V);
Vector<int> ipiv(3);
... |
6,658,788 | 6,658,825 | Can a valid pointer be allocated at address 0? | On any of the 'major platforms' (which I'm defining as Windows, Mac and Linux for the purpose of this question,) is it conceivable for a validly allocated pointer to be allocated at address 0 in a programs address space (therefore messing up comparisons to NULL?)
Does the standard even allow a compiler/platform to have... | The C++ standard allows it, but such a pointer will not compare equal to literal 0 (the NULL pointer constant).
User-mode applications in the major OSes, however, will never have a valid pointer at 0, or even in the range -65536 to 65535 (to help detect offsets from a NULL pointer).
For the most part, 0 as a usable add... |
6,658,981 | 6,659,916 | strange mingw linker errors with boost? | I've been working on this for a while now, and can't seem to make sense of the situation - partly bceause I don't fully understand what's going on (which is why I came here).
I'm doing a sort of boost hello world as follows:
#include <boost/thread/thread.hpp>
#include <cstdio>
void helloworld() {
std::printf("HEL... | Solved the problem. Boost's headers are configured to be dynamically linked, but the dynamic libraries (dll's) are not built unless you specify:
--build-type=complete
when invoking bjam. After that, copy the appropriate dll to your application directory, but still use the
-L/BOOST_DIR/stage/lib -lname
when linking.
|
6,659,236 | 6,661,904 | Design Pattern for Data Structure | This question has been answered, so what follows below is an explanation of what I wanted to achieve.
I wanted to create a tablular data structure designed to allow efficient access to any row entry through a primary column that could possibly be hashed. I thought that the best way to go about this would be to maintain... |
front() should return a reference to a node containing the value_type
Sounds like your thinking of begin instead of front, in STL/Boost terms, except that begin methods usually return iterators instead of references.
How would I be able to use a map of key hashes to std::list::iterator types and allow for addition o... |
6,659,460 | 6,659,510 | Get RAM and CPU usage for process in Linux with C++ | I want to write a program like system monitor.
I want to have a list of programs with their process ID and usage of CPU and RAM.
I know Linux writes this information in the /proc folder but somebody told me that I can use some functions to get it too. For example a program that will return a list like:
name PID RAM... | Why don't you look at the source code for top, which displays these and many more process statistics?
Here is the busybox version, which is comparatively short and simple. It gets the information by reading the proc filesystem, that logic is here.
|
6,659,570 | 6,659,615 | When are includes not needed? | I admit I'm a bit naive when it comes to includes. My understanding is that if you use it in your class you either need to include it or forward declare it. But then I was going through some code and I saw this:
// file: A.cpp
#include "Helper.h"
#include "B.h"
#include "C.h"
#include "A.h"
// ...
// file: A.h
B b;
C ... | When you #include some header (or other) file into a .cpp file, that #include statement is simply replaced by the content of the header file. For example:
//header.h
int i;
float f;
// file.cpp
#include"header.h"
int main()
{}
After preprocessing stage, file.cpp will look like,
int i;
float f;
int main()
{}
Can see... |
6,659,586 | 6,659,801 | C++ HelloWorld not printing correctly | I just installed c/c++ development tools for my eclipse and everything is working except no text is being printed in the console when I run the hello world program, but I receive no errors. I'm really stumped, anyone know why this is?
Edit:
Ok I realized if that debug it, it works correctly, but not if I run it, any i... | Are you using a 64-bit version of Eclipse? If so, that might be your problem. The 64-bit version doesn't do console output. sigh Try downgrading to the 32-bit version.
On SO, check this question.
On the Eclipse forums, check this thread.
|
6,659,819 | 6,660,975 | Using a string in click function of windows form app | Just a curious question.
Is it possible to get the editor to allow the use of strings in a click function of a design project? Say for this function that was created when the click button was created:
System::Void Form1::Calculate_Click(System::Object^ sender, System::EventArgs^ e)
When I try to create a string wit... | Have you tried System::String^ variable_name ?
|
6,659,858 | 6,660,056 | How to find a socket's local port number? (Windows C++) | I'm new to Windows networking, and I am trying to find out which PORT number my socket is bound to (C++, Windows 7, Visual Studio 2010 Professional). It is a UDP socket, and from what I understand, using the following initial setup should bind it to a random available port/address:
sockaddr_in local;
local.sin_family =... | Use getsockname. For example:
struct sockaddr_in sin;
int addrlen = sizeof(sin);
if(getsockname(clientSock, (struct sockaddr *)&sin, &addrlen) == 0 &&
sin.sin_family == AF_INET &&
addrlen == sizeof(sin))
{
int local_port = ntohs(sin.sin_port);
}
else
; // handle error
This also works for *nix-based syst... |
6,659,943 | 6,661,051 | error C2143 : missing ';' before '*' | hello I have searched everywhere on the internet for an answer but i can't find any.
code:
#ifndef GAME_H
#define GAME_H
#include "drawEngine.h"
#include "sprite.h"
#include <iostream>
using namespace std;
class Game
{
public:
bool run(void);
protected:
bool getinput(char *c);
void timerUpdate(void);
pr... | The problem in this case appears to be that Sprite is not recognized as a type. After a better look, the problem you have is that you define:
#ifndef GAME_H
#define GAME_H
//...
#endif
in both files. You do that in the .cpp file(or Game.h file.. first code snippet) and you also do it in the Sprite.h file. The problem ... |
6,659,962 | 6,717,992 | Winsocks Compatability issues | I have a executable that requires ws2_32.dll but requires WS2tcpip.h and only works on Windows 7, doesn't work on XP, haven't tried vista.
This is a serious issue, as you can't run the program without missing DLL files. How can I wrap it all up so I won't have any missing DLL issues? Or compatibility issues at all!
| I just used LoadLibrary and GetProcAddress to find the functions inside of ws2_32.dll, so your standard dynamic function linking. Simple!
|
6,660,189 | 6,660,203 | Interesting issue when attempting to reset pointer | Being that my C++ isn't that great, this may be a really simple/obvious answer, but it sure has me stumped. Keep in mind its kinda late here and I'm a little tired. I got this code here:
void TestFunc(int *pVar)
{
cout << endl << *pVar << endl;
delete pVar;
pVar = nullptr;
}
int main(int argc, char *argv[]... | Because it's being passed by value (i.e. as a copy).
If you want the variable itself to be passed (rather than just its value, which is copied), use
void TestFunc(int *&pVar)
instead.
Note that delete only cares about the pointee, not the pointer. So "deleting" a copy of a pointer deletes the same thing as the origina... |
6,660,366 | 6,660,628 | p2p open source library tcp/udp multicast support | I have a certain application running on my computer. The same application can run on many computers on a LAN or different places in the world. I want to communicate between them. So I basically want a p2p system. But I will always know which computers(specific IP address) will be peers. I just want peers to have join a... | I think you're missing the point of UDP. It's not saving any time in a sense that a message gets faster to the destination, it's just you're posting the message and don't care if it arrives safely to the other side. On WAN - it will probably not arrive on the other side. UDP accross networks is problematic, as it can b... |
6,660,501 | 6,660,602 | Counting overhead due to packing in C (gcc/g++) | I'd like to count/sum up the overhead in an object file due to packing (and, ideally, have gcc minimize it for me).
For example, consider the following structure (32 bit x86, gcc):
struct a {
uint8_t a_char;
uint32_t an_integer
uint8_t another_letter;
};
While the actual data only takes up 6 bytes, the st... | For #1, the reason it's not done is that both the C and C++ standards prohibit structure member reordering.
Yes, struct packing will generally reduce performance. And, as mentioned in a comment, in some cases on non-x86 architectures you can get a SIGBUS if you try to operate on a member.
For #2, yes a perl script migh... |
6,660,533 | 6,660,581 | How to browse folders in C++ or C? | I am implementing a program in C (also in C++) to sort files using threads, I need to implement a GUI in C++ or C to select the file to sort, without indicating the path through input standard (a equivalent of JFileChooser in Java). What tutorials do you recommend? I was reading about Qt but I'm not very familiar with ... | Very simple with QT:
void openFile()
{
QFileDialog::getOpenFileName( this, tr("Open Document"), QDir::currentPath(), tr("Document files (*.doc *.rtf);;All files (*.*)"), 0, QFileDialog::DontUseNativeDialog );
QString filename = QFileDialog::getOpenFileName(
this,
tr("Open Document"),
... |
6,660,577 | 6,661,164 | Libraries available on Android NDK? | Are there any libraries available by default in the Android NDK? If not, can I use any c++/c library, as long as I include it myself?
In particular, I need compression, encryption, regex and sqlite. I was thinking of using zlib, crypto++, sqlite(duh!) and boost, but can use anything else if it is already available.
Als... | First, I think you need to download the NDK package from here: http://developer.android.com/sdk/ndk/index.html and investigate the documentation from the package. I'm sure you will get the answers to most of your questions.
And quick answer to your questions. Yes there are libraries by default in the Android NDK. For e... |
6,660,705 | 6,690,085 | MFC C++: TODO <file description> has stopped working | I have wrote a program which tries to write a file in C:\windows\ directory. I have tested the program in several PCs with winXP, win7 (64 & 32 bit).But when i install it in my client's PC it crashed with the message : TODO ( file description ) has stopped working
Please if anybudy knows any solution then reply me.
| It is quite awesome that you gave your client a "TODO:..." product? Please edit the version info to reflect your product name~
As for crash scenario:
Check if your application really needs Admin rights, if yes, start with "run as admin" and see it it solves the problem.
View the problem details in either "Stopped work... |
6,661,064 | 6,661,120 | How NOT to use virtual inheritance? | I am making a win32 api program. I first created a base class called WinClass and inherited like a dozen other classes from it. Now I need to create a derived class from two classes inherited from base class WinControl and WinHandler.Since I intend to make many more derived classes out of the original dozen, I'll have ... | Learn how to avoid overuse of inheritance at all. For example, read this article
http://berniesumption.com/software/inheritance-is-evil-and-must-be-destroyed/
A good start to learn how to get things done the way you want it (with the correct use of inheritance) is the book "Design Patterns":
http://c2.com/cgi/wiki?Desi... |
6,661,306 | 6,661,522 | Apple GUI programming | I'm looking for a tutorial/guide on GUI programming in c++ for Mac OSX.
I've made a small library and would like to make a simple graphic interface for it, since I would like to port my code someday I would like to do the programming in c++.
I know about Qt, but would like to know how apples does it. As I understand i... | My advice:
Avoid Carbon -- it is a legacy technology. You will not get good support for modern releases of the OS, or for 64 bit targets -- and then you'll have a bunch of code to rewrite once you want to support recent releases.
First, get comfortable with Cocoa APIs. Cocoa interfaces (e.g. AppKit) are written in Obje... |
6,661,493 | 6,661,523 | C++ equivalent of Java's Linked List / C#'s Array List? | Is there an STL container or something else that gives the same functionality as Java's Linked List or C#'s Array List? i.e appending different types into the same array like
List.Append(1);
List.Append("I am a string");
List.Append(True);
and dynamic functions like
List.Resize();
List.GetSize();
etc.?
If not , can u... | It's hard to implement this using templates because templates assume a single type for members. In C++ you'll have to use polymorphism with a common source (which is available in Java and C# as a common "Object" parent for all the classes, IMHO).
You can try to do it using the boost library, and the boost::variant or b... |
6,661,633 | 6,661,740 | Advice about the Encryption Method I should Use | Ok, so I need some advice on which encryption method I should use for my current project. All the questions about this subject on here are to do with networking and passing encrypted data from one machine to another.
A brief summary of how the system works is:
I have some data that is held in tables that are in text fo... | I see no reason to use asymmetric crypto in your case. I see two decent solutions depending on the availability of internet access:
Store the key on a server. Only if the user of the program logs in to the server he gets back the key to his local storage.
Use a Key-Derivation-Function such as PBKDF2 to derive the key ... |
6,662,499 | 6,663,693 | Usinfg CImg lib with Qt for faster image resizing. Is It worth it to dig? | My project is to batch resize a big number (30000) of small jpeg images (400*300) to 15 different destination sizes (which are smaller than the source).
I first created a multi-threded command line tool based on CImg and libjpg to batch process the images. And is worked as a charm on my 4*2 cores Ubuntu notepad (20 min... | If it will run faster is difficult to tell without measuring (though I would guess it is), but it is nonetheless a good idea.
Create a interface (API not GUI) for your command line tool, build the gui parts in Qt and call the API of your image resizing backend from it.
This is a good (I would even call it a fundamenta... |
6,662,611 | 6,662,672 | C++ No main() function? | I'm a graduate programmer and when it comes to C++ I expect there to be a main() function everytime.
However I've been given a project written in C++ with Visual Studio 6.0 and it doesn't have a main() function. I really can't figure out how this program executes or where it begins.
I have seen examples of the Macro th... | Maybe the main function is in a library, and the program startes with a virtual function call on a static object. That's what happens in MFC-applications.
The program derives a class from CWinApp and instanciates it once as a static variable. MFC then knows a pointer (that was set up by the constructor of CWinApp, a... |
6,662,626 | 6,662,941 | Advice on STL data structure | I am implementing a display algorithm where we can have multiple layers of windows based on their z-order i.e. I start with the last z-value and merge the images until we have the image with the z-value as 0 at the top.
To maintain the z-values which data structure do you recommend?
For eg: If the z-order is 2 3 4 5 1... | Given that the number of windows is probably going to be minimal, I would probably go with a vector of (smart) pointers, and reorder the vector components. While the complexity is greater than with other alternatives, the actual performance will not be bad, as the constants might dominate the complexity.
|
6,662,917 | 6,663,142 | In what ways member functions may be compared to each other? | I would like to know if I can compare 2 member functions with the "<" operator. I can do "==" but I can't use it in the case below. I tried casting them to void* but that won't work either.
template <class Receiver, class Sender>
class CallBack2 : public ICallBack2 {
protected:
Receiver* receiver;
void(Receiv... | If you just want to arbitrarily order them to be keys in a set/map, then you can reinterpret_cast them. You may need a template class like exact_int<sizeof(void (Foo::*bar)())>::type because pointers to member functions can have funny sizes.
|
6,662,998 | 6,663,026 | Access struct inside struct fails | I have a struct A that is defined as follows:
typedef struct A
{
CvRect B; // rect
int C;
double D;
}
A;
...
In my main program, I grab one item of a sequence of items:
A *r = (A*) cvGetSeqElem(X, i);
Whenever I try to access rect, I get one of the following errors:
if (r.rect.width>100 && r.rect... | r is a pointer to `struct A, which contains a (non-pointer) member B (supposedly rect?) to a CvRect. So you have to write
r->rect.width
|
6,663,068 | 6,663,098 | Code Blocks and Thread Priority | When I put code in blocks, like so:
{
f1();
f2();
}
Does it GUARANTEE that those two functions will be called after one another by the CPU regardless of what other processes are running?
The reason I ask is because f1, in my case, does something with the OS, then f2 relies on the the OS being in th... |
Does it GUARANTEE that those two functions will be called after one another by the CPU regardless of what other processes are running?
Yes. If those functions spawn threads or whatever, they may run in different orders. But the actual code for those functions will be executed in order.
If you're talking about access ... |
6,663,131 | 6,663,172 | reading a line from ifstream into a string variable | In the following code :
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string x = "This is C++.";
ofstream of("d:/tester.txt");
of << x;
of.close();
ifstream read("d:/tester.txt");
read >> x;
cout << x << endl ;
}
Output :
This
Since >> operat... | Use the std::getline() from <string>.
istream & getline(istream & is,std::string& str)
So, for your case it would be:
std::getline(read,x);
|
6,663,230 | 6,663,270 | what's the alternative of set object = null in C++ like C# | I have a function something like:
MyClass1 mc1, mc0; //Single Object
MyClass2 mc2; //vector of MyClass1
mc1.Init(1);
mc2.Add(mc1);
mc1 = mc0;
mc1.Init(2);
mc2.Add(mc1);
mc1 = mc0;
//so on......
I actually want to set mc1 = null before at the beginning of the step but cannot do that in C++. So I kept a never-initiali... | This has nothing to do with whether the language is managed or not, but rather with C++' different approach to object references. In C#, the declaration MyClass mc; would produce a variable that may refer to a MyClass or be null. In C++, MyClass mc; produces a variable that is a MyClass - the object instance is wholly ... |
6,663,666 | 6,663,744 | When should I use templates instead of inheritance, and vice versa? | In many situations, the question doesn't even ask itself, since sometimes inheritance provides necessary features which templates can't provide. For example, when I need to address different types via one base-type (polymorphism), I need to use inheritance.
However, there are some instances where the problem can be sol... | If you know during compile-time what objects you're going to manipulate, then static polymorphism with templates is often the fastest way to go, and it produces code that's a little bit more concise (no need for explicit inheritance). It can also be more generic as you're not restricted to a strong class hierarchy.
If ... |
6,663,811 | 6,663,867 | Basic C++ inheritance challenged by my compiler? | #include <iostream>
class Base
{
public:
virtual void ok( float k ){ std::cout<< "ok..." << k; }
virtual float ok(){ std::cout<< "ok..."; return 42.0f; }
};
class Test : public Base
{
public:
void ok( float k ) { std::cout<< "OK! " << k; }
//float ok() { std::cout << "OK!"; return 42; }
};
int main()... | It's called name hiding, any derived class field hides all overloaded fields of the same name in all base classes. To make the method available in Test, add a using directive, i.e.
using Base::ok;
somewhere in the scope of Test. See this for more information.
|
6,664,022 | 6,664,228 | How to make an animated png from bmp files? | How can I convert 1.bmp 2.bmp ... n.bmp (each 24 bpp) into a single mng or apng file (with animation) in bash/cpp?
| This program can create APNG from TGA/PNG sequences:
http://sourceforge.net/projects/apngasm/files/
|
6,664,115 | 6,664,177 | Is nullptr not a special keyword and an object of std::nullptr_t? |
Possible Duplicate:
What exactly is nullptr?
I first thought it's a keyword. My present gcc doesn't highlight nullptr in a different shade. To verify that, I wrote following:
void *&p = nullptr;
So I got some clue from the error that:
error: invalid initialization of non-const reference of type ‘void*&’
from an ... | It is a keyword, the standard draft says (lex.nullptr):
The pointer literal is the keyword nullptr. It is a prvalue of type std::nullptr_t.
the nullptr is not yet a pointer, but it can be converted to a pointer type. This forbids your above assignment, which is an assignment to an unrelated reference type, in which c... |
6,664,116 | 6,670,978 | Codeblocks and Qt -- how to work with them? | I am new to codeblocks and Qt. I would like to create some nice interfaces with buttons, lists, combo box and so on using Qt. Can someone help me, give me some links from where I can start my journey? I didn't find anywhere how to include qt designer in codeblocks in order to work with it.
Any help is appreciated.
P.S ... | When you have Qt Creator, you don't need anything else unless you have any specific preference for Code::Blocks or any other IDEs.
Qt Creator has an integrated debugging interface too (somewhat similar to Visual Studio).
Here is the Qt Creator manual and here you can find details on How to manage projects using Qt Crea... |
6,664,471 | 6,664,790 | "Observable behaviour" and compiler freedom to eliminate/transform pieces c++ code | After reading this discussion I realized that I almost totally misunderstand the matter :)
As the description of C++ abstract machine is not rigorous enough(comparing, for instance, with JVM specification), and if a precise answer isn't possible I would rather want to get informal clarifications about rules that reason... | The important bit is that the compiler must be able to prove that the code has no side effects before it can remove it (or determine which side effects it has and replace it with some equivalent piece of code). In general, and because of the separate compilation model, that means that the compiler is somehow limited as... |
6,664,686 | 6,664,763 | A C++ library for IIR filter | Do you know of some C++ library that implements IIR filters? I need something similar to Matlab's filter(B,A,X) function. Although it is not necessary, I would prefer an implementation of the IIR direct form 2.
| There's octave, an open-source MatLab clone, you could use its implementation (but it will likely require you use use its special matrix type).
Searching for "C++ IIR filter" finds a bunch of other projects, such as:
Signal Processing using C++
dspfilterscpp
There are also a variety of books on the subject, for examp... |
6,664,769 | 6,664,892 | Where will I find WOW64... defines on my setup (VS 2005 on Vista 64, C++) | I got a project from the web. The "solution" and the "projects" files were coded for VS2010 but I changed the version numbers and I could load them in my VS2005. I tried to build the solution and I get errors like:
'WOW64_CONTEXT': undeclared identifier
'wow64Context': undeclared identifier
'Wow64GetThreadContext': is ... | In the docs, see that "Minimum supported client: Vista" section.
You'll need a recent version of the Windows SDK that covers Vista, and also need to define the WINVER and _WIN32_WINNT macros to 0x600 or higher to enable Vista functions. The documentation is here and Raymond Chen gives some history on his blog.
Curren... |
6,664,850 | 6,664,912 | Namespaces and scope visibility issue | I made a header file sampleheader.h with following code:
namespace sample_namespace
{
int add(int n1,int n2)
{
return (n1 + n2);
}
}
Now my main.cpp file is:
#include <iostream>
#include "sampleheader.h"
using namespace std;
int add(int n1, int n2)
{
return (n1 + n2);
}
int main(void)
{
usi... | "using namespace" does not hide other implementations. What it does in this case is make it ambiguous.
You have both sample_namespace::add and ::add with the same signature. Since you don't explicitly say which one to use, the compiler can't tell.
Declaring both functions is legal and unambiguous (which is why the co... |
6,664,914 | 6,664,935 | Why does friend class crash on static function call? | #include <iostream>
using namespace std;
class CClass
{
private:
friend class CFriend;
static void privateFunc(){std::cout << "privateFunc" << std::endl;};
};
class CFriend
{
public:
void privateFunc(){privateFunc();};
};
int main(int argc, char* argv[])
{
CFriend b;
b.privateFunc();
return 0;
}
... | You've created infinite recursion:
void privateFunc(){privateFunc();};
Use instead:
void privateFunc(){CClass::privateFunc();};
There's nothing wrong with friend declaration.
|
6,665,284 | 6,665,939 | Boost ASIO async acceptor not opening a listening port | OS : linux 64 bit ARCH.
BOOST : 1.46.1
COMPILER : clang++ / GCC.
I have a code fragment that has the wire up of a tcp acceptor modelled on a boost::asio example (Chat Server). However, when I run the fragment, No listening TCP socket shows up in a netstat listening(linux) . However, the chat server example, when compil... | I found that I could get this to work on my Windows machine if I changed the endpoint and acceptor to shared pointers, and instead of creating them by passing them as arguments in the constructor, I specifically created the shared pointers inside the constructor. I'm not exactly sure why this works. My only guess is th... |
6,665,535 | 6,669,265 | Changing the taskbar text without using SetWindowText | I know SetWindowText would set the taskbar text, but it would the titlebar's text also (to be the same text), and I want to have different texts for the titlebar and the taskbar. So I'm looking for a function that would change the taskbar text only.
By taskbar text I mean this:
| The first paragraph in the "Managing Taskbar Buttons" section of MSDN page on The Taskbar suggests creating an invisible window with the WS_EX_APPWINDOW style that can be used to control the taskbar button and then creating a visible window that is a child of the invisible window that contains all of your content.
|
6,665,550 | 6,666,156 | Two questions related to virtual functions | I was reading this articles , was at this heading
Inheritance of Base-class vPtrs , but couldn't understand what did he mean in this para :
"However, due to multiple inheritance, a class may indirectly inherit from many classes. If we decide to merge the vtables of all the base classes into one, the vtable may become v... | With regards to your first question, I don't really follow what the
quoted passage is getting at; it actually sounds like the author doesn't
really understand how vtables work (or hasn't thought about it in
detail). It's important to realize that when we speak of
“merging” the base and the derived classes' vtables, we... |
6,665,554 | 6,666,131 | Unit/integration testing time sensitive C++ code | Is there a way to create unit/integration tests that not only test for correctness, but also test that steps were completed within a specific time period?
For example:
// MyTestSuite.h
#include <cxxtest/TestSuite.h>
class MyTestSuite : public CxxTest::TestSuite
{
public:
void testTimeCriticalFunction(void)
... | In general it is not a good idea to place specific timing requirements such as that at a small granularity. Since you are using OSX you have at most a soft real-time system. (If you have hard real-time requirements a general purpose OS such as OSX is not the answer.) There are a limited number of CPUs / CPU cores avail... |
6,666,259 | 6,666,747 | How to get Windows thread pool to call class member function? | I want the Windows thread pool (QueueUserWorkItem()) to call my class' member functions.
Unfortunately this cannot be done directly by passing a member function pointer as an argument to QueueUserWorkItem().
What makes it difficult is that more than one member function must be callable and they have different signature... | This might help.
You can use tr1::function () and tr1::bind to "coalesce" various calls:
#include <iostream>
#include <tr1/functional>
using namespace std;
using namespace tr1;
class A
{
public:
void function(int i) { cout << "Called A::function with i=" << i << endl; }
};
void differ... |
6,666,280 | 6,666,583 | template class with static data member used across DLL/SO | Suppose I have such a template class:
template <class T>
class Queue
{
public:
static int Size;
};
template <class T> int Queue<T>::Size = 0;
And I export a function in D.dll use Queue as an parameter:
void ChangeQueueSize(Queue<int>& q)
{
q.Size = 100;
}
And then I use this exported function in an A.exe:
Qu... | You cannot put templates in a library in the way you might think. You can only put actual, instantiated class definitions in a library.
Templates are essentially a code generation tool, and you can only put generated code into the library.
You might want to use explicit template instantiation to make the compiler gener... |
6,666,300 | 6,666,851 | Limit the number of instances with the new keyword | I've been reading a lot of debates about whether the Singleton pattern is good/bad/ugly, and what should be used instead of it.
The common implementation requires an Instance() method that invokes a private constructor if the object has not yet been created.
My question doesn't really fit the Singleton pattern, but wou... | Objects can be allocated statically, on the stack, and within other objects. If you want just one instance, you need to disallow all of these somehow. Overloading operator new won't help you with this. Making the constructors private or protected will, but this will disable operator new for the users of the class as we... |
6,666,381 | 6,666,938 | C++ music playback on Mac | is there an simple and lightweight C++ solution for playing music (aac, or mp3 or m4a) on the MAC OSX platform?
i found the SDL and OpenAL, but they are just to heavy for simple music playback
(the music is intended to be a background music for a game)
thank you
| If you want just music playback and only for osx, I did a little mini-lib that uses the system provided routines to play. Available from here: https://github.com/scoopr/auplay
|
6,666,387 | 10,718,147 | How to use CssStyleProvider in Gtkmm3 | I'm programming in c++ with gtkmm3. I want to change some fonts in my program. I read all the things about CssStyleProvider, StyleContext in gtkmm documentation and also in gtk+ documentaion but i couldn't make it work and couldn't find any tutorial about that. I'm trying like that
Glib::ustring data;
data="GtkMenuBar,... | Have you also to tried to use the macro GTK_STYLE_PROVIDER_PRIORITY_APPLICATION instead of 0?
asd2->add_provider(screen, asd, macro GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
Works for me, also on Windows.
Example:
int main(int argc, char **argv) {
Main app(argc, argv);
Glib::ustring data = "GtkLabel {color: #ff00... |
6,666,413 | 6,666,458 | Need of privatizing assignment operator in a Singleton class | Can someone justify the need of privatizing the assignment operator in a Singleton class implementation?
What problem does it solve by making Singleton& operator=(Singleton const&); private?
class Singleton {
public:
static Singleton& Instance() {
static Singleton theSingleton;
return theSingleton;
}
priv... | Assignment on a singleton is simply a nonsense operation since only one object of it should ever exist.
Making the assignment operator private helps diagnose nonsense code such as the following:
Singleton& a = Singleton::Instance();
Singleton& b = Singleton::Instance();
a = b; // Oops, accidental assignment.
|
6,666,979 | 6,669,555 | Eclipse Helios CDT: ignore build directory | We use Eclipse Helios CDT for development. We use cmake as build system, build dirs are typically called build-* inside the project directory.
How do I get the indexer and the refactoring tool to ignore the build directories?
| Exclude these build dirs from project tree by adding Resource filters. Add Exclude All resource filter type to root folder of your project. You can also use regular expressions if needed.
|
6,667,176 | 6,667,629 | iterating encapsulated nested STL containers | Here's a fairly normal encapsulation of an STL container which allows the user of Cfoo to iterate the container without allowing changes to the innards.
#include <vector>
class Cfoo
{
public:
class Cbar
{
/* contents of Cbar */
};
typedef std::vector<Cbar> TbarVector;
typedef TbarVector::c... | None of the standard iterators are able to iterate over more than a single container, so your assumption is correct - you'll have to write a custom iterator.
It is possible to do this in a generic fashion, if you have an intermediate iterator that returns pairs of (begin,end) iterators to the inner containers.
Some unt... |
6,667,326 | 6,667,665 | Access Violation while using _tcstok | I am trying to tokenize lines in a file using _tcstok. I am able to tokenize the line once, but when i try to tokenize it a second time, I get an access violation. I feel like it has something to do with not actually accessing the values, but locations instead. I'm not sure how else to do this though.
Thanks,
Dave
p.s.... | First up, your code is a mongrel mixture of C string manipulation and C++ containers. This will just dig you into a hole. Ideally you should tokenize the line into std::vector<std::wstring>
Also, you're very confused about TCHAR and UTF-8. TCHAR is a character type that 'floats' between 8 and 16 bits depending on comp... |
6,667,341 | 6,667,417 | linker stage: undefined reference | I already read like 15 of the undefined reference topics here and used google too to find a valid answer, but there was non that really helped.
I wrote a 1D and 2D simple storage class which allows rapid loop through by directly accessing the data (plus some convenience accessors). Here the 1D goes (2D is pretty much t... | Where have you defined?
Multi1<voCam*>::operator[](int) const
Ah ok, You have it, You should have template declaration and definition in the same header file.
|
6,667,449 | 6,667,517 | Is it possible to retrieve the argument types from a (Functor member's) function signature for use in a template? | Assume you have a functor:
struct MyFunctor
{
bool operator ()( int value )
{
return true;
}
};
Is it possible to retrieve a functor's member's argument type for use within your template? The following is a use of this mythical functionality:
template < typename FunctorType >
bool doIt( FunctorType... | No there is not. The most elegant way to do this would be to either require your functors to provide a typedef for the argument-type, or to introduce a traits-class. The latter is useful if you want your template to work with functors and functions.
Alternatively, you can just make the argument type a second template p... |
6,667,732 | 6,667,815 | standard multivariate normal random vector using Boost::random | I would like to generate random points on a 2D surface, distributed around a x0, y0 coordinate.
I understand that what I need to generate is called "standard multivariate normal random vector", but I don't know how to do it in C++, for example using the Boost::random library.
I know there is an algorith for generatin... | It seems to be:
// deterministic Box-Muller method, uses trigonometric functions
template<class RealType = double>
class normal_distribution
{
But Box-Muller isn't 2D. All you really have to do to get the 2D version is to take the two random numbers generated and add them to the x0, y0 coordinates.
|
6,667,965 | 6,668,498 | Selecting the path file for QTableWidgetItem qt | Hi I'm trying to get a path name to link to the image viewer but it wont link the error is on
path = (currentDir.absoluteFilePath(item->text()) );
can anyone help me.
created in qt c++
void Window::open(int row, int /* column */)
{
QTableWidgetItem *item = filesTable->item(row, 0);
QString path;
... | replace
item->text()
with
(item->data(Qt::DisplayRole)).toString();
and see if that works. I m not sure.
Copy this entire line and replace with urs. U misplaced the brackets thats why u were getting error.
path = currentDir.absoluteFilePath(( item->data(Qt::DisplayRole) ).toString());
|
6,668,025 | 7,597,177 | Improving Makefile performance generated from qmake | Our Qt 4.5 project has a root .pro file that has a SUBDIRS qmake variable. When qmake is called on this root .pro file, it generates a Makefile that calls "qmake && make" for each sub directory.
Now the problem is that for 100+ sub folders, this takes a long time for a one liner change of an other wise up to date proj... | This is a classic argument for the recursive make considered harmful theory: Your problem is that you have dozens of single Makefiles instead of one large one. The only way around the predicament is to refactor the .pro files so that only a single Makefile is generated. I don't know enough about qmake to tell you how t... |
6,668,106 | 6,668,164 | C++ pointer casting when passing pointer as parameter to reference | I'm curious, is:
bool State::operator<(const State* S)
{
return this->operator<(*dynamic_cast<const State *>(S));
}
exactly the same as:
bool State::operator<(const State* S)
{
return this->operator<(*(S));
}
For reference the this->operator< being called is:
bool State::operator<(const State& S)
{
return this-... | No, the first one casts the pointer to itself, which doesn't really do anything, and then calls const State* overload, which results in an infinite loop. You don't need dynamic_cast until you need to downcast at runtime — there is no downcasting here, so
return this->operator<(*S);
is the only thing to do.
|
6,668,282 | 6,668,700 | srand(time(NULL)) generating similar results | I don't understand why srand() generates so similar random numbers between runs!
I am trying to run the following code
srand ( time(NULL) );
int x = rand();
cout << x << endl;
However instead of a proper random number I always end up with almost the same number, which is growing slowly as the time goes. So I get numbe... | First, srand() isn't a random function; it sets up the starting point
of a pseudo-random sequence. And somewhat surprisingly, your
implementation of rand() seems to be returning a value based on the
previous state, and not on the newly calculated state, so that the first
value after a call to srand() depends very much... |
6,668,284 | 6,668,318 | How to hide ampersand | In Qt when I ie name a label '&label' this means that letter 'l' will be underscored after I press 'Alt' button. And that works. Is there a way as to make this underscore dissapear after some action has been executed?
| Just name it 'label' as the action is executed
|
6,668,824 | 6,669,741 | Caching huge data in Process memory | I am working in Finance Industry. We want to roll out Database hit for data processing. It is very costly. So we are planning to go for on-demand cache logic. [ runtime insert & runtime lookup ]
Is anyone worked in implementation of Caching logic for more than 10 million of records?. Per record is say about 160 - 200 b... | If your cache is a simple key-value store, you should not be using std::map, which has O(log n) lookup, but std::unordered_map, which has O(1) lookup. You should only use std::map if you require sorting.
It sounds like performance is what you're after, so you might want to look at Boost Intrusive. You can easily comb... |
6,669,033 | 6,669,129 | c++ waiting for thread exit | I wrote a program in C++ under Linux. For thread I am using pthread.
In the program I start the thread and this thread is running until I call the function, that should stop it. Here you can see my code.
bool isRunning = false;
pthread_t thread;
void startThread() {
isRunning = true;
int thread_return = pthre... | From what I understand in your question, you should be using the concept of thread joining.
Like so,
bool stopThread() {
int returnCode;
isRunning = false;
void *status;
rc = pthread_join(your_thread, &status);
// wait until the thread will be finished
if (rc) {
printf("ERROR; return c... |
6,669,078 | 6,669,502 | Purpose of uppercase VOID macro & INT typedef in winnt.h | Anyone any clue as to why there is an uppercase VOID macro defined in the winnt.h header?
To make matters more confusing, VOID is a macro, whereas CHAR, SHORT, INT, and LONG are typedefs.
See the relevant excerpt from winnt.h:
#ifndef VOID
#define VOID void
typedef char CHAR;
typedef short SHORT;
typedef long LONG;
#if... | The original reason is that the Win32 API was originally supposed to be language independent, so they made up their own names (following their naming convention), and then provided a C implementation of that. In reality, much of what they defined tends to be ignored by most people using other languages (and largely eve... |
6,669,117 | 6,669,444 | g++ optimizing lowercase to uppercase - bug? | I'm encountering a very strange problem using g++ 4.1.2. I have a very basic program that opens a serial port and writes data to it. The port is opened & setup using following commands:
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
struct termios port_settings;
cfsetispeed(&port_settings, B115200);
cfsetos... | This is because you are basically setting the terminal parameters to random values.
To get more meaningful behavior, first interrogate the serial port's settings and then change the items as you see fit:
struct termios port_settings;
if (tcgetattr (fd, &port_settings) != 0)
return -1;
cfsetispeed(&port_set... |
6,669,176 | 6,669,219 | How to code a selector? | I am working on a algorithm but there is a note about a selector. I am not sure what this means but the research paper I am working says:
δ () is a selector, i.e. δ (x) =1 if x>0, else
δ (x) = 0 ;
How does one code this using pseudo code, c++, or Java?
Thanks
|
δ () is a selector, i.e. δ (x) =1 if x>0, else δ (x) = 0
You just need an if
In pseudocode:
delta = function(x)
{
if (x > 0)
return 1
else
return 0
}
|
6,669,229 | 6,669,248 | When will C++ call the constructor on an object that is a class member? | let's say I have a class
class MyClass {
public:
AnotherClass myObject;
};
My issue is that I want to initialize myObject with arguments to it's constructor, exactly if I were declaring it on the stack during a function
AnotherClass myObject(1, 2, 3);
but I want to do this for the class member in the cons... | Use the ctor-initializer. Members are initialized after base classes and before the constructor body runs.
MyClass::MyClass() : myObject(1,2,3) {
...
}
|
6,669,297 | 6,669,787 | Measure Render-To-Texture Performance in OpenGL ES 2.0 | Basically, I'm doing some sort of image processing using a screen-sized rectangle made of two triangles and a fragment shader, which is doing the whole processing stuff. The actual effect is something like an animation as it depends on a uniform variable, called current_frame.
I'm very much interested in measuring the ... | Concerning speed, using glDrawArrays() still duplicates the shared vertices.
glDrawElements() is the solution to reduce the number of vertices in
the array, so it allows transferring less data to OpenGL.
http://www.songho.ca/opengl/gl_vertexarray.html
Just throwing that in there to help speed up your results. As fa... |
6,669,475 | 6,669,793 | How to compile a .dll for MSHTML v9. I'm currently getting 100s of "MIDL 2035: constant expression expected" errors | I'm a .net developer and I'm trying to compile a .tbl and .dll for MSHTML v9 for use in my .net applications.
I found the following instructions for building a MSHTML v8 .dll:
start menu -> Windows SDK 7.1 Command Prompt
cd c:\temp
midl "C:\Program Files (x86)\Microsoft SDKs\Internet Explorer\v8\include\mshtml.idl"
t... | #include <mshtmdid.h>
#include <mshtmcid.h>
#include <olectl.h>
First couple of lines from mshtml.idl. The mshtmdid.h header file defines the constants. This file is also present in the Windows SDK include folder but that's an old version. You need to correct the INCLUDE environment variable so it looks in the Inte... |
6,669,499 | 6,669,525 | Socket Programming Under Visual Studio 2010, Non-Managed C++ |
Possible Duplicate:
Socket Programming for Windows C/C++
I am trying to understand what my options are for doing socket programming in C++ (non-managed) under Visual Studio 2010. Please note that one constraint I have is that I cannot use a third-party library. I must use only the capabilities provided directly by V... | The only way of doing it in Windows is using the Win32 Socket API (which is indeed POSIX compatible, for better or for worse). Both MFC and the .NET implementations are just wrappers around it.
If you can go higher level than just a socket though, say to the TCP or even HTTP (or FTP) levels, there are alternatives like... |
6,669,551 | 6,669,750 | Converting string macros/constants to wide characters/Unicode | I have a Unicode Win32 application that uses 3rd party libraries, some of which provide constants for their version information as #defined (narrow) strings. For instance, libpng has the following:
#define PNG_LIBPNG_VER_STRING "1.5.4"
#define PNG_HEADER_VERSION_STRING \
" libpng version 1.5.4 - July 7, 2011\n"
I'm... | The trick is to use two macros. When a macro is expanded, the arguments are macro-expanded before being substituted into the replacement list. So WIDEN(VERSIONSTR) becomes WIDEN2("Test V1.2.3").
#define WIDEN(quote) WIDEN2(quote)
#define WIDEN2(quote) L##quote
#define VERSIONSTR "Test V1.2.3"
#define VERSIONSTRW WIDEN... |
6,669,600 | 6,669,751 | approximating circle with given number of segments | Is there better way to calculate circle from radius and num of vertices?
My solution compute sin and cos for every vertex. Is it necessary?
void getCircle2D(Vector2 * perimeterPointsArray, int32 numOfPoints, Vector2 & center, flt32 radius)
{
ASSERT(numOfPoints >= 3);
flt32 pieceAngle = MathConst::TAU / numOfPoi... | Your suggested approach should be the usual method to do it. But maybe you can come up with an iterative computation using the following addition theorems (see Wikipedia):
sin(a+b) = sin(a)*cos(b) + cos(a)*sin(b)
cos(a+b) = cos(a)*cos(b) - sin(a)*sin(b)
Where in your case a is the previous angle (whose cos and sin you... |
6,669,610 | 6,673,036 | Call to WinHttpCreateUrl with ICU_REJECT_USERPWD flag set working in Windows 7 but not Windows XP (using Virtual PC) | I've been getting unexpected errors when running the app I'm developing in Windows XP (under Virtual PC from Windows 7). I'm compiling it using Visual Studio 2010 in Windows 7 64-bit Professional.
I've tracked the problem down to URLs not being created properly under XP. The following is a small test bed I put togeth... | I can't get WinHttpCrackURL to work with the ICU_REJECT_PASSWORD flag on XP.
Starting with the msdn example
http://msdn.microsoft.com/en-us/library/aa384092(v=vs.85).aspx
ICU_DECODE and ICU_ESCAPE work fine if you set the buffers.
However passing in ICU_REJECT_PASSWORD always results in a fail and GetLastError return... |
6,669,733 | 6,669,799 | Choosing specific objects satisfying conditions | Let's say I have objects which look very roughly like this:
class object
{
public:
// ctors etc.
bool has_property_X() const { ... }
std::size_t size() const { ... }
private:
// a little something here, but not really much
};
I'm storing these objects inside a vector and the vector is rather smal... | Your last choice is always a good one. Our intuitions about how code will run are often wrong. So where possible profiling is always useful on critical code.
|
6,669,753 | 6,670,158 | Declare static variable inside a function call in C++ | I have a C++ program with many thousands of string literals in the code which need to be translated, for example:
statusBar->Print( "My Message" );
I wrapped the string literals with a function which looks up the value in a dictionary and returns the translated version:
statusBar->Print( Translated( "My Message" ) );
... | I/O time needed to print your message should be several orders of magnitude more than any dictionary lookup time. If this is not the case, you are doing something wrong.
Tried and tested software is available that does what you need. I suggest you either study GNU Gettext, which is used by every other FOSS project out... |
6,669,789 | 6,669,877 | Can't write to file in a loop containing sleep() | The essence of my problem is that I can't write to a file in a loop with sleep(). If I have the following code:
ofstream file
file.open("file.name");
for(;;) {
file << "HELLO\n";
}
This code works perfectly and prints HELLO repeatedly into "file.name". However, I want to do something like this (I'm recording data... | You need to flush the output. The output stream is buffering your data into memory but not writing it out to disk. You should either use std::endl (which prints a newline and flushes) instead of the string literal '\n', or explicitly flush the stream with std::flush:
for(;;) {
file << "HELLO" << endl;
}
// or
for... |
6,669,838 | 6,670,115 | Top K smallest selection algorithm - O (n + k log n) vs O (n log k) for k << N | I'm asking this in regards to Top K algorithm. I'd think that O(n + k log n) should be faster, because well.. for instance if you try plugging in k = 300 and n = 100000000 for example, we can see that O(n + k log n) is smaller.
However when I do a benchmark with C++, it's showing me that O (n log k) is more than 2x fas... | Big O in several variables is complex, since you need assumptions on how your variables scale with one another, so you can take unambiguously the limit to infinity.
If eg. k ~ n^(1/2), then O(n log k) becomes O(n log n) and O(n + k log n) becomes O(n + n^(1/2) log n) = O(n), which is better.
If k ~ log n, then O(n log ... |
6,669,959 | 6,698,627 | MPI with thread support and Bcast calls | I was wondering if in an MPI program where you specify that there is thread support, all the threads make an MPI::Bcast call (making shure that in the call, the sender process only possesses one thread), is this received by all the other threads or just for one thread from each process (the fastest)?
| Common MPI implementations deal with communication among processes. Implementations supporting threads simply allow multiple threads to make some or all MPI calls, rather than just one. Every one of T threads in a process calling MPI_Bcast means that the process has called MPI_Bcast T times, and expects that all of the... |
6,669,987 | 6,670,035 | How do I create a timer run my program repeatedly? C++ | I want create timer in my program so that I can cause it to rerun every minute and I don't know how to do it in a C++ Application. In C# I could just create a timer but I'm struggling here now...
sleep(); is not an option because as far as I know it makes your program inactive for X seconds, I need my app to be active ... | I suppose you work on Windows, since you mentioned C#. So take a look at SetTimer, and if it is a MFC app, then look at CWnd::SetTimer.
|
6,670,113 | 6,670,238 | Shared Library Object File Linkage | I'm interested in solutions for the question below for Linux and Windows, GCC, MinGW, and MSVC (if possible).
I have an application that I've written that supports user-defined shared library imports (add on modules). The application scans a directory, finds *.dll files or *.so files, and loads them dynamically at runt... | Create a library with the code you want to share between the user module and your program.
Now the user program and your program can link with this new library.
|
6,670,284 | 6,670,370 | static member explicit definition | Consider this code:
#include<iostream>
using namespace std;
class Wilma
{
public:
static int i;
Wilma()
{
cout<<"\nWilma ctor\n";
cout<<"\ni::"<<i<<"\n";
}
};
class Fred
{
public:
Fred()
{
cout<<"\nFred ctor\n";
}
... | Wilma has no non-static fields. Fred::wilma_=w; doesn't do anything.
edit
If there are no non-static members - there's no copy. Basically the assignment was a no-op and might just been optimized out by the compiler, and the linker never saw it. Adding a non-static member made the copy to be an actual operation that ref... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.