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,777,131
7,777,152
Can't read Serial Input
I have an Arduino hooked up via usb to my computer. From it I try to read the from the COM port. Can anyone see if theres anything blatantly wrong with this??? void main() { int exitStatus; unsigned int bytesToRead = 1; unsigned char *buffer = (unsigned char*) malloc(sizeof(unsigned char) + 1); Seri...
You are not evaluating the exitStatus variable, which might indicate it the read was successful. Also you don't need to malloc memory if you want to read just one byte, you can simply pass the pointer to a local char variable. And while I'm at it, the type for main is either int main() or int main(int argc, char** argv...
7,777,242
7,777,316
determine power of number
i know that if number is power of two,then it must satisfy (x&(x-1))=0; for example let's take x=16 or 10000 x-16=10000-1=01111 and (x&(x-1))=0; for another non power number 7 for example, 7=0111,7-1=0110 7&(7-1)=0110 which is not equal 0,my question how can i determine if number is some power of another numbe...
For arbitrary k there is only the generic solution: bool is_pow(unsigned long x, unsigned int base) { assert(base >= 2); if (x == 0) { return false; } unsigned long t = x; while (t % base == 0) { t /= base; } return t == 1; } When k is a power of two, you can speed things up by checking whether x...
7,777,276
7,777,297
In OOP, Private membes are private for who?
In OOP why need to put something Private , for example. I know that any private member can not be accessed but with the same class objects. But why I need to do that while I am the only coder of my project. The same question extends to Protected, protected from who!
private and protected are not there to prevent other coders from accessing the internals of a class, but (also) to prevent yourself from creating a program without clearly defined interfaces. If every class in your project can modify every other class, you're not only prone to introduce bugs because of the huge state s...
7,777,827
7,777,856
Is it possible to change the comparator of a C++ std::set?
I have a set of data which in some occasion I need to sort them in one way and some occasion in another way. For example, suppose the data set is a set of strings,{"abc", "dfg",...}. Sometimes I need to sort them in alphabetic order and sometimes by comparing their length. Initially I used std::set as a container of my...
You have to specify the comparator of std::set at construction time. As a solution, I would maintain two 'index' sets instead, each referring to the actual collection. This would yield the greatest flexibility. To keep everything together, I suggest you wrap it up in a single class: // to be compiled, debugged etc......
7,777,965
7,777,989
Why does this occur?
Given the following code: class TestA { private: char Temp; public: char *Ptr; TestA(){Ptr = NULL; Temp = 'A'; Ptr = &Temp;} void Function(){Ptr = &Temp; Temp = 'B';} void operator=(const TestA &ItemCopy) { //ItemCopy.Temp = 'N'; //Not permitted ...
Because ItemCopy is const, ItemCopy.Ptr has and effective type of char * const. The pointer is const but the item pointed to can be modified. This means that the assignment: *ItemCopy.Ptr = 'M'; is meaningful and allowed (the underlying object is not itself const), it is also legal to copy the pointer and assign throu...
7,778,149
7,778,222
Compiler unable to find valid library path
I'm getting the following error: ld.exe||cannot find -lD:\Libraries\boost_1_47_0\boost_1_47_0\stage\lib| Even though the path is valid. Any thoughts on that? Edit: Thanks MichalR! For others, in order to configure boost for gcc: Download boost install it according to instructions from boost site In code::blo...
The params for ld are e.g.: -larchive -Lsearch_path The first tells what library to look for, the latter specifies library search paths. Perhaps you have these options mixed in your command line - it looks you have -l with a directory parameter.
7,778,392
7,778,447
Colorize stdout output to Windows cmd.exe from console C++ app
I would like to write something similar to cout << "this text is not colorized\n"; setForeground(Color::Red); cout << "this text shows as red\n"; setForeground(Color::Blue); cout << "this text shows as blue\n"; for a C++ console program running under Windows 7. I have read that global foreground & background can be ch...
You can use SetConsoleTextAttribute function: BOOL WINAPI SetConsoleTextAttribute( __in HANDLE hConsoleOutput, __in WORD wAttributes ); Here's a brief example which you can take a look. #include "stdafx.h" #include <iostream> #include <windows.h> #include <winnt.h> #include <stdio.h> using namespace std; int ma...
7,778,452
7,778,472
missing ';' before identifier
I get these errors when I compile this. I can not find out the error. Specially why ; is required and why function templates are already defined. I am using Visual Studio 2010. This works with Turbo C++ but I want to know why these errors comes with Visual C++. Error 1 error C2146: syntax error : missing ';' before...
Say std::fstream file; instead of fstream file;, because fstream is declared in the Standard namespace std, not in the global namespace. In the .cpp file corresponding to FileOp.h you may choose to say using namespace std; in that .cpp file if you don't want to type std:: everywhere in that file (it's basically a ques...
7,778,473
7,778,475
in C++ what does this code means?
I was working on linked lists and found a sample. In that sample it says while (currNode && index > currIndex) so here, whats the boolean value of currNode?
It most likely means currNode != NULL. In C++ everything not 0 (thus including everything not NULL) is considered true in boolean contexts.
7,778,889
7,778,959
What is the C++ standard library equivalent for mkstemp?
I am transitioning a program that uses temporary files from POSIX FILE to C++ standard library iostreams. What's the correct alternative to mkstemp?
There is no portable C++ way to do it. You need to create a file (which is done automatically when opening a file for writing using an ofstream) and then remove it again when you're finished with the file (using the C library function remove). But you can use tmpnam to generate a name for the file: #include <fstream> #...
7,779,034
7,779,057
In C++ is there something wrong including in this way?
In my program I have classes for Vertex's Edges and Faces which I'll hopefully use to model shapes. Previous to this my Edge class included my "vertex.h" file and my Face class included my Edge.h file. In the Face class I declared some edge type variables and in the Edge class I declared some variables of type vertex. ...
You have a circular reference; if you only need to refer to pointers or references to Face in Edge.h, then you can forward-declare Face instead of including Face.h: class Face; Think about how inclusion works: if you were to paste the contents of Face.h in Edge.h, and then the contents of Edge.h in Face.h, you would h...
7,779,140
7,779,302
Reading and writing a buffer issues
bool CReadWrite::write(unsigned long long offset, void* pvsrc, unsigned long long nbytes) { int m_WriteResult; pFile = fopen("E:\\myfile.bin","wb"); if (!pFile){ puts("Can't open file"); return false; } fseek(pFile,SIZE_OF_FILE-1,SEEK_SET); fwrite(pvsrc,1,1,pFile); fseek...
Here are the problems I see: You fopen the file with "wb", which would truncate the file if existing or create a new one if not existing. So how do you expect to seek to 20th byte? Where is SIZE_OF_FILE set or more importantly is it set correctly? Suggestions: Never forget to check the return codes of all functions y...
7,779,204
7,779,489
using makefile in QT creator
I have a C++ project which uses Makefile,now i want to use QT creator for development but I do not want to touch the Makefile, Is there any way QT creator with an existing Makefile.
When you make a new QT Creator project, you are able to edit the make file in the program. I haven't not had any trouble with adding in my own files, libraries ect. into it, from another, non-QT project. If you want to avoid the make file all together there is an import function in the GUI to bring in outside files, ...
7,779,354
7,779,383
C and C++ interface
why it is much more difficult to provide wrappers in other languages to C++ code as opposed to C code ?
This varies significantly by the library itself and how its designed. Speaking very generally, C++ is more complex in that it has objects, classes and interfaces, where C is primarily functions. Member functions of a class are named and called differently, so wrapping them takes a bit more work to provide equivalent n...
7,779,468
7,779,531
Alphabetic Linked List Not in Order
I'm trying to create a linked list that is sorted by both name and rating. The rating sort part puts everything in the right order, but for some reason, the alphabetic sort doesn't put anything in the right order (or even in reverse order). Sometimes, the alphabet sort part of List::Insert breaks the printByRating() fu...
It seems you are comparing const char* pointers instead of comparing their contents. Use strcmp or std::string to compare strings lexicographically.
7,779,469
7,779,747
C++ match string in file and get line number
I have a file with the top 1000 baby names. I want to ask the user for a name...search the file...and tell the user what rank that name is for boy names and what rank for girl names. If it isn't in boy names or girl names, it tells the user it's not among the popular names for that gender. The file is laid out like th...
First off, looks like you're trying to open a rich text format file (.rtf). This won't work, as the file doesn't contains only text but also other data (http://en.wikipedia.org/wiki/Rich_Text_Format). Then in your code: while(getline(input,line1)) reads a line every iteration. That's fine, but inside the loop yo do inp...
7,779,482
7,779,527
boost::asio async_read doesn't receive data or doesn't use callback
I am trying to receive data from a server application using boost asio's async_read() free function, but the callback I set for when the receiving is never called. The client code is like this: Client::Client() { m_oIoService.run(); // member boost::asio::io_service m_pSocket = new boost::asio::ip::tcp::socket(m_oI...
boost::asio::service::run () is a blocking call. Now, in your example it may or may not return immediately. In case it doesn't, you you are blocked even before you create a socket, and never call read, so cannot expect a callback. Otherwise, dispatch loop is exited, so no callbacks are ever delivered. Read more about b...
7,779,638
7,779,660
C++ Accessing private vector values
I'm doing a restaurant management program. Right now I'm trying to output private vector data and am getting stuck. So I have a Menu.h private: vector<Category> categories; vector<Menu_Item> menu_items; vector<Recipe> recipes; vector<Ingredient> ingredients; vector<Order> orders; vector<Order_Item> order_items; And Me...
You have to make menu_items public or make a public getter function like the following. public: vector<Menu_Item> get_menu_items(){ return menu_items;} Then say if you had a Menu object of this type called Menu you can do this: if(Menu.get_menu_items()[0].menu_item_name == "Onion Rings") The other possible option...
7,779,653
7,787,543
Openssl need to use CA bundle file (Intermediate cert)
I just purchased a SSL certificate from Go Daddy. Great price, but it seems that it has a draw back. It seems to need the bundle.crt in order to work correctly on must browser. I'm not yet really sure what it is, from what I have understand it is an intermediate certificate from Certificate Authority. Correct me if I'm...
Okay, after testing one million things I finally found out. I didn't convert the bundle.crt into PEM. I have pasted the certificate file directly in the bundle.crt (at the beginning of the file) I have removed this line on my code : SSL_CTX_use_certificate_file(SSL_ctx, _certificate, SSL_FILETYPE_PEM); So here's the ...
7,779,798
7,779,841
how to read the formatted file in C++
I have the following format. Each line has two integers and the file is ended by "*". How can I read the two numbers from the file. Thanks. 4 5 7 8 78 89 * //end of file Edit I know read the two numbers but do not know how to deal with "*". If I store each number as integer type and read them by cin. But The last li...
You can simply pull the numbers from the ifstream object until it fails. std::ifstream fin("file.txt"); int num1, num2; while (fin >> num1 >> num2) { // do whatever with num1 and num2 }
7,779,827
7,779,871
Why is copy constructor not being called in this code
So why is Copy constructor not being invoked in "const Integer operator+(const Integer &rv)" function. Is it because of RVO. If Yes what do I need to do to prevent it? #include <iostream> using namespace std; class Integer { int i; public: Integer(int ii = 0) : i(ii) { cout << "Integer()" << endl; ...
Is it because of RVO. If Yes what do I need to do to prevent it? Yes. But it didn't get called because of Return Value Optimization by the compiler. If you're using GCC, then use -fno-elide-constructors option to avoid it. GCC 4.6.1 manual says, -fno-elide-constructors The C++ standard allows an implementation to om...
7,779,860
7,779,905
How to read contents of file into string in C++
I want to read the all the contents of a file into a string or some other method that would allow me to compare two files. I am looking for files that are exact matches. Just a little snippet of how I am opening the file and read how many characters it has. which I use to compare to other files to check if it is necess...
Use a memory mapped file for this. With UNIX mmap() With Windows MapViewOfFile(). This will give you a pointer in memory that maps to the contents of the file. Why is this a good idea? You don't need to allocate space for the file using malloc() or new(). The files can be any size, ok 32bit limit, but there should be a...
7,779,899
7,779,968
static const std::array in class
I have a templated struct with some enumerations in it and I'd like to make a std::array with the enumerations in it for convenience. Is there any way of doing the following? template< typename A > struct someClass{ enum class State{ sA, sB, sC } static const std::array<State,4> the...
No. Only static const integral data members can be initialized within a class. However, you could do this... template< typename A > struct someClass { enum State { sA, sB, sC }; static const std::array<const State,4> the_states; }; template<typename A> const std::array<const so...
7,779,900
8,862,379
Why is template argument deduction disabled with std::forward?
In VS2010 std::forward is defined as such: template<class _Ty> inline _Ty&& forward(typename identity<_Ty>::type& _Arg) { // forward _Arg, given explicitly specified type parameter return ((_Ty&&)_Arg); } identity appears to be used solely to disable template argument deduction. What's the point of purposefully ...
If you pass an rvalue reference to an object of type X to a template function that takes type T&& as its parameter, template argument deduction deduces T to be X. Therefore, the parameter has type X&&. If the function argument is an lvalue or const lvalue, the compiler deduces its type to be an lvalue reference or cons...
7,779,936
7,779,953
How to call a function when using a map constructor?
I found this code at here. How does the compiler know to use the function defined in classcomp? struct/function struct classcomp { bool operator() (const char& lhs, const char& rhs) const { return lhs<rhs; } }; Map Construction map<char,int,classcomp> fourthm; Constructor Prototypes from link ab...
It uses the default-constructor for classcomp class so you get an object that has operator() defined and acts like a function.
7,779,938
7,780,328
Weird difference in callstack between release and debug
I'm trying to walk the stack of this sample program: #include <windows.h> void Func1() { Sleep(1000); } void Func2() { Sleep(1000); Func1(); } void Func3() { Sleep(1000); Func2(); } void main() { for (int i = 0; i < 100; i++) { Func3(); } } In debug mode I get what you'd exp...
The function was inlined. I simply change the "Inline Function Expansion" to Only_inline (in VS2008) and the missing function appears. :)
7,780,072
7,780,145
When to use printf/scanf vs cout/cin?
I'm testing some snippets I found off the web using g++ from MinGW. This is the C++ compiler...why then does it correctly compile C....why do people intertwine C and C++. The concrete question is: Is it O.K. to use both C and C++ and compile under g++. If the answer is yes, this makes my life easy as I do not have ...
There are a few oddities where char* is needed. You can bridge the gap by using the .c_str() method of a std::string to get one. For the most part, the C subset of C++ is compatible. Exactly how it isn't compatible is not likely to matter for the most part: http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B ...
7,780,232
7,789,915
Test structure for Containers
I want to build a test structure to test arrays, vectors, lists, maps, and unordered_maps. Basically I want to populate each structure with a large amount of random data. I want to run 3 tests on these. I want to be able to see the Big O trends for insert and search. Question is should I store the random data set in...
The text file versus generating the data in the code is really up to you... As far as STL limitations you can use vector::max_size which would also give you a good benchmark for arrays since vectors are dynamic arrays. This function also exists for lists and maps. The key here is whether or not you intend to also measu...
7,780,245
7,780,273
Calling iterator constructor from another class
I am trying to write graph class as a template class. As answered in Question, I was trying to implement graph in term of std::set , here is what I have wrote till now. #include <set> template <class T, class Container = std::set<T> > class graph { public: class iterator { ...
I think you want to provide iterators for your graph class, and graph's iterators are nothing but the iterators of the underlying container type. If so, then you should actually be doing this, template <class T, class Container = std::set<T> > class graph { public: typedef typename Container::iterator iterator; ...
7,780,279
7,780,962
De-interleave an array in place?
Lets say I have an array of interlaced data, such as 1a2b3c4d5e, and I want to de-interlace it into an array that looks like 12345abcde, in place (without a temporary buffer). What would be the fastest way of doing this? What I have so far is this template<typename T> void deinterlace(T* arr, int length){ if(length<=...
This is essentially a matrix transposition problem. Your array [1 a] [2 b] [3 c] [4 d] is equivalent to 1, a, 2, b, 3, c, 4, d if represented as a vector (by reading rows first). The transpose of this matrix is: [1 2 3 4] [a b c d] which is equivalent to 1, 2, 3, 4, a, b, c, d. There is a wikipedia page that deals w...
7,780,370
7,780,429
Create Bitmap in C# from char[] buffer
I've got to interface my C++ project with a C# project and send an image to it across a named pipe. OpenCV stores matrix data in a contiguous chunk, starting at uchar* Mat::data. However, to send data across a named pipe, it must be a char*, so I just do a cast, not sure what else I'm supposed to do. It shouldn't matte...
The use of a StreamReader here seems like the wrong choice if what you're sending is actually binary data. The StreamReader is used for reading text, and will decode the data to characters with some encoding which in your case would be auto-detected (and definitely wrong). You want to use the BinaryReader for reading b...
7,780,560
7,780,634
Local variables in assembly:are they faster than global variables?
I was wondering if local variables in assembly are faster than the global variables that we use. The context for this is that I am learning some 2d animation using the win32 api, from a book. The author uses a function to initialize(Creation,registration, showing and updating of the window) the main window for the pro...
The top of the stack is touched by a lot of code. That means the the top of the stack is usually in CPU cache. Accessing this would be faster than accessing other memory areas (from .bss, etc). But for a function like CreateWindow which is called only a few times per program this doesn't really matter. The differen...
7,780,640
7,780,653
How to use sort to sort a vector in a class
I was wondering how I can use the sort function to sort a vector which is private in a class: #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; class A{ private: const vector<int> myvec; A(vector<int>& vec) : myvec(vec) { } public: const vector<int>& getve...
You declared myvec as const -- how would you expect to modify it? Declare myvec as: vector<int> myvec;
7,780,746
7,785,340
How to control the connect timeout with the Winsock API?
I'm writing a program using the Winsock API because a friend wanted a simple program to check and see if a Minecraft server was running or not. It works fine if it is running, however if it is not running, the program freezes until, I'm assuming, the connection times out. Another issue is, if I have something like this...
Your code does not skip the label update. The update simply involves issuing window messages that have not been processed yet, that is why you do not see the new text appear before connecting the socket. You will have to pump the message queue for new messages before connecting the socket. As for the socket itself, the...
7,780,749
7,780,899
Waiting on multiple semaphores without busy-waiting (C/C++ Linux)
If I have more than one semaphore, how can I have a process block until at least one of the semaphores is free? I know I can do this with a busy-wait loop such as: // blocks until one of the semaphores in sems is free, returns // index of semaphore that was available int multiple_sem_wait(sem_t **sems, int num_sems) { ...
Here (developers.sun.com, via the Internet Archive) is a short paper from Sun about how they implemented their WaitForMultipleObjects emulation in Solaris. The basic idea is to associate a list of condition variables to a handle (protected by a mutex), and signal all of the condition variables whenever the handle is si...
7,780,918
9,251,920
std::uniform_int_distribution<int> range in g++ and msvc
While doing a minor school project, I just noticed a difference in the range of std::uniform_int_distribution<int>: When using g++ the range is [a, b], however when using msvc (Visual Studio 2010) the range is (a, b], so the output of the following program: #include <iostream> #include <random> using std::cout; using ...
It's a bug in the Visual Studio 2010 implementation of std::uniform_int_distribution. I reported it here in December 2011 and got confirmation from Stephan T. Lavavej that: It is indeed a bug. It's been fixed in the next version of Visual Studio (including the current Developer Preview). The bug occurs when the first...
7,780,934
7,781,105
Memory access and cache
When is the CPU Data Cache updated? Take these situations as examples: Example 1: SomeObject* pObject; //[...] pObject->member = variable; Example 2: SomeObject object; object.member = variable; How is cache updated in those examples? Is it the same? Or are there differences in terms of data access because example ...
In example 1, CPU first needs to access the pointer itself, then the actual object. Pointer is on the stack which gives it a good chance it is already in data cache due good locality with other variables on the stack. It might even be in register. It is unusual for the object to be on the same stack frame as pointer -...
7,781,188
7,781,200
Static variable for object count in c++ classes?
I would like to have a static member variable keep track of the amount of objects that have been made. Like so: class test{ static int count = 0; public: test(){ count++; } } That doesn't work because, according to VC++, a member with an in-class initializer must be constant. So I ...
Put static int count; In your header in the class definition, and int test::count = 0; In the .cpp file. It will still be private (if you leave the declaration in the header in the private section of the class). The reason you need this is because static int count is a variable declaration, but you need the definitio...
7,781,256
7,828,939
How I can prevent every key being sent to KeyboardUpFunc in GLUT?
I'm fairly new to OpenGL, and I am writing a simple game in 2D, for fun. However, I ran into an issue I am having a hard time wrapping my head around. It seems that whenever my keyboardUpFunc is called, that not only the key that has actually come up sent to the function, but every single key currently being pressed as...
I changed my implementation of the keyboard buffer, and what I was describing above now works. The difference is that before I was using a vector to pile on the keys that were being pressed, whereas now, I am using a fixed-size array of boolean values. Apparently, a vector implementation of a key buffer won't work prop...
7,781,292
7,781,528
C++ - When to exactly use ->? Error: base operand of ‘->’ has non-pointer type ‘BaseBond’
Getting some really confusing errors and not sure exactly why. Here is my code: //=====================WORKS======================= TradingBook::TradingBook(const char* yieldCurvePath, const char* bondPath) { //...Some stuff BaseBond* tradingBook[bondCount]; for (int i=0; i < bondCount; i++) { trad...
It because this: BaseBond* tradingBook[bondCount]; in the constructor constructs a scoped variable that hides tradingBook. change that whole line to: tradingBook = new BaseBond*[bondCount]; and the line BaseBond* tradingBook; in the header to BaseBond** tradingBook; and it should work.
7,781,302
7,788,969
OpenCV on ubuntu 11.10
I've just updated my system from ubuntu 11.04 to 11.10 and now I can't compile anymore any C program that contain references to OpenCV libraries I've already tried to reinstall OpenCV (I use the 2.1 version) but I'm stuck with this error: /tmp/ccArHTZL.o: In function `main': z.c:(.text+0x59): undefined reference to `cv...
Why don't you use pkg-config to your favor? g++ hello.c -o hello `pkg-config --cflags --libs opencv`
7,781,334
7,781,433
An error when removing a file using remove() function
I have problem with remove() function First, look at the example and you will see the problem cout << "Please enter the phone number to remove" << endl << "Phone number: "; string rphNumber; cin >> rphNumber; ifstream ifile("db/" + rphNumber + ".txt"); if(ifile) remove(("db/" + rphNumber + ".txt").c_str()); // the pr...
Your problem may be that you still have ifile open at the point where you try to remove it. Some operating systems don't let you delete a file that's open. Another possibility is that the string rphNumber might have a newline at the end which you need to strip off before assembling the filename. (I don't remember if...
7,781,390
7,781,460
iphone game runs on devices. crash on specific level in simulator
i have developed a game that is currently running on iphone/ipad/ipod touch without any problems. recently i needed to run it on the simulator, and i found that it crashes on a specific load function when starting one of the levels, i went to the crash report in user/Library/Logs/DiagnosticReports and saw that abort() ...
A close bracket means the destructor of some local variable. For example: struct Test { ~Test() { throw "error"; } } int main() { int b; { Test a; }; //On your stack trace, here it will be pointed as the error line. b = 1; };
7,781,410
7,781,438
HW Help: get char instead of get line C++
I wrote the code below that successfully gets a random line from a file; however, I need to be able to modify one of the lines, so I need to be able to get the line character by character. How can I change my code to do this?
Use std::istream::get instead of std::getline. Just read your string character by character until you reach \n, EOF or other errors. I also recommend you read the full std::istream reference. Good luck with your homework! UPDATE: OK, I don't think an example will hurt. Here is how I'd do it if I were you: #include <str...
7,781,449
7,781,554
Errors trying to call GetAsyncKeyState() in C++/CLI project
I'm working on a fairly convoluted project in which I'm accessing classes written in plain-old-C++ from a project using C++/CLI. It's a Windows Forms GUI project that uses a lot of the same functions as its (non-CLI) C++ sister project. In one of my classes that I'm trying to adjustment to work in both environments, I...
The MSDN library provides the details of which header files and libraries need to be included for any particular function. In this case, you need windows.h (which you must already have) and user32.lib (which is probably missing). So add #pragma comment(lib, "user32.lib") at the top of your code and all should be well...
7,781,463
7,781,476
What is Member templates?
Can i call a member template, template template member function? or how can I know to call it member template and how does it make sense? For example: For case A: I have a class, if I make its member function a template member function, would i call it a member template? For case B: I have a template class, If I make i...
For both cases you call it member template. template<typename T> struct A { // this is not a template void f(); // but this is a member template template<typename T> void g(); }; It's a member template because it's a member that is a template. The member function f is not a template, but is a member function...
7,781,746
7,781,755
Efficient way to implement a bounded string formatting operator for use with <<?
I'm looking for something where: string pearString ("pear"); string bananaString ("banana"); cout << ???? 5 ??? pearString ??????? << "[end]" << endl; cout << ???? 5 ??? bananaString ??????? << "[end]" << endl; Will (for some sequence of code characters ???) output: pear[end] banan[end] But I'd like this to work wit...
Why not just use the write member function of ostream: cout.write(bananaString.c_str(),5); Perhaps surprisingly, you can even put this at the start of an insertion chain. Taking your example as a basis, you can use the following somewhat convoluted chain: cout.write(bananaString.c_str(),5) << "[end]" << endl;
7,781,747
7,781,766
Safe Message Queue with multiple threads
Here is what I essentially have: I have thread A that periodically checks for messages and processes them. Threads B and C need to send messages to A. The problem arises when B and C or B or C try to send a message to A while A is processing a message and thus accessing the queue. How is this problem usually solved? Th...
This is normally solved using mutexes, or other multi-thread protection mechanisms. If you are working on windows, MFC provides the CMutex class for this problem. If you are working on a posix system, the posix api provides the pthread_mutex_lock, pthread_mutex_unlock, and pthread_mutex_trylock functions. Some basic ps...
7,781,771
7,781,777
I want to get multi line by using string data type not char type
Look at the examples to see what do I want string name cin >> name; This example does not allow spaces or multi line char name[20]; cin.getline(name,20); This example allow spaces and multi line My question: I want to using string data type with getline function or other function work with string data type allows mu...
There's a global getline function that works on strings. string name; getline(cin,name); You can get multiple lines by specifying a terminating character other than '\n' getline(cin,name,'#');
7,781,796
7,782,282
read input data gzipped file line by line
I am acquainted that some folks have already written about this question; however, this question is not clear to me yet. I need to read gzipped files which contain unformatted data. I have unsuccessfully tried following instructions from zlib and gzstream sites. Could anybody provide me a quick example of how to extrac...
if you know how to link in gzstream, you can do that just replace "ifstream" with "igzstream" .
7,781,849
7,781,891
Where should I put this enum?
Here is my situation: C sends an A.message to mediator B then B passes it on to A. So essentially, C absolutely does not even need to know anything about A. The problem is it needs to know what messages it can send which is defined in an enum inside of A. This means C needs to $include A to know about the enum. Shoving...
Define the enum in a separate file, say D, and in both C and A #include D
7,781,850
7,781,859
About "undefined refence to" in C++
=) I have a question about "undefined reference to" in C++. Here in this code i have the next: #include "HelloWorldAgent/helloworldagent.hh" int main() { HelloWorldAgent agent; agent.run(); } In another C++ file is the next code: #ifndef _HELLOWORLDAGENT_HH_ #define _HELLOWORLDAGENT_HH_ #include "../../Humanoi...
You have not included the implementation (definition) to the virtual functions in HelloWorldAgent. Make sure you pass whatever file has those definitions to G++ at the same time as the rest (or use -c to compile one at a time to .o files, then link them together in a final link step)
7,781,898
7,782,037
Get an istream from a char*
I have a char* and the data length that I'm receiving from a library, and I need to pass the data to a function that takes an istream. I know I can create a stringstream but that will copy all the data. And also, the data will surely have 0s since it's a zip file, and creating a stringstream will take the data until th...
Here's a non-deprecated method found on the web, has you derive your own std::streambuf class, but easy and seems to work: #include <iostream> #include <istream> #include <streambuf> #include <string> struct membuf : std::streambuf { membuf(char* begin, char* end) { this->setg(begin, begin, end); } }; ...
7,781,941
7,782,463
Canonical relation operators (==,<,...)
Consider a struct (as in: stupid aggergation of several members) with members that all implement a certain relation R (e.g. <): struct X { A a; B b; }; For most operators there exists a canonical definition for X R X. For instance: bool operator<(X const& x1, X const& x2) { if ((x1.a < x2.a) || (x2.a < x1.a)) //...
As apparently there is no non-boost solution, I brewed up some template magic, which I am posting as an answer in case somebody has the same problem; Version 1: explicit arguments namespace multioperator { enum LazyBool { LB_false = false, LB_true = true, LB_undefined }; template <typename Cmp, type...
7,782,081
7,782,106
Indefinite amount of generic types in template?
I want to make a custom print function that takes any amount of arguments and prints them all on new lines. In javascript, the document.write and console.log functions can do this because javascript stores all arguments in an array. To my knowledge, c++ doesn't do this and can't because of type restrictions. So is th...
You can use a variadic function, similar to printf, but you will still need to know the types of the arguments and how many there are to be able to access them properly. A better approach would probably be to do something similar to how the << operator was overloaded for ostream or use a chainable function. You will in...
7,782,094
7,782,100
Struct Giving Incorrect Output
When I compile this code, I get an output of 10 when it should be 0. #include <iostream> struct player { int hp; int dmg; }; void dealdamage(player x, player y) { y.hp = y.hp - x.dmg; } int main() { player p1, p2; p1.hp = 10, p1.dmg = 10; p2.hp = 10, p2.dmg = 10; dealdamage(p1, p2); std::cout << p2.hp <<...
That's because you're passing the player structs in by value. When the parameter is passed by value, a copy is made into the called function. So whatever changes you make in the function won't affect the original. So your statement: y.hp = y.hp - x.dmg; Only affects the local copy of x and y. Which falls out of scope ...
7,782,183
7,783,260
linux path in fstream
i try to create a new file and save it in a subdirectory of the current folder ON LINUX the path(convert) should look something like markus/123456 where markus is an (existing) subdirectory and 123456 is the non existing file the strange thing is: it works when i dont use a subdirectory to say it short: "123456" ...
mkdir(name.c_str(),0600); This is wrong. Try mkdir(name.c_str(), 0700);
7,782,207
7,782,234
What are unit tests and such?
I've noticed the features for making tests in Visual Studio 2010 and Netbeans 7 and was wondering what they do exactly. Would using them be more efficient than designing my own tests?
A unit test (as opposed to an integration test) is a test (usually actually multiple tests that happen to exist in the same class and file) that test the functionality of a single unit (typically a class). An integration test, by contrast, tests the interactions of multiple different units. An end-to-end test is a part...
7,782,223
7,782,249
Problems overloading the << Operator
I am trying to overload the << operator for my Currency class but I get this compiler error: C2143: syntax error : missing ';' before '&' In my .h file I have: friend ostream &operator << (ostream &, const Currency&); And in my Currency.cpp file I have: ostream &operator << (ostream &stream, const Currency &obj)...
ostream is declared in namespace std and you are missing std:: identifier before it: std::ostream &operator << (std::ostream &, const Currency &); If you want to avoid std:: then after header file you can put using namespace statement: ... #include<ostream> using namespace std; // this is not desirable though in real...
7,782,343
7,782,369
Details of C++ Constructor Syntax
This is almost a duplicate question, but I really didn't understand the answer given for the other one, so I am going to try again: I am learning C++ and I an trying to understand the various options for creating and using constructors. So my first question is what is the difference between these two object creations: ...
The two declarations Example example2 = Example(5); Example example3(5); are equivalent. Although the first one looks like it might create an object and then invoke the copy constructor, most compilers will simply create the example2 object in place. The decision about when to choose which of the above styles to use i...
7,782,385
7,782,442
Problems overloading the >> Operator
I have the following block of code trying to overload the >> operator: istream &operator >> (istream &stream, const Currency &obj){ cout << "Dollars: "; stream>>obj.dollars; cout<< "Cents: "; stream>> obj.cents; return stream; } But when I call cin>>newMoney from my main program it keeps repeating "DOLLARS...
There is no enough information in your code (as of now). Till you post more code, all I can say is this, which is also important for you to note down: since you overload >> to take input, the object obj should be passed by non-const reference, so remove const from the second parameter, and make it look like this: istre...
7,782,413
7,782,428
Trying to Read a Line of Keyboard Input in C++
I mam trying to complete a college assignment in C++ and am having trouble with what should be a very basic operation. I am trying to read a string of characters from the keyboard. This is the relevant code: string t; cout << endl << "Enter title to search for: "; getline(cin, t, '\n'); I understand, that the ...
The reason that the input operation apparently is skipped, is most probably (that means, ignoring possible peculiarities of a bugsy XCode IDE) that you have performed some input earlier and left a newline in the input buffer. To fix that, make sure that you have emptied the input buffer after each input operation that ...
7,782,482
7,801,941
What is an effective way to organize C++ projects that are going to be unit tested?
I am wondering what would be an effective way to organize C++ projects and classes that are going to be unit tested. I have read many SO posts related to unit test but couldn't find practical examples. Here are some ways I have collected: Method A Project A: Application (.exe) project that "include" the classes from P...
I have previously used the first method quite well. Have most of your code in a static library project, have the main executable project just contain the main function, and have your tests and the test main function in a third project. The two executable projects will link to the static library and reuse the code. The ...
7,782,513
7,789,834
Classes, namespaces and inheritance help for D&D game
So for class we have to make a D&D 3.5 game, and for the first assignment I have to generate a Fighter character. The way I have the hierarchy set up in my head is character.cpp and it's child is classname.cpp where it has some attributes specific to the class since all classes share the same basic things. Is that a go...
Here's my best stab at answering you... A good inheritance structure is very context specific, but the basic principle is a base class contains data and functions relevant to all the derived classes. Derived classes will contain specific data and functions to itself. In your case there will be a lot of data in the base...
7,782,577
7,782,776
How do I fix "ambiguous overload" error when overloading operator<< (templated)?
I am trying to overload the << operator, but I get the following error: error: ambiguous overload for 'operator<<' in 'std::cout << "Test "' ..Followed by 5 billion other errors similar to: c:\mingw\bin../lib/gcc/mingw32/4.5.2/include/c++/ostream:165:7: note: candidates are: ... This comes up because I'm using co...
Your function has the same signature than the one already defined. This is why the compiler moans about ambigous overload. Your function tries to define a function to stream everything to a ostream. This function already exists in the standards library. template <typename T> std::ostream& operator<< (std:: ostream& o,...
7,782,741
7,782,768
Template template parameter on function
Is this valid template construct in C++ templates? template < template <typename T2> class T> void foo() { }
Yes. It is valid. You can call this function with any class template which takes exactly one template parameter. For example, template<typename T> struct A { //... }; foo< A >(); //ok Note that you don't have to provide the template argument for A class template, which means, the following would result in compil...
7,782,847
7,782,860
Thread-safety of sub-word-size flags
Consider the following scenario: There exists a globally accessible variable F. Thread A repeatedly assigns a random value to F (without any regard to the previous value of F). Thread B does the same thing as thread A (independent of A). Thread C repeatedly reads the value of F (and say, prints it). This is in C++ (V...
It depends on your thread-safety requirements. You'll always get a consistent value (that is, it is impossible that you get half the value of thread A's write and the other half from thread B), but there is no guarantee that the value you'll read is, in fact, the latest one that was logically written. The problem here ...
7,783,176
7,783,188
error C2039: 'Open' : is not a member of 'std::basic_fstream
When i call void fileOpen(const char* fname_){file_.Open(fname_,ios::in|ios::out|ios::ate|ios::binary);}; Function like tempobj->fileOpen("LastID.dat"); It gives me the error Error 23 error C2039: 'Open' : is not a member of 'std::basic_fstream<_Elem,_Traits>' How do i resolve this. This is the class I have thi...
C++ is case sensitive. You need to use open() instead of Open().
7,783,237
7,786,881
Sending raw data with write() in boost::asio
I've recently decided to use boost::asio for my sockets, but now I'm running into a problem: documentation seems to be lacking. What I want to do is write a function that will send a message consisting of the following structure: 2 bytes of an unsigned integer (uint16_t) for an opcode all bytes all bytes after that...
documentation seems to be lacking The highest voted question in boost-asio is about documentation, start there :-) Can someone help me debug this compilation error? The write() free function expects a reference type as the first parameter. Not a pointer as you have in your example bool sendMessage(tcp::socket* sock...
7,783,243
7,784,940
Gradient descent algorithm won't converge
I'm trying to write out a bit of code for the gradient descent algorithm explained in the Stanford Machine Learning lecture (lecture 2 at around 25:00). Below is the implementation I used at first, and I think it's properly copied over from the lecture, but it doesn't converge when I add large numbers (>8) to the train...
Your implementation is good. Generally, stochastic gradient descent might diverge when α is too large. What you would do with a large dataset is take a reasonably sized random sample, find α that gives you the best results, and then use it for the rest.
7,783,319
7,783,961
OSI Layer 2 Network Programming
I've recently taken some classes in networking (CCNA 1 through 4), so I understand most of the theory behind it all. What I'd like to do now is take that knowledge I have and put it into practice in the form of some small applications. I've been reading through some articles on MSDN on how to do this, but they seem to ...
For Windows, have a look at WinPcap which provides low-level network access. The developer pack already contains some simple examples to get you started. BTW, on Linux there are packet sockets.
7,783,337
7,783,517
How do i rewrite this typecast so nonsense is a compile time error?
This code compiles. Its obviously wrong because B can never be a WTF. Is there a way i can write the typecast so this is a compile time error? class B{ public: virtual void abc(){} }; class D1 : public B{}; class WTF{ }; template<class T, class TT> T DoSomething(TT o){ return dynamic_cast<T>(o); } B*Factory() ...
There are two solutions to this problem, depending on what you want the code to be doing. The first solution: Change the dynamic_cast into static_cast. This solution assumes that you never use class WTF in a class hierarchy with multiple inheritance. See below. The second solution: You realize that C++ allows multiple ...
7,783,345
7,783,411
library is linked but reference is undefined
I'm trying to compile an openCL program on Ubuntu with an NVIDIA card that worked once before, #include <CL/cl.h> #include <iostream> #include <vector> using namespace std; int main() { cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue command_queue; cl_int error; if(clGe...
From the gcc man page: -llibrary -l library Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.) It makes a difference where in the command you write this option; the linker searches and...
7,783,451
7,783,509
How can I detect the subsystem used when my program was compiled?
How can I detect whether my Win32 / Win64 program was compiled with /SUBSYSTEM:WINDOWS, or /SUBSYSTEM:CONSOLE? A preprocessor method would be best if it already exists, but I'd also like to know how to detect it at runtime. It would be sufficient to just detect if there is a console associated with the app, as long as...
Since in your setting you desire a console in both modes the simplest solution is to call AllocConsole all the time. A process can be associated with only one console, so the AllocConsole function fails if the calling process already has a console. A process can use the FreeConsole function to detach itself from its c...
7,783,527
7,783,708
Return the result of subtraction of character arrays in C++
I'm trying to subtract strings where each ASCII character is treated as a decimal digit. For instance: "1000000000001" - "0100000000001" = "900000000000" How would I get started on an implementation of this if my function prototype looked like: char* get_sub(char* a, char* b)
It doesn't seems, but it's a quite complex problem (unless I'm getting too much old). This works only in N. So it must be true that a >= 0, b >= 0, a >= b. I won't explain how does it works. As I've written, it's quite complex :-) (and I'm not even happy of what I've written. I'm sure there is something I haven't thoug...
7,783,532
7,783,597
Generally, is it possible to write kinect-like app using only C++?
I mean, write web-cam recognition that is close to kinect in it's accuracy.
As long as you have an available ABI, it is possible. In the same manner it is possible to do it in any language, including Javascript, brain fuck, and so on. More specially, if you do it in assembly you don't even need an ABI as you can do it yourself :) If you want to know if you can use the Kinect SDK in C++, then y...
7,783,627
7,783,665
C++: Strange behavior of pointer data member in const context
The const qualifier on a method supposed to protect the data member from overwriting by mistake. If you have a data member which is a pointer then only the pointer is defended, the pointed value is not. Is it a flaw in the design of C++ or is there something fundamental thing it serves? Here is a code which demonstrate...
The fundamental thing served here is simply clarity. The pointer is a member of the class, its pointee is not: It is neither automatically destructed when the class is nor automatically constructed. It might be a wholly different object, so it should not necessarily be const when the class becomes const. You are desiri...
7,783,671
7,784,187
Reading data from file
I have .txt file which contains data as follows [12,25],[36,45] i.e numbers are enclosed in square brackets separated by comma from each other I want to read such file through C++ program I referred to string toolkit available,specifically regex facility can be used but i'm not able put in program can someone please he...
#include <iostream> #include <iterator> #include <fstream> #include <sstream> #include <string> #include <vector> #include <algorithm> using namespace std; bool isSeparator(const char c){ return c == '[' || c == ']' || c == ','; } int main(){ const char filename[] = "data.txt"; ifstream fin(filename); ...
7,783,695
7,783,740
OpenGL texture vs FBO
I am pretty new to OpenGL and just want some quick advice. I want to draw a tiled background for a game. I guess this means drawing a whole bunch of sprite like objects to the screen. I have about 48 columns to 30 rows, therefore 1440 tiles (tiles change depending on the game, so I can't pre-render the entire grid). Cu...
I don't really understand your question. A texture is a (usually 2-dimensinal) image that can be applied to polygons, whereas an FBO (framebuffer object) is a kind of offscreen buffer that can be rendered into instead of the screen, usually used to render directly into textures. So I don't see where your question could...
7,783,748
7,783,767
non static or const array syntax
what's wrong with this syntax? sorry for the newbie question. source: Level::Level() { NintyDegreeDirections[4] = { 1.0f, 1.4f, 2.4f, 0.1f } ...rest of class header: //all necessary includes class Level { private: float NintyDegreeDirections[4]; ...rest of header how do I have an array...
In the current version of C++ (C++11), you can initialize the member array like this: Level::Level() : NintyDegreeDirections( { 1.0f, 1.4f, 2.4f, 0.1f } ) { } C++11 isn't universally supported and if you don't have support for this in your compiler you will have to assign to each member in turn. E.g.: NintyDegreeDire...
7,783,837
7,783,853
bitsets binary AND operation
I wrote the following lines: std::bitset<4> bitvec; //bitset 0000 std::bitset<4> addition; //bitset 0000 addition.set(0); //setting the least significant bit std::cout << addition << std::endl; //output 0001 std::cout << std::endl; for(int x = 0; x != 16; ++x) { //addition loop std::cout << bitvec << std::endl;...
Logical AND is not addition. Specifically, 0000 & 0001 ------ = 0000 Which explains why you always get 0000. Logical AND just looks at each bit in both bitsets and only outputs a 1 if that bit is 1 in both of the other vectors. As an example: 1001 & 1100 ------ = 1000 The reason that first bit is 1 is because the...
7,783,894
7,784,076
Static variables in inline function
I have a hash function defined in a header file which I want to make sure is being inlined, but it uses a very large const static buffer of ints. I am wondering whether this buffer will affect the ability of the function to be inlined. Here is the code,(it's based on a crc32 implementation found here). inline HashId h...
As Oli indicates, your best bet is to simply look at the compiler output. However, here are some things to consider: If the contents of the static are truly constant you will be better putting this in an anonymous namespace. This ensures its initialization has nothing to do with calling the function. type of the stati...
7,783,937
7,784,002
bitsets which implement addition and access to all bits
This question is related to this one, as I am looking for a way for adding bitset(-like) structures. I need something like a bitset which can store at least 2400bits, and can (random) access all of them. The second important ability the class has to have is addition, I need to be able to add at least 1. The representat...
Take a look at XInt. It is developed as a candidate for boost.
7,783,965
7,785,124
DFS return only one element
here is DFS algorithm which returns only one vertex ,instead of ABCDE #include <iostream> using namespace std; class Stack { private: static const int size=20; int *st; int top; public : Stack(){ st =new int[size]; top=-1; } ~Stack(){ delete[] st; t...
You have a few problems in the code (for example, don't use delete[] on an object you created with new, it's not an array). But the problem seems to be that your adjacent definition requires vertexlist[j].visited==1, but I think your intention is to look for unvisited nodes. So you don't find any nodes that are adjacen...
7,784,000
7,784,014
Remove Element from std::vector<std::string> >
My compiler complains. #include <iostream> #include <vector> using namespace std; int main(){ vector<string> vec[2]; vec[0].push_back("test1"); vec[0].push_back("test2"); cout << vec[0][0] << endl; vec[0].erase(vec.begin()); cout << vec[0][1] << endl; } What is wron...
vec is an array of vector<string>s. I believe you meant vec[0].begin() like so: vec[0].erase(vec[0].begin());
7,784,167
7,784,234
Unexpected Pointer Behaviour in C++
I'm having a problem with my pointers in C++, and it would be great if someone was able to share their expertise with me! The output I'm getting is: 1: 2: END: C 1:C 2:E END: E The output I was expecting is: 1: 2: END: C 1:C 2:C END: E The code of relevance is this: my test.cpp tree.insert('C'); tree.insert('E'); Th...
You got it by luck: 1: 2: END: C 1:C <--- Undefined. 2:E END: E The mistake is here: template <typename T> pair<typename btree<T>::iterator, bool> btree<T>::insert(const T& elem) { cout << "1:" << this->rbegin_->value() << endl; btree_node<T> node(elem); /* LOCAL parameter, will be deleted when leaving scope*...
7,784,251
7,785,115
two 0 to 1 directions in a loop
This is so simple I can't believe I'm having so much trouble with it. For an analogy to what I'm after imagine a two handed clock face, where instead of 12 hours the time was between 0 and 1. The two hands can point in any direction, provided there values are 0 to 1, for example one pointing upwards and the other diago...
Yeah, so I got it very wrong the first time around (calculated the length of the segment instead of its halving point), and also the second time around (was kind of dodgy, so ended up deleting the answer), but bear with me. The solution lies in the fact we're talking about a circle here. So if we have one halving point...
7,784,307
7,785,339
Socket programming, check entry UDP buffer is empty or not?
I'm writing a UDP client that sends a string to a server, when the server sends back several packets, the behavior of the program is not as my expectation. I want to process any incoming packet by process() one by one until the entry buffer gets empty, but I think there is a problem related to blocking behavior of recv...
I think the problems (unsatisfying behavior you do not describe) come from a different source. Let me just list some ideas and comments c./ what was said before: (1) recvfrom() blocks too. However, you want to use it. Your communication currently sends and receives from loopback, which is fine for your toy program (but...
7,784,330
7,784,365
c++ vector performance non intuitive result?
I am fiddling with the performance wizard in VS2010, the one that tests instrumentation (function call counts and timing.) After learning about vectors in the C++ STL, I just decided to see what info I can get about performance of filling a vector with 1 million integers: #include <iostream> #include <vector> void gen...
From the screenshot you posted, it looks like you're compiling without optimization, which invalidates any benchmarking you do. You benchmark when you care about performance, and when you care about performance, you press the "go faster" button on the compiler, and enable optimizations. Telling the compiler to go slow,...
7,784,357
7,784,796
Invalid heap error when trying to copy elements from a Map to a compatible priority Queue
My program makes a frequency map of characters (which I store in , surprise surprise, a Map), I am trying to copy each element from this map into a Priority Queue so that I can have a sorted copy of these values (I plan to make further use of the Q, that's why am not sorting the map) , but whenever I try to copy these ...
Your vector is reallocating and invalidating your pointers. You need to use a different data structure, or an index into the vector, instead of a raw pointer. When you insert elements into a vector, then pointers to the contents become invalid. while(dispIterator != map_charFreqDistribution.end()) { std::cout<< "Ch...
7,784,573
7,989,587
Callback to member function using libevent
I am trying to pass a member function to libevent which should be treated as a callback. #include <event.h> class A { public: void eventcb(evutil_socket_t fd, short events, void *ctx) { } }; static void global_eventcb(evutil_socket_t fd, short events, void *ctx) { } typedef void (A::*mthd)(evutil_socke...
Instance method pointers need an instance to be invoked on. Since libevent is a C library, it doesn't directly provide a mechanism to associate an instance and an instance method, so you'll have to do it yourself. libevent's various event creation functions let you pass arbitrary data as a callback argument. The instan...
7,784,660
7,784,728
How do I manipulate input from the keyboard in Win32?
Or to clarify this question, how can I make Windows think I hit a key, when I really didn't? I know I could possibly use SendMessage and specify the input there, but then wouldn't only my application receive it? I'd like control to the extent of all applications receiving the "fake" input. Any advice?
You can SendMessage to whatever window you want, even on other processes. You can even use HWND_BROADCAST to send it to every to-level window on the system. But is that what you really want? If you're only interested in a specific program, you can get its window's handle using FindWindow, and then send the message only...
7,784,665
36,545,376
Windows package-manager for C++ libraries
I've been working on various open-source projects, which involve the following C++ libraries (& others): MuPDF Boost FreeType GTKmm hummus PDF libraries LibTiff LibXML2 Wt xpdf xpdf Poppler ZLib It often takes a long time to configure these libraries, when setting them up on a clean machine. Is there a way to automat...
Take a look at the Hunter package manager when you already use CMake to setup your project. It automatically downloads and builds your dependencies whith only a few lines of extra cmake code. Hunter is based on cmake export and import targets. For example if you want to use the GoogleTest library in your cmake based pr...
7,784,743
7,784,829
how to get the process name from the PID in C++?
Possible Duplicate: How to get Process Name in C++ I am looking for a way to to get the process name from the PID? I need to translate process id (PID) to process name any idea?
it depends on the used platform like Yahia mentioned in his comment. on linux: you can get the command-line by reading that file: /proc/[PID]/cmdline on windows: I've found this: get process name from process id (win32)
7,784,774
7,784,819
Is comma operator free from side effect?
For example for such statement: c += 2, c -= 1 Is it true that c += 2 will be always evaluated first, and c in second expression c-= 1 will always be updated value from expression c += 2?
Yes, it is guaranteed by the standard, as long as that comma is a non-overloaded comma operator. Quoting n3290 §5.18: The comma operator groups left-to-right. expression: assignment-expression expression , assignment-expression A pair of expressions separated by a comma is evaluated left-to-right; the left expre...
7,784,898
7,784,928
Dynamic Template Instantiation
I've got a class template, and I need to declare an object of that class, without defining the type parameters, so that I can define them conditionally later, e.g.: template<typename T> class A{ public: A(T v){var = v}; ~A(){}; T var; } int main(){ A<>* object; // Or sometihng along these lines...? ...
Well, you certainly can't do that. You'll have to make A derive from another class, for example: template<typename T> class A : public B { public: A(T v){var = v}; ~A(){}; T var; } int main(){ B* object; if(/* something*/) object = new A<float>(0.2f); else{ object = new A<int>...
7,784,975
7,785,428
c++ win32 add a hyperlink to a dialog
I would like to add an About dialog to my Win32 application (developed using C++). How can I add a hyperlink to the dialog? I'm loading the dialog from a resource file (.rc). Is it possible to define this functionality from the .rc file? My .rc file now looks like this: IDD_ABOUTBOX DIALOGEX 0, 0, 218, 118 STYLE DS_...
You can use a SysLink Control on Windows XP or above. You can define it from the .rc file like this: In resource.rc: CONTROL "<a>Link</a>",IDC_SYSLINK1,"SysLink",WS_TABSTOP,7,7,53,12 In resource.h: #define IDC_SYSLINK1 1001
7,785,096
7,785,296
Read Laptop Battery Status in Float/Double
I have a program that reads battery status in Windows that looks like this (simplified code): #include <iostream> #include <windows.h> using namespace std; int main(int argc, char *argv[]) { SYSTEM_POWER_STATUS spsPwr; if( GetSystemPowerStatus(&spsPwr) ) { cout << "\nAC Status : " << static_cast<doubl...
You can get this information using the WMI . try using the BatteryFullChargedCapacity and BatteryStatus classes both are part of the root\WMI namespace. To get the remaining battery charge in percent just must use the RemainingCapacity (BatteryStatus) and FullChargedCapacity (BatteryFullChargedCapacity) properties. T...
7,785,185
7,785,378
Sending a message between 2 objects
I have objects A and B that need to send and receive messages from each other. For example: I click, this causes A to send a message to B. B does something with it then sends A another message as a reply. Right now the way I have it is, A has a B* and B has an A* and they call each other's sendMessageTo method to commu...
I think you need to implement Listener/Observer pattern. from Wikipedia: The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usual...
7,785,256
7,786,966
Send wstring and ptime over MS RPC
Iam using Microsoft RPC and i need to transfer my custom structure that have fields of type std::wstring and boost::ptime. In idl there is no such data types. What is best solution to send that struct. In read about serialization with RPC. But ms serialization is also based on idl file, so i cant define struct in idl f...
The IDL has a limited set of basic types, and it can't transfer complete c++ objects, as the receiver might not be written in c++ at all. So, you'll have to do some conversions, but doing so with the types you mention is not very complicated. Starting with the wstring, here are your options: Pass a c string as [in, st...