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 |
|---|---|---|---|---|
5,425,092 | 5,425,495 | Split a wstring by specified separator | I have a std::wstring variable that contains a text and I need to split it by separator. How could I do this? I wouldn't use boost that generate some warnings. Thank you
EDIT 1
this is an example text:
hi how are you?
and this is the code:
typedef boost::tokenizer<boost::char_separator<wchar_t>, std::wstring::const_i... | In your code, question mark appears on a separate line because that's how boost::tokenizer works by default.
If your desired output is four tokens ("hi", "how", "are", and "you?"), you could
a) change char_separator you're using to
boost::char_separator<wchar_t> sep(L" ", L"");
b) use boost::split which, I think, is t... |
5,425,201 | 5,425,227 | Get readable error messages from a c++ compiler | Have you ever heard about a script able to make the g++ error messages more readable?
I am pretty sure I heard about it some times ago but I can't remember the name.
Thank you.
| You might be thinking of STLFilt, which supports a variety of C++ compilers but is no longer being developed and doesn't guarantee to work with the latest versions of g++.
|
5,425,211 | 5,425,262 | store images in an array | I need to store images(I cropped them in a for loop,after every crop,I want to store in an array) into an array of images. How could I do that in OpenCV?
| std::vector<IplImage*> vec_images;
IplImage* frame = cvQueryFrame(capture); // Acquiring a new image
// Cropping or whatever
vec_images.push_bask(frame);
Don't forget to deallocate these frames when you don't need them anymore:
for (int i = 0; i < vec_images.size(); i++)
cvReleaseImage(&vec_images[i]);
|
5,425,631 | 5,425,698 | Saving values into array | I have some trouble, saving values from input stream (cin) into an array.
int count = 2;
double *startValues = new double[count];
for(int i = 0; i < count; i++) {
double tmpVal;
cout << i + 1 << ". Startwert: "; cin >> tmpVal;
startValues[i] = tmpVal;
}
After the for loop only the first value is saved in t... | Error checking. You need to verify that you actually did read a double from cin
int count = 2;
double *startValues = new double[count];
int i = 0;
while (i < count) {
double tmpVal;
cout << i + 1 << ". Startwert: ";
if (cin >> tmpVal) {
startValues[i] = tmpVal;
++i;
} else {
cout << "... |
5,425,666 | 5,425,756 | Passing around boost::asio::ip::tcp::socket | Alright, this is my current code snippet:
namespace bai = boost::asio::ip;
bai::tcp::socket tcp_connect(std::string hostname, std::string port) {
try {
boost::asio::io_service io_service;
bai::tcp::resolver resolver(io_service);
// we now try to get a list of endpoints to the server
... | socket can't be copied. Use a boost::shared_ptr<bai::tcp::socket> instead. If you could copy a socket you'd have all sorts of funny issues if you ended up with two socket instances representing the same underlying OS socket - so it makes sense that copying (and therefore return by value, pass by value) is not allowed.
|
5,425,770 | 5,431,017 | In-Proc COM object sharing across another Process | Before I ask this question I would like to make it clear that I know there are libraries and techniques for Inter process communcation. This though, is a learning question about COM.
I also do know about out-of-proc servers but that's not what I am looking for.
The question:
What I want to know, because I don't know t... | Yes, it's possible. The underlying principle is the same regardless of whether you are sharing a single object instance between apartments in a single process, or between separate processes.
There's two approaches here: perhaps the simplest is to use the Running Object Table: this is essentially a workstation-wide tabl... |
5,425,934 | 5,426,249 | how to search for a word in a docx file in c++? | i am writing a search program in c++ which will search for a set of words in a set of files.. these files are either text files or docx files.The problem is how can i search a docx file in c++, i cannot open it even,if i need to convert it to text file, what is the procedure and how will i search it?
| The OOXML file formats are officially documented in ECMA-376. There's an equivalent ISO standard (29500, if memory serves), but I believe you have to pay to get it, and the two are identical1. As a warning, however, these are huge documents, and the file formats themselves are definitely non-trivial to deal with. Just ... |
5,426,091 | 5,426,202 | Does Mock Objects in C++ Always Requires Virtual Methods or Templates? | Suppose I have classes
class Inner {
public:
void doSomething();
};
class Outer {
public:
Outer(Inner *inner); // Dependency injection.
void callInner();
};
Proper unit-testing says I should have tests for Inner. Then, I should have tests for Outer that uses not a real Inner but rather a MockInner ... | I don't think you must mock out every dependency of your tested class in practice. If it is complicated to create, use or sense through, then yes. Also if it directly depends on some unneeded external resource such as a DB, network or filesystem.
But if none of these is an issue, IMO it is OK to just use an instance o... |
5,426,217 | 5,426,503 | How to create win7 style button using CreateWindowEx |
Possible Duplicate:
winapi CreateWindowEx -> create button with user system styles?
Hi,
I am kinda new to WinAPI and C++ and I am using Visual Studio 2010. I want to create some buttons in the main window. So there are two questions:
1) can I use a dialog window created with resource editor as a main window so that ... | You need to link a manifest to your app that specifies v6 common controls. Websearch will do the rest for you.
|
5,426,289 | 5,426,350 | What is the best practice for porting #defines from .h file to a C# application? | I am converting an application from C++ to C#. The C++ application has a defines file .h with over 500 #define directives. I would like to represent this data in a Definition.cs file. What is the best way to do this?
An example of the defines:
//Digital ouputs
#define FLAGLEDCOOL "BIT12032"
#define FLAGLEDL... | Just declare them as consts - a const is implicitly a static as well:
public class DigitalOuputs
{
public const string FLAGLEDCOOL ="BIT12032"
...
}
|
5,426,359 | 5,426,858 | makefile which build the library (lib.a)from the list of object files (*.o) | I have a problem because i have never written any makefile. So if any could help me I become happy. I have a lot of different .o files, which stored in the different folders. For example:
folder1: obj1.o
folder2: obj2.o
folder3: obj3.o
I need makefile, which will build the library from files which I send to makefile li... | GNU make does not support passing parameters "to the makefile" on the command line.
You have two basic mechanism for setting parameters to be used by make while executing a makefile (I'm assuming that you are using GNU make, and not all of his advice will apply to other makes):
Write to submakefiles, possibly using a ... |
5,426,708 | 5,426,753 | Why are exceptions so rarely used in C++ | I have been programming in C++ on and off for about 5 years, why have I never seen exceptions used other than examples for examples sake?
| Observation bias at work here.
A significant fraction of C++ code is for systems programming and embedded systems. (After all, C++ is just one of many options for applications programming, and many of the alternatives have fancier RAD environments, but in systems work, it's often the highest level language for which a... |
5,427,037 | 5,427,064 | UUID generator problem | I have a uuid class that is part of a portable library that gets initialized with the following piece of code. It works fine under windows, but under linux it's
not generating UUID's correctly.
uint32 data[4];
data[0] = rng.Get();
data[1] = rng.Get();
data[2] = rng.Get();
data[3] = rng.Get();
data[1] = (data[1] & 0xf... | It appears that the %X specifier is expecting an int-sized input to be passed, while you seem to be passing it an unsigned char (isn't that what uuid[i] is?).
Try doing this and see if it helps:
for (int i = 0; i < 16; i++) {
int temp = uuid[i];
printf("%02X", temp);
}
printf("\n");
Update - New theory
OK, I l... |
5,427,086 | 5,427,109 | Detecting if two images are similar | Could someone give me a push in the right direction, if I am willing to determine if
two images actually make a panorama together (or are panorama-like, e.g contain "same" parts, which are obviously a bit transformed).
| The technique you are after is known as "image stitching". There is a reasonable Wikipedia entry on it. That gives a few hints about how the algorithm would work.
It's necessarily a tricky heuristic. You need to find groups of pixels that are similar (but obviously not identical). This could include parts that are rota... |
5,427,091 | 5,427,197 | Library for basic image manipulation in C++ | I am looking for a great C++ library for doing basic image manipulation. What I need done is to be able to convert an image to grayscale and have access to read the pixels of the image.
I have looked at OpenCV, GIL, CImg and Magick++, but either they were not too great, or I couldn't figure out how to convert an image ... | CImg is probably easiest to use, no install it's just a header file
|
5,427,227 | 5,433,015 | Opencv 2.2 Face Detection Max Size | In opencv 2.2 the cvHaarDetectObjects function offers a max face size option. The problem is it doesn't seem to work. I am hoping somone can try it out, and let me know if I am just doing soemthing wrong or not. I am putting in a min face size detection of cvSize(30,30) and a max face size of cvSize(40,40), however it ... | It turns out this feature does not work, there is a small bug in opencv's source code.
|
5,427,334 | 5,427,380 | Qt4: The best way to access parent class (1 level up, 2 levels up .... ) | I'm wondering how to access parent class in my Qt application.
Lets say my project has following structure:
mainWindow: MainWindow
tabWidget: QTabWidget
tab1: MySubClass1
tab2: MySubClass2
tabWidget: QTabWidget
xtab1: MySubSubClass1
xtab2: MySubSubClass2
... | You could create a static method and object inside MainWindow that would return mainwindow object.
Something like this:
private:
static MainWindow* _windowInstance
public:
static MainWindow* windowInstance()
{
return _windowInstance;
}
This seems to be the simples solution in most cases.... |
5,427,572 | 5,428,370 | How to change current line format in QTextEdit without selection? | there! I want to find out how to change current line format in QTextEdit?
In the document I read that
"Formatting can be applied to the
current text document using the
setCharFormat(), mergeCharFormat(),
setBlockFormat() and
mergeBlockFormat() functions. If the
cursor has no selection, current block
forma... | Pls, check if an example below would work for you, it should change the current text block format and font.
QTextCursor cursor(myTextEdit->textCursor());
// change block format (will set the yellow background)
QTextBlockFormat blockFormat = cursor.blockFormat();
blockFormat.setBackground(QColor("yellow"));
blockFormat... |
5,427,612 | 5,427,888 | .lib error when I'm using a dll? | I'm trying to get some practice using windows DLLs (not used to them). I followed this article:
http://msdn.microsoft.com/en-us/library/ms235636(v=vs.80).aspx
To the letter.
And yet, I am receiving this error:
1>LINK : fatal error LNK1104: cannot open file '..\debug\math.lib'
My project is a dll project, not a lib. And... | VS does not create an import library if dll does not actually export anything. To quickly check if that is your case, find your dll, open it with dependency walker and see if there are any exports at all.
If you find exports missing check if you did mark anything for export: either by declaring classes/functions as "__... |
5,427,744 | 5,427,762 | How to convert ASCII string to hexadecimal? | I have tried to find this topic on the web but I couldn't find the one I need.
I have a string of character:
char * tempBuf = "qj";
The result I want is 0x716A, and that value is going to be converted into decimal value.
Is there any function in vc++ that can be used for that?
| You can use a stringstream to convert each character to a hexadecimal representation.
#include <iostream>
#include <sstream>
#include <cstring>
int main()
{
const char* tempBuf = "qj";
std::stringstream ss;
const char* it = tempBuf;
const char* end = tempBuf + std::strlen(tempBuf);
for (; it !=... |
5,427,858 | 5,428,748 | C++ If/Else statement question | What am I doing wrong with the syntax of these If/Else statements
I'm pretty sure it has something to do wiht my curly bracket placement.
All of the examples in my book only contain really primitive/simple examples (not to say that this code isn't simple; b/c it is). I guess my general question would also be how do yo... | I think, for this particular problem if-else isn't even required!
I would rather recommend this solution:
const char *stens[] = {"", "", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninty"};
const char *sones[] = {"", "one", "two", "three", "four", "five",
... |
5,428,093 | 5,428,305 | Child Window painting problem on Vista only | I have a dialog-based MFC C++ app. My dialog displays a number of "pages" (similar to a tab page or property dialog box).
I display each "page" by displaying a Child window over the top of the parent's client area. This works fine on Vista until I then open another window on top of the child.
Vista then seems to draw a... | I've figured out the problem.. I shouldn't be calling CDialog::OnNcActivate() - I should have just been returning TRUE instead. All working fine now.
|
5,428,498 | 5,428,683 | C++ sax2 parser problem | I want to parse an XML file. My XML looks like this:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!-- Put site-specific property overrides in this file. -->
<configuration>
<property>
<name>tracker</name>
<value>localhost:58303</value>
<description>The host and port that th... | You can't change the value with the SAX handler AFAIK. Generally I define both a sax handler to convert from xml to some c++ object, as well as a document builder to convert from object to xml.
A general approach is as follows: use the sax handler with an xml parser to get an object, modify the object, and then use t... |
5,428,552 | 5,428,691 | C: Lock-Free Memory Allocation Library | Anyone have any good experience with a lock-free memory allocator for C/c++?
I have looked into boost, and libcds, but I am unsure about which library to use.
Background, I have been researching a "Lock-Free, Wait-Free, Non-Blocking, Dynamic Perfect Hashing, Expandable, Concurrent Hash Table"
*Yes I know that sounds p... | The pretty graphs show this implementation is good:
http://locklessinc.com/
It's open source GPL 3.0 since 14 Nov 2011 :)
|
5,428,568 | 5,428,705 | CString value changing after calling UpdateData(TRUE) | I have an application in which I have an Edit Box. This edit box allows users to enter any character upto 20 characters.
Now I have written a function for handling the edit changed for event
ON_EN_CHANGE
void CDlgFloatingEdit::OnEditChanged() { UpdateData(TRUE); }
Now when I enter a text value of 20 characters w... | UpdateData will always copy the data from the controls into the dialog data members, that is its function. It will immediately apply any DDV data validations, including the 20 character limit on a field. If the validation fails it should display an error, but even if it doesn't it might clear out the CString data membe... |
5,428,725 | 5,428,754 | Access a specific record using lseek | Is it possible to access a specific one (using a specific index) in a text file without knowing the size of each record?
| If you maintain a separate index of record offsets then you can simply consult it for the appropriate location to seek to. Otherwise, no.
|
5,429,007 | 5,481,974 | How to Sort CTypedPtrList in C++ or MFc? | I want some template classes like sort etc is used to sort the CTypedPtrList.
| This Sample will sort CTypedPtrArray :
typedef CTypedPtrArray<CPtrArray , CLog *> CLogData;
CLogData tLogData;
CLog *t1Log , * t2Log;
bool bChanged = true;
if (tLogData.IsEmpty())
return;
long int i, j;
for (i = 0 ; i < m_nCount - 1 ; i++)
{
for( j = i + 1; j < m_nCount ; j++ )
{
... |
5,429,027 | 5,429,050 | Can anyone explain this portion of the C++0x draft standard? | From ISO Standard Draft: §3.0/9:
n3234 says:
A name used in more than one translation unit can potentially refer to the
same entity in these translationunits depending on the linkage (3.5) of the
name specified in each translation unit.
Can anyone explain this point with an example, please?
What is th... | Sure! What this is saying is that if you have multiple source files (translation units) that both use some name (for example, the name of a variable, class or function), then it's possible that those different files are talking about the same variable, class, or function, assuming that that entity was declared in a wa... |
5,429,141 | 5,429,592 | What happens to malloc'ed memory after exec() changes the program image? | I know that when I call one of the exec() system calls in Linux that it will replace the currently running process with a new image. So when I fork a new process and run exec(), the child will be replaced with the new process.
What happens to any memory I've allocated from the heap? Say I want to parse an arbitrary num... | When you call fork(), a copy of the calling process is created. This child process is (almost) exactly the same as the parent, i.e. memory allocated by malloc() is preserved and you're free to read or modify it. The modifications will not be visible to the parent process, though, as the parent and child processes are c... |
5,429,194 | 5,452,615 | unresolved external symbol _NPN_MemAlloc referenced in function | i develop extension for Chrome using XPCOM and i try communicate my dll with JS all fine ! but if i try return value ( string ) from my cpp code i have crash my browser ((( me need allocate memory through NPN_MemAlloc ! but i can't because my VC2008 show me subj error !
i include on my
stdafx.h
npapi.h
npfunctions.h... | I don't know why npapi.h declares NPN_MemAlloc, however I looked at the source for Mozilla's test plugin and it actually has a definition for NPN_MemAlloc; all it does is call through the memalloc member of the NPNetscapeFuncs* parameter of your NP_Initialize method.
|
5,429,299 | 5,429,425 | c++ Realy large floating point calculation | I want to do really large floating point calculations. Should be fast enough.
How can I make use of Graphics processors if available? If not GPU available then I would like to use main CPU.
thanks
| Depending on the 'size' of these numbers, you can try MPFR, although its not a GPU solution, it can handle big numbers and should be relitively fast, its used by a few opensource compilers(GCC & LLVM) to do static constant folding, so its designed to preserve accuracy.
To do work on a GPU (really a GPGPU), you'd need t... |
5,429,309 | 5,429,442 | Loop not working in C++ | I have created a program that creates a file of the users name and then allows them to insert lines. I want to make it so that if they enter nothing (just pressing enter) it exits, but I have trouble figuring out what I'm doing wrong.
Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int m... | It's just your while condition that needs to be changed:
while (strlen(line) != 0);
|
5,429,381 | 5,429,408 | Free C/C++ IDE for Windows 7 that works with GCC | I've learned C and C++ in Borland's Turbo C++ IDE, the 16-Bit version with that old blue screen background, in which I started off building console programs for Windows. Now that Windows Vista and 7 doesn't support that IDE to be run in full-screen mode, I'm looking for such similar IDE (not necessarily from Borland), ... | Turbo C++ is very old, and the concepts and philosophies of IDE design as (as well as the language C++ compilers are compiling) have developed much further since.
You might try Code::Blocks or Eclipse, but I wouldn't expect a transition as smooth as going to the next version of Turbo C++. (Which weren't as smooth eith... |
5,429,530 | 5,429,798 | How to get Unicode for Chracter strings(UTF-8) in c or c++ language (Linux) | I am working on one application in which i need to know Unicode of Characters to classify them like Chinese Characters, Japanese Characters(Kanji,Katakana,Hiragana) , Latin , Greek etc .
The given string is in UTF-8 Format.
If there is any way to know Unicode for UTF-8 Character? For example:
Character '≠' has U+2260... | The utf-8 encoding is a variable width encoding of unicode. Each unicode code point can be encoded from one to four char.
To decode a char* string and extract a single code point, you read one byte. If the most significant bit is set then, the code point is encoded on multiple characters, otherwise it is the unicode co... |
5,429,653 | 5,429,695 | What feature corresponds to 'synchronized' in Java? | synchronized in Java can guarantee thread-safety when accessing a shared object.
What about C++?
| Use the following in C++:
#include <mutex>
std::mutex _mutex;
void f()
{
std::unique_lock<std::mutex> lock(_mutex);
// access your resource here.
}
|
5,429,705 | 5,429,769 | C++ double data type | The data type double is another floating-point type.Then why is it treated as a distinct data type?
| Not sure I understand your question correctly, but I'm going to assume you mean the difference between a float and a double.
If you refer to http://www.cplusplus.com/doc/tutorial/variables/ you'll see a list of fundamental data types.
Essentially, a double is a floating point number with higher precision since it uses ... |
5,429,855 | 5,429,869 | Why can't objects of type void be created in C++? | C++ doesn't allow creating objects of type void. Why is that?
| Consider the code below.
class Foo
{
// etc ...
};
int main()
{
// Declaring an object...
Foo foo;
// foo has been created.
// etc ...
return 0; // When function returns, foo will be destroyed.
}
In order to know how to actually create the object, the compiler has to know the type. Informall... |
5,430,316 | 5,431,300 | dup2 to redirect stdout and stderr to another file descriptor | i have a call like this.
int fd[2];
pipe(fd)
and then
dup2(fd[WRITE],STDOUT_FILENO)
is there a way to use the dup call to duplicate both 1 and 2 to fd[WRITE]?
| Just repeat this operation for stderr.
dup2(fd[WRITE], STDOUT_FILENO);
dup2(fd[WRITE], STDERR_FILENO);
|
5,430,536 | 5,430,742 | Configuring Systems environment with Java to invoke JNI calls | I have written some JNI code that works just fine. I call an API out of Java which needs some environment variables set. Currently, I am working on Windows XP SP3.
I need to set a variable (Example: FOO=bar) in the user space and need to add some paths to the systems path. I need to that because I use third party DLLs ... | What sort of batch script are you using? Normally, variables
set in a process propagate down to all processes created from
that process: if I do
set toto=abc
in a console window, I find this environment variable in all
programs started from that window.
|
5,430,566 | 5,430,580 | Estimating length of result of sprintf | I need to estimate the length of the string obtained on sprintf operation. How can I do this. In other words, how can I avoid harcoding the value 50 in the below snippet.
double sum;
char* resultString;
..
resultString = new char[50]; //how can I avoid hardcoding 50 here?
sprintf(resultString,"[%e]",sum);
| Use snprintf(char *buffer, int buf_size, const char *format, ...);. sprintf is unsafe.
However I read you are using C++, so I would use a stringstream like this:
#include <iostream>
#include <sstream>
double sum;
std::stringstream buf(std::stringstream::in | std::stringstream::out);
std::string resultString;
..
buf <... |
5,430,688 | 5,430,720 | Compiling C and C++ files together using GCC | I'm trying to compile C and C++ sources together using GCC.
gcc -std=c++0x test.cpp -std=c99 test.c -lstdc++
Now, this works fine, except that I get two warnings.
cc1plus: warning: command line option "-std=c99" is valid for C/ObjC but not for C++
cc1: warning: command line option "-std=c++0x" is valid for C++/ObjC++ b... | Compile the files separately, link with g++
gcc -c -std=c99 -o file1.o file1.c
g++ -c -std=c++0x -o file2.o file2.cpp
g++ -o myapp file1.o file2.o
|
5,430,801 | 5,453,372 | C++ guarantee and name for POD-like data, memcpy capable | In another question I incorrectly used the term POD to refer to data types that aren't actually POD types (on account of having a constructor). Now, I've looked through the standard and couldn't find a proper name for what I want. Nor can I actually find a guarantee that copying is actually allowed.
The data type I mea... | In C++0x, the concept of PODness is broken out into several individually useful categories:
A trivially copyable class is a class that (draft 3242, section [class]):
has no non-trivial copy constructors (12.8),
has no non-trivial move constructors (12.8),
has no non-trivial copy assignment operators (13.5.3, 12.8),
h... |
5,430,849 | 5,430,878 | Implementing a user registry in a c++ based server | So I'm planning to develop a Community feature for a game I'm developing. Currently, the high score server, which I want to integrate this user registry with is developed in pure c++.
Is there a c++ library for developing user registries? Currently, I am thinking of implementing the user registry by saving to the file ... | This sounds like a very open ended question.
If you intend to have quite a lot of users and possibly do reporting on data or have to manage pieces of data manually.... you may want to look into sqlite. There would be slightly less administration and overhead than using a fully featured DBMS.
|
5,431,130 | 5,431,173 | managing 1000+connection using boost in client | Here I am working Gateway simulator purpose of the gateway is to connect with data center and stream video to data center if data center request it.
Here gateway simulator can simulate 1000 gateway.that means each gateway will connect with data center.Here i am confused how to manage this much of socket in the gateway.... | If it were my problem to solve, I'd try first with libevent. Libevent automatically picks the 'best available' mechanism for each platform, whether that is epoll, or kqueue, or select, and allows you to focus on what is unique to your program.
|
5,431,180 | 5,431,194 | C++ Compiler error C2440 | I am getting the following error but I don't understand what is wrong:
Error 7 error C2440: 'initializing' :
cannot convert from
'std::pair<_Ty1,_Ty2> *' to
'std::pair<_Ty1,_Ty2> *'
c:\documents
and settings\vay\my documents\visual
studio
2010\projects\socks\chatserver\server.h 107
This is the relev... | Your two pairs are different.
Remove the &:
std::pair<std::string, ChatClient> *p = new std::pair<std::string, ChatClient>(...);
|
5,431,221 | 5,933,152 | Netbeans C++ Detecting errors when there are none | I am using Netbeans for a c++ project. However, all the c++ includes/syntax(iostream, cstdlib, cout etc) are indicated as errors by Netbeans. I pointed the project compiler to g++ and the project runs fine, but I don't know how to make it find the libraries
Resolved:
Netbeans was just being dumb...restarted it and cre... | Resolved: Netbeans was just being dumb...restarted it and created new project...everything works...
|
5,431,302 | 5,432,126 | Board game AI design: choosing STL data container | I'm coding an AI engine for a simple board game. My simple implementation for now is to iterate over all optional board states, weight each one according to the game rules and my simple algorithm, and selecting the best move according to that score.
As the scoring algorithm is totally stateless, I want to save computat... | Yes it's common to store evaluated boards into a hash table it's called transposition table. A STL container could be std::vector. In general you have to create a hash function (e.g. zobrist hashing). The hash function calculates a hash value of a particulare board. The result of hash_value modulo HASH_TABLE_SIZE would... |
5,431,362 | 5,431,498 | how does templates work, are they always inlined? | I can understand how it work if they are inlined. But if they are not, how does it work? does all object files get their own copy of for example the function template anyway?
| Templates will be inlined in the standard meaning of inline, which is more related to the One Definition Rule than to actual code inlining. That is, the linker will not complain if the template functions are defined in more than one translation unit, it will just pick one (beware: random one, current compilers do not c... |
5,431,420 | 5,431,445 | Why doesn't the program crash when I call a member function through a null pointer in C++? | #include "iostream"
using namespace std;
class A
{
public:
void mprint()
{
cout<<"\n TESTING NULL POINTER";
}
};
int main()
{
A *a = NULL;
a->mprint();
return 0;
}
I am getting output as "TESTING NULL POINTER". Can anyone please explain why this program is printing the output instead o... | You're not using any member variables of A - the function is completely independent of the A instance, and therefore the generated code happens to not contain anything that dereferences 0. This is still undefined behavior - it just may happen to work on some compilers. Undefined behavior means "anything can happen" - i... |
5,432,083 | 5,432,104 | The best practice solution of differenses search of two STL vectors | I have already two STL vectors. For instance:
vector<int> MyList;
MyList.push_back(10);
MyList.push_back(20);
MyList.push_back(30);
MyList.push_back(40);
MyList.push_back(50);
vector<int> MyListSub;
MyListSub.push_back(20);
MyListSub.push_back(30);
MyListSub.push_back(40);
And I want to get the number of elements w... | You can use std::set_difference for this:
std::vector<int> diff;
std::set_difference(MyList.begin(), MyList.end(),
MyListSub.begin(), MyListSub.end(),
std::back_inserter(diff));
As @Jan points out, the vectors have to be sorted. If they are not, use std::sort to sort them:
std::... |
5,432,147 | 5,432,172 | Chain initialization without temporary pointers | An object of class A is constructed from an object of class B, which is inherited by class C. How can I create an A object without temporary pointers to the B object?
B *my_b = new C();
A *my_a = new A( *my_b );
// but *my_b is only used here
Update: The constructor of A takes a B as the argument, not a C.
| If you don't need to retain the object of type B and class A constructor copies the object and doesn't instead store a reference to it:
A* my_a = new A( B() );
otherwise you can't do anything much better than what you're doing already.
|
5,432,266 | 5,528,757 | Interpolation using boost:timer and slerp, quaternions | Im aware this code just looks like a massive block of mess so iv'e done my best to comment what i can... If anyone regularly does skeletal animation im hoping youl see whats going on here.
The problem im having is that float interp = (next-current)/(next-start); is not returning whats expected, e.g. values greater than... | Turns out there were quite a few mistakes... But the main error was to do with pointers, I fixed it by giving the bones ids for parents, children and itself. Then I changed the functions to take bone id instead of reference to a joint. Problem = fixed :D
|
5,432,411 | 5,438,424 | Is safe to use gperf generated perfect hash function? | I'm now considering using gperf generated hash function to replace our old one, but I had no idea if it's safe or not, and will that add our maintaining cost.
The reliability and system complexity is our first consideration.
Is there someone who had used gperf generated hash function in big project?
Is safe to use it i... | Never had to use the API myself, but,
in this write-up, which seems to be from the late 90s, they show that GPERF has been used in TAO, gnu indent, and a handful of other applications.
It's been out for a while, and likely to be well shaken out.
Here's an interesting developer works writeup.
|
5,432,681 | 5,432,696 | Performances of Structs vs Classes | I wonder if there are performance comparisons of classes and C style structs in C++ with g++ -O3 option. Is there any benchmark or comparison about this. I've always thought C++ classes as heavier and possibly slower as well than the structs (compile time isn't very important for me, run time is more crucial). I'm goin... | On runtime level there is no difference between structs and classes in C++ at all.
So it doesn't make any performance difference whether you use struct A or class A in your code.
Other thing, is using some features -- like, constructors, destructors and virtual functions, -- could have some performance penalties (but i... |
5,432,693 | 5,433,439 | C++ lambda expression | I am trying to understand lambda expression.
Its going over my head. Need self explanatory examples
Please !
| If you are familiar with the current C++ functors (i.e., classes that implement operator() so that they can be called like a function, but have internal data-members that can be initialized), then basically lambdas are a nice extension to that language feature by enabling you to create functors as well as initialize th... |
5,432,739 | 5,432,774 | Am I using the copy_if wrong? | I am using visual studio 2010 and I am trying to use std::copy_if,
I want to copy all values that are satisfying a predicate. For example:
struct comp
{
bool operator()(const int i) { return i == 5 || i == 7; }
};
int main()
{
array<int, 10> arr = { 3, 2, 5, 7, 3, 5, 6, 7 };
vector<int> res;
copy_if(a... | The copy_if algorithm looks something like this(taken from MSVC2010):
template<class InIt, class OutIt, class Pr> inline
OutIt copy_if(InIt First, InIt Last, OutIt Dest, Pr Pred)
{
for (; First != _Last; ++First)
if (Pred(*_First))
*Dest++ = *First;
return (Dest);
}
And as you can see the ... |
5,432,793 | 5,433,984 | C++, Multilanguage/Localisation support | what's the best way to add multilanguage support to a C++ program?
If possible, the language should be read in from a plain text file containing something like key-value pairs (§WelcomeMessage§ "Hello %s!").
I thought of something like adding a localizedString(key) function that returns the string of the loaded languag... | Simplest way without external libraries:
// strings.h
enum
{
LANG_EN_EN,
LANG_EN_AU
};
enum
{
STRING_HELLO,
STRING_DO_SOMETHING,
STRING_GOODBYE
};
// strings.c
char* en_gb[] = {"Well, Hello","Please do something","Goodbye"};
char* en_au[] = {"Morning, Cobber","do somin'","See Ya"};
char** la... |
5,432,853 | 5,432,991 | receiving data using boost library | I have gone through the following article boost-asio.
http://www.boost.org/doc/libs/1_46_0/doc/html/boost_asio/example/echo/async_tcp_echo_server.cpp.
I wanted to modify above server so that it can accept multiple clients and receive data from the clients as well.
For accepting connection it has a handler, how and wher... | Hi you can look for tcp server example .
And here more examples
|
5,433,769 | 5,433,964 | Qt debugging error: "while parsing target library list: not well-formed (invalid token)" | I am debugging an application developed in Qt/C++ using QtCreator. My application reads from the serial port using QextSerialPort, where the serial port is connected to a Rhino Mark IV controller.
int bytesRead;
char buffer[BUFFER_SIZE];
if (_serialPort->bytesAvailable() > 0
&& (bytesRead = _serialPort->read(buffe... | Did you configure the serial port correctly in your application (i.e. baudrate, stop bits, etc.)?
Also, you should not add 1 to bytesRead when zero terminating the buffer as that allows a single unwanted byte at the end of the string.
That error message is generated by gdb, not Qt. It may be related to using files/fold... |
5,433,852 | 5,434,385 | When does postincrement i++ get executed? |
Possible Duplicate:
Undefined Behavior and Sequence Points
In C++ on a machine code level, when does the postincrement++ operator get executed?
The precedence table indicates that postfix++ operators are level 2: which means in
int x = 0 ;
int y = x++ + x++ ; // ans: y=0
The postfix ++'s execute first.
However, i... | Instead of jumping on the details of the example that is UB, I will discuss the following example that is perfectly fine:
int a = 0, b = 0;
int c = a++ + b++;
Now, the precedence of operators means that the last line is equivalent to:
int c = (a++) + (b++);
And not:
int c = (a++ + b)++; // compile time error, post in... |
5,433,971 | 5,434,053 | C++ Macro code substitution | 1) - i have two enums
enum FixedScriptingEvent {
FIXED_SCRIPTING_EVENT_NOTOUCH,
FIXED_SCRIPTING_EVENT_OVER_MOVED,
FIXED_SCRIPTING_EVENT_OVER_RELEASED,
FIXED_SCRIPTING_EVENT_OUTSIDE_RELEASED,
FIXED_SCRIPTING_EVENT_OUTSIDE_MOVED,
...
enum InputState {
INPUT_STATE_NOTOUCH,
INPUT_ST... | Token concatenation?
#define EXECUTEFIXEDSCRIPTEVENTFORSTATE(x)\
if (inputMonitor.state.current == INPUT_STATE_ ## x) {\
executeScriptsForEvent(FIXED_SCRIPTING_EVENT_INPUT_STATE_CHANGED_TO_ ## x);\
}
|
5,434,171 | 5,434,221 | C++: how do I convert an unsigned char to a string representing the binary value that the char has? | char myChar = 0x01;
how do I get my output to be "00000001"
If there is a way to do it with a built in function, without a loop (I can do this with a loop, I just want to be elegant), that would be preferred ?
As for the why I'm doing this: I'm saving these numbers in a file that an external library needs this formatt... | You may use a bitset:
std::bitset<8> bits(myChar);
std::cout << bits << std::endl;
|
5,434,484 | 5,434,801 | Defining a hash function in TR1 unordered_map inside a struct | According to this, it is possible to define an equality function in a TR1 unordered_map like this:
#include <tr1/unordered_map>
using namespace std;
using namespace std::tr1;
struct foo{
...
bool operator==(const foo& b) const{
return ..;
}
};
unordered_map<foo,int> map;
Is it possible to define t... | If you want to change the default hashing (or, more often, provide hashing for a type that isn't currently supported), you provide a specialization of std::tr1::hash<T> for your key-type:
namespace std {
namespace tr1 {
template<>
struct hash<typename my_key_type> {
std::size_t operator()(my_key_type ... |
5,434,516 | 5,435,008 | expression: deque iterator not incrementable (special case - i can't figure it out) | I have something like deq.push_back(object) which works fine in a source file but not in another one - if I try the same operation there I get the runtime error in the title. How can it be possible? deq is a global variable in the source file where the code works. Just as a test, I tried to swap the global declaration ... | Is it possible that you have moved the deq.push_back(object) statement to within a loop and thus modifying the container invalidates the loop iterator?
|
5,434,534 | 5,435,021 | how to remove const from member function template type signature? | I'm working on some C++ type system stuff, and I'm having a problem removing const-ness from a member function for use with function trait classes. What is really toubling here is that this works fine with G++, but MSVC10 fails to handle the partial specialization correctly, and I don't know if one of these compilers ... | I suggest you take a look at the TypeTraits.h of the loki library by Alexandrescu.
It provides a generic way to strip qualifiers, like const.
http://loki-lib.cvs.sourceforge.net/loki-lib/loki/include/loki/TypeTraits.h?view=markup
When I have some philosophical issues with meta programming c++ meta programming I tend ... |
5,434,595 | 5,434,672 | How to find and solve dependencies between global variables | I have an application which [unfortunately] contains quite some global variables. A recent crash-at-startup lead me to the following construction:
FILE1.CPP:
ClassX globalVariableX;
FILE2.CPP
ClassY globalVariableY;
Unfortunately, the constructor of class Y uses code in which globalVariableX is used.
Until now every... | The usual solution is to rely on initialization on first use.
In C++, you can use local static (in functions) to get this behavior. In C++0x (but already implemented in major compilers) this is even guaranteed to be thread-safe (the initialization, at least).
ClassX& GetClassX() {
static ClassX X; return X;
}
ClassY... |
5,434,737 | 5,435,096 | Requirements on standard library allocator pointer types | I am trying to write a quadtree sparse matrix class. In short, a quadtree_matrix<T> is either the zero matrix or a quadruple (ne, nw, se, sw) of quadtree_matrix<T>.
I'd like eventually to test different allocation schemes since this will probably impact the performance of linear algebra operations. So I will also templ... | From the tables in 20.1.5/2 it clearly indicates that the type of A<T>::pointer must be "pointer to T". Since those pointer types are normally convertible your 1 and 2 are true. It follows then that A<void>::pointer must be void*.
EDIT:
There's also explicit wording in 20.1.5/4 (it applies to what standard containers m... |
5,434,924 | 5,435,398 | Conversion from std::string to unsigned char[] | Let's suppose I have a string str which consists of characters default to hexadecimal system (0-9, a-f):
string str="1234567890abcdef";
I also have an empty array of n-length (n is known):
unsigned char arr[n]
What I would like to do is fill my array arr with values of str but in a specific manner shown below:
unsig... | Your requirements are somewhat unclear. Does the following program perform the action you desire?
#include <string>
#include <iostream>
#include <cstdio>
#include <iterator>
#include <algorithm>
void str2bin(const std::string& in, unsigned char out[])
{
const char* data = in.data();
const std::string::size_... |
5,435,271 | 5,435,392 | Zlib C++ boost inflate socket data | I am receiving data from a server through a socket using boost asio, and the data is compressed using zlib. I need to inflate this data once I get it. Is there an easy way to do this using boost? Or any other way? The code is C++.
| The Boost.Iostreams library includes a zlib decompressor filter (link). You can read a chunk of data from the socket into a buffer then decompress, or you can (hopefully, but I haven't tried it myself) chain the filter onto the socket and read decompressed data straight out of the end of the filter.
Note, however, that... |
5,435,684 | 5,435,864 | Problem: Getting buffer data | I'm trying to get my buffer copied into another buffer but I cant get the actual value.
Here is how my program flows:
1. Create random integers
2. Convert it into char
3. Store them into STL container
4. Retrieve first element from the container
5. Convert it into int form
Here is my header file:
struct BufferData
... | Change this:
memcpy(BufferSource1, *IterBuffer1, BUFFER_SIZE);
to this:
memcpy(BufferSource1, (*IterBuffer1)->m_BufferData, (*IterBuffer1)->m_Size);
Because the type of m_RecvBuffer1 is std::vector<BufferData*>, not std::vector<char*>.
Change similarly for others!
|
5,435,803 | 5,435,897 | wrapper around API using reference counting logic C++ | I am going to use heavily some C-API in my C++ application, I have a lot of functions available that I need to call in couple. For example createFoo(void*) at the beginning and freeFoo(void*) when the job is done.
So, I thought to use the RAII idiom, so I created the first wrapper with copy constructor and assignment ... | It's really easy. As an example, suppose you have the C fopen interface:
FILE* fopen(blah);
int fclose(FILE*);
Then you can wrap FILE resource with shared_ptr like this:
shared_ptr<FILE> ptr(fopen("file.txt", "rt"), fclose);
// use the file pointed by ptr
fwrite(..., ptr.get());
// FILE is automatically closed by a c... |
5,435,841 | 5,435,890 | Memory alignment in C-structs | I'm working on a 32-bit machine, so I suppose that the memory alignment should be 4 bytes. Say I have this struct:
typedef struct {
unsigned short v1;
unsigned short v2;
unsigned short v3;
} myStruct;
The plain added size is 6 bytes, and I suppose that the aligned size should be 8, but sizeof(myStruct) ret... | At least on most machines, a type is only ever aligned to a boundary as large as the type itself [Edit: you can't really demand any "more" alignment than that, because you have to be able to create arrays, and you can't insert padding into an array]. On your implementation, short is apparently 2 bytes, and int 4 bytes.... |
5,435,891 | 6,971,393 | QT Breadcrumb Navigation | I would like to add a breadcrumb navigation bar to a QT application. In KDE there is KUrlNavigator which is used by dolphin. Is there a native QT widget?
| qxtcrumbview in libqxt.org
Not documented, you need to download the source code in order to find this one.
|
5,435,997 | 5,436,117 | Which is faster (mask >> i & 1) or (mask & 1 << i)? | In my code I must choose one of this two expressions (where mask and i non constant integer numbers -1 < i < (sizeof(int) << 3) + 1). I don't think that this will make preformance of my programm better or worse, but it is very interesting for me. Do you know which is better and why?
| C expressions cannot be "faster" or "slower", because CPU cannot evaluate them directly.
Which one is "faster" depends on the machine code your compiler will be able to generate for these two expressions. If your compiler is smart enough to realize that in your context both do the same thing (e.g. you simply compare t... |
5,436,039 | 5,436,094 | C++, equality with g++ | Why this condition is never true ? Both parts of the equation are integers, so there must be equality for index = 0, 10, 20, 30, 40. I am compiling this code using g++.
for(int index = 0; index < 50; index++){
if ( (int) (10 * ( 0.1 * index) == (int)(10 * ( int ) ( 0.1 * index ) ) ) )
{
... | Your parentheses are wrong:
if ( (int) (10 * ( 0.1 * index) == (int)(10 * ( int ) ( 0.1 * index ) ) ) )
Should be:
if ( (int) (10 * ( 0.1 * index) ) == (int)(10 * ( int ) ( 0.1 * index ) ) )
|
5,436,092 | 5,436,123 | c++ casting char* to object? |
Is it possible in C++ to convert an array of chars to an object like so:
char* bytes = some bytes...
MyObject obj = (MyObject)(bytes);
?
How do I have to define the cast operator?
thanks :)
| You probably want to define a constructor for MyObject:
class MyObject {
public:
explicit MyObject(const char* bytes);
...
};
MyObject::MyObject(const char* bytes) {
// do whatever you want to initialize "MyObject" from the byte string
}
and then you can use it:
char* bytes = some bytes...
MyObject obj = MyObje... |
5,436,139 | 5,448,571 | When will C++0x be finished? | Ok, this is the first question I've asked and I didn't know you couldn't answer your own question.
Answer:
March 25, 2011. :-) I'm not kidding, it's official. Well, at least as far as the committee is concerned.
Update
Aug. 12, 2011.
The C++ FDIS has officially been approved by ISO in a unanimous vote. 21 of 21 Nati... | As Howard already said in the question, the final draft was completed on March 25, 2011.
There will now be some months of editorial changes, voting and ISO red tape before it officially becomes a standard, but on the 25th, the standards committee themselves officially signed off on it.
Sources:
https://www.ibm.com/deve... |
5,436,146 | 5,436,384 | Undefined symbol with g++ | I have implemented the tutorial example of boost for the asio library, but with seperation through a header file:
server.cpp
server.h
I build both files with another .cpp file in the following way:
g++ -I/usr/lib/jvm/java-6-openjdk/include -L/usr/local/lib -fPIC -lboost_system -shared -o libagent.so agent.cpp server.... | You're not actually linking to the boost::asio library, therefore the shared object doesn't know where to find the symbol that is being used in your class.
assuming the library is called boost_asio, you need to add:
-lboost_asio
to the link line.
... scratch that, completely wrong.
You're missing the implementation of... |
5,436,193 | 5,436,242 | Read up to a null-terminator using read() | Is there an option, part of read() that when calling read() on a file descriptor it only prints out the characters up to the null terminator?
| Sorry, no, there isn't. read() doesn't look at the data at all; it just reads as many bytes as there are (but not more than your buffer size).
I would do this with the higher-level stdio.h functions, by calling getc() (and writing to a buffer) until I saw a NUL byte, and then ungetc() on the NUL.
|
5,436,232 | 5,436,376 | What is the best data structure to implement this? [Nested Properties in C#] | I am trying to figure out how to store and organize the following data efficiently within a data structure in C#. The data are settings which each have a corresponding parameter name (string), label (string), and possibly other items.
For example, the data in C++:
//Analog Inputs
#define PROBETEMPERATURE "P33352"
#d... | something like this might help (dont know if it is the best but i would have used it)
declare Class of both types and use them like
public class AnalogInput
{
public string Label { get; set; }
public string Parameter { get; set; }
}
public class DigitalInput
{
public string Label { get; set; }
public s... |
5,436,487 | 5,442,158 | How would i be able to use GLU_RGBA or other GLU_ parameters? | hey i have yet another question. There isnt much information involved but i noticed that even though i have libglu32.a linked, and the glu.h included, im still not ablt to use GLU_ parameters
Im wondering how that is not so. would anyone have any ideas?
if any code is needed please comment and i will respond quickly.
A... | This not so much an answer but a comment on your code. I see, that you're using SFML as framework. SFML internally uses OpenGL, and sf::Image is backed by an OpenGL texture. Or in other words: There's no need to create an OpenGL texture from a sf::Image on your own. Actually SFML takes care everything is properly set u... |
5,436,660 | 5,436,755 | Do overloaded operators within classes require __declspec(dllexport) if they're used in a DLL project? | When using __declspec(dllexport), should overloaded operators also have this exportation flag assigned? For example, say you have something like:
/*
Overloaded operator (equivalent operator) returns true if x equals compared vector
*/
__declspec(dllexport) bool operator ==(const vector &v)
{
return (x == v.x && y==v... | You'd normally apply __declspec(dllexport) to the class declaration so the whole shebang gets exported. Also exports the v-table, important if the class has virtual members. Doing it one member at the time is pretty tiresome and troublesome.
No real idea why you'd skip the overload. If you made it public in the clas... |
5,436,884 | 5,437,183 | Catch Registry request C++ | I known such tools
http://portableapps.com/development/projects/registry_rapper
RegRap.exe can get through param other .exe file and catch requests to registry and save it into .ini
That is good, but I need snippt code to set such hundler inside my C++ program and for given Reg KEY return my value...
RegRap.exe written... | This post seems to say that there are no hooks for the registry and you can only long poll. Simple way to hook registry access for specific process
|
5,436,893 | 5,436,928 | Returning deep copies of objects when overloading the = operator | So I making a container class for integers and I want to overload the = operator so that I can return a deep copy of the object. My code works but the two objects point to the same address. This is the main.cpp file:
int main (int argc, const char * argv[]) {
IntList cArray(5);
for (int i = 0; i < cArray.getLe... | You're not working with pointers to IntList - operator= typically takes a const & and returns a reference to the instance being assigned to.
IntList & IntList::operator=(IntList const & source) {
...
return *this;
}
Remember that you also need a copy constructor: IntList(IntList const & source)
You can make an ope... |
5,436,977 | 5,437,370 | a "general function signature" pointer that points to an arbitrary function | I'll try to explain better what I want to do.
I read a file with function signatures, and I want to create a pointer to each function.
For example, a file that looks like this:
something.dll;int f(char* x, int y, SOMESTRUCT z)
something.dll;void g(void)
something.dll;SOMESTRUCT l(longlong w)
now, during runtime I wan... |
Function types are compile-time in C++, so it won't work, unless you can define all the types you're going to use in advance.
Its a matter of pushing the arguments to the stack (and local vars are like that) and calling the function as void (__cdecl *)(void).
With some other kinds of functions (like fastcall, or thisc... |
5,437,059 | 5,437,095 | What's the design pattern I must draw attention when i develop vector editor? | What's the design pattern I must draw attention when i develop vector editor?
Now I use composite pattern (composite draw objects) and fabric method - for creation draw objects, which make user.
And what is the patterns i can use for my vector editor?
| Most likely you need these:
Composite Pattern
Visitor Pattern
Command Pattern
And after that, you may need these as well:
Strategy
Decorator
Observer
|
5,437,117 | 5,439,967 | Global Movement Estimation of squence of images in C++ | I need to find a C++ library to find the global movement estimation for a project of super resolution of medical images. But I'm not aware of any of them. Does anyone know a library that could help me do this? I've heard of OpenCV but haven't found anything, maybe I wasn't looking at the right thing.
Thank you.
| This looks like a good starting point:
http://www.cvpapers.com/rr.html
although I'm surprised to not see VXL on the list:
http://vxl.sourceforge.net
Have fun!
|
5,437,240 | 5,437,333 | Linux C/C++ Timer signal handler in userspace | I need a function(eg signal handler) in C/C++ linux that gets activated every 'n' milliseconds. How do I setup signals etc...to register to timer events at the millisecond resolution.
Accuracy is not super critical, but need within hundred ms or so.
I am new to linux and I really don't know where to start.
| setitimer(2) is a good start, but do you really want to go asynchronous with signals? Otherwise, you could have a main loop with select(2) or poll(2) and an appropiate timeout.
|
5,437,246 | 5,437,283 | Is it better to start learning C# or C++ in the .NET world? | I have some very rusty C++ and lots of C experience, but have done little OO design or coding. I've started learning C++.NET as that seemed to be the best starting point.
I've hit restrictions in Microsoft's provision with multiple inheritance and extensions, neither work in C++.
Would I be better off starting again w... | MS wants you to use C#, so use C#. If your C++ is rusty, you'll end up wasting time learning a difficult language, which is actually a second class citizen in the .NET world.
However, C++ in the .NET world (called C++/CLI) is a wonderful tool to wrap existing non-.NET code into .NET classes.
For the multiple inheritanc... |
5,437,311 | 5,437,356 | Missing Type Specifier - Int Assumed in C++ | These second line of these is throwing this error, but I'm not sure why.
std::vector<std::string> weapons(100);
weapons[3] = "Rusty dagger";
--
Here's my entire file:
//global variables
#ifndef _GLOBAL_
#define _GLOBAL_
#include <vector>
#include <iostream>
#include <string>
//prototypes
void NPCTalk(std::string con... | weapons[3] = "Rusty dagger";
This is a statement. You can't write statements in global scope. You must put it inside a function.
|
5,437,550 | 5,437,631 | Calling a member-function from within overloaded operator delete? | This article on Binary-compatible C++ Interfaces contains the code:
class Window {
public:
// ...
virtual void destroy() = 0;
void operator delete(void* p) {
if (p) {
Window* w = static_cast<Window*>(p);
w->destroy(); // VERY BAD IDEA
}
}
};
To me, that seems wrong: operator delete() works... | I agree (assuming Window::destroy is not a static member function):
3.8p1: The lifetime of an object of type T ends when: if T is a class type with a non-trivial destructor, the destructor call starts, or [...]
3.8p5: [...] After the lifetime of an object has ended and before the storage which the object occupied is r... |
5,437,675 | 5,438,104 | Mixing ObjC and C++ with C++ template classes in more than one source | I'm just thinking of porting some old C++ sources held in my archive to iOS thus supplying a ObjC GUI, using wrappers for some C++ stuff and leave the important data working stuff within the C++ code. So, the problem is that the old sources come from Win32 MFC thus using CString class for strings and I want to replace ... | I agree with CString, as long as you stay with std::string or some other multi-platform string implementation for C++ you are not going to face any issues ( even boost works on iOS ).
I've been integrating C++/Obj-C for about two years now so you can be sure that keeping model classes in C++ ( even with heavily templat... |
5,437,708 | 5,438,735 | Easily comment (C++) code in vim | I have looked at the following question:
How to comment out a block of Python code in Vim
But that does not seem to work for me. How do I comment code easily without resorting to plugins/scripts?
| You can use the NERD commenter plugin for vim, which has support for a whole bunch of languages (I'm sure C++ is one of them). With this installed, to comment/uncomment any line, use <Leader>ci. To do the same for a block of text, select text by entering the visual mode and use the same command as above.
There are othe... |
5,437,800 | 5,437,841 | Setting a DWORD value in the registry | I'm trying to set a DWORD value in the registry. I made it work with a text value, but now I want to set another value with a numeric one(0). But it doesnt write it.
This is my code:
RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\pager", 0, KEY_ALL_ACCESS, &hKey);
RegSetValueEx(hKey, TEXT("Save"), 0, REG_SZ, (const BYTE*)0... | The biggest error is in (const BYTE*)0x00: you are casting 0x00 to a BYTE *, which means that basically you are passing a NULL pointer. Instead, you should create a DWORD variable, put the value you want to store in the registry in it and pass a pointer to it instead of that 0x00.
Also, you must change REG_SZ to REG_DW... |
5,437,813 | 5,437,868 | MSBuild.exe not building projects in parallel | I use MSBuild.exe to build my Visual C++ Solution. One project in the solution compiles to a static library (let's called it MyLib.lib), and the many other projects are small tools which link to MyLib.lib.
I compile it like this:
msbuild MySolution.sln /p:Configuration=Release /p:Platform="Win32" /maxcpucount:4
Howeve... | Only projects that don't depend on each other can be built in parallel. Clearly that's not your case, can't build the tool until the .lib is available.
EDIT: you are not using VS2010. For VS2008 you should use vcbuild.exe. Enable concurrent builds with /M4
|
5,438,183 | 5,438,889 | Algorithm for finding minimum distance between pixel and groups of pixles | I need algorithm(preferably in c++ though pseudo code is ok too) to find a group among groups of pixels that have minimum distance to one particular pixel.
The distance is defined as sum of distances of each pixel of the group to the particular pixel while each distance is equal |x|+|y| coordinates.
If its not clear en... | Updated
The first draft of this solution computed geometric (euclidean) distances when the questian referred to Manhattan distances
This makes it simpler to optimise.
For each group of pixels choose one pixel as the primary pixel. It doesn't matter which one.
For each other pixel in the group, compute its offset (... |
5,438,194 | 5,480,294 | CUBLAS - matrix addition.. how? | I am trying to use CUBLAS to sum two big matrices of unknown size. I need a fully optimized code (if possible) so I chose not to rewrite the matrix addition code (simple) but using CUBLAS, in particular the cublasSgemm function which allows to sum A and C (if B is a unit matrix): *C = alpha*op(A)*op(B)+beta*c*
The prob... | If you're just adding the matrices, it doesn't actually matter. You give it alpha, Aij, beta, and Cij. It thinks you're giving it alpha, Aji, beta, and Cji, and gives you what it thinks is Cji = beta Cji + alpha Aji. But that's the correct Cij as far as you're concerned. My worry is when you start going to things which... |
5,438,313 | 5,438,343 | Faster alpha blending using a lookup table? | I have made a lookup table that allows you to blend two single-byte channels (256 colors per channel) using a single-byte alpha channel using no floating point values (hence no float to int conversions). Each index in the lookup table corresponds to the value of 256ths of a channel, as related to an alpha value.
In al... | I would be interested in seeing some benchmarks.
There is an algorithm that can do perfect alpha blending without any floating point calculations or lookup tables. You can find more info in the following document (the algorithm and code is described at the end)
I also did an SSE implementation of this long ago, if you ... |
5,438,400 | 5,438,427 | Using tilde to get MAX value for int | I tryed to get MAX value for int, using tilde.But output is not what I have expected.
When I run this:
#include <stdio.h>
#include <limits.h>
int main(){
int a=0;
a=~a;
printf("\nMax value: %d",-a);
printf("\nMax value: %d",INT_MAX);
return 0;
}
I get output:
Max value: 1
Max value: 2147483647
I th... | You have a 32-bit two's complement system. So - a = 0 is straightforward. ~a is 0xffffffff. In a 32-bit two's complement representation, 0xffffffff is -1. Basic algebra explains that -(-1) is 1, so that's where your first printout comes from. INT_MAX is 0x7fffffff.
Your logical error is in this statement: "-(1111... |
5,438,437 | 5,438,507 | Problem when I try to free a pointer vector | I am trying to learn to free pointer in a vector, I have read the questions on this page, and follow the answers to write some test code.I grab images from a web camera and first store all the images in memory, after all images are grabbed ,I save all image into jpg format.
Everything works fine at first, I can store ... | The reason you're having issues is the image not being created with new. OpenCV being C uses malloc(). But before trying to call free(), use the function provided for this: cvReleaseImage().
Side note: Just because a function called CreateSomething returns a pointer doesn't mean you're even able to delete/free the memo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.