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 |
|---|---|---|---|---|
4,054,458 | 4,054,505 | two nearly identical calls, one works one fails | I have these template functions for use inline on device with cuda
template <class T> __device__ inline T& cmin(T&a,T&b){return (a<b)?(a):(b);};
template <class T> __device__ inline T& cmax(T&a,T&b){return (a>b)?(a):(b);};
In the code I have
cmin(z[i],y[j])-cmax(x[i],z[j])
for int arrays x,y,and z. I get the error:... | If either x or z is a const array, their element type will be const int, which is not convertible to int&.
Try with:
template<class T> __device__ inline T cmin(const T& a, const T& b)
{
return (a < b ? a : b);
}
template<class T> __device__ inline T cmax(const T& a, const T& b)
{
return (a > b ? a : b);
}
If ... |
4,054,695 | 4,054,721 | Why doesn't Createfile() have a binary flag | One of the great joys of windows programming is remembering to put 'wb' or 'rb' or ios::binary in all the file open calls so that Windows doesn't merrily convert all your 0x13s.
I just had to convert a bunch of nicely standard code to use Createfile() to get a certain flag - and it occurred to me that there is no way t... | Because CreateFile doesn't do "text-mode"/newline conversions. Those are handled at a higher level, either in FILE for the CRT or iostreams for C++.
|
4,054,850 | 4,055,292 | Efficient push_back of classes and structs | I've seen my colleague do the second snippet quite often. Why is this? I've tried adding print statements to track the ctors and dtors, but both seem identical.
std::vector<ClassTest> vecClass1;
ClassTest ct1;
ct1.blah = blah // set some stuff
...
vecClass1.push_back(ct1);
std::vector<ClassT... | If we accept that your colleague's snippet is wise, because ClassTest is expensive to copy, I would prefer:
using std::swap;
std::vector<ClassTest> vecClass1;
ClassTest ct1;
ct1.blah = blah // set some stuff
...
vecClass1.push_back(ClassTest());
swap(ct1, vecClass1.back());
I think it's clearer, and it may well be mo... |
4,054,946 | 4,056,299 | Is this the best way to do a "with" statement in C++? | Edit:
So this question was misinterpreted to such a ludicrous degree that it has no point anymore. I don't know how, since the question that I actually asked was whether my specific implementation of this—yes, known to be pointless, yes, not remotely resembling idiomatic C++—macro was as good as it could be, and whethe... | ?? attempted vb syntax into C++
with says do all the things in the following block by default referencing the object I've said to do it with right? Executes a series of statements making repeated reference to a single object or structure.
with(a)
.do
.domore
.doitall
so how is the example giving you the same syntax... |
4,054,969 | 4,055,047 | Dynamic Memory Handling Java vs C++ | I am a C++ programmer currently trying to work on Java. Working on C++ I have an habit of keeping track of dynamic memory allocations and employing various techniques like RAII to avoid memory leak. Java as we know provides a Garbage Collector(GC) to take care of memory leaks.So while programing in Java should one just... | I'm not sure what you mean by trying to take care of the memory you allocate in presence of a GC, but I'll try some mind reading.
Basically, you shouldn't "worry" about your memory being collected. If you don't reference objects anymore, they will be picked up. Logical memory leaks are still possible if you create a si... |
4,055,106 | 4,055,124 | Using overloaded operators on pointers | I overloaded the << operator of a class. How do I have to overload the operator if I want to use it on pointers, like the following?
class A {
std::string operator<<(std::string&);
}
aInst << "This works";
aPointer << "This doesnt work";
aPointer->operator<<("Whereas this works but is useless");
I hope you can he... | You need to dereference the pointer first.
A *ptr = new A();
(*ptr) << "Something";
The only other way is the way you described above
Edit: Andre's solution below is workable as well, but like he said it may not be a good idea.
|
4,055,503 | 4,055,577 | client socket sends data but server socket does not receive them. c++ buffered stream? | I am working on a project where a partner provides a service as socket server. And I write client sockets to communicate with it. The communication is two way: I send a request to server and then receive a response from server.
The problem is that I send the data to the server but apparently the server cannot receive t... | Further to Jay's answer, you can try any network packet sniffer and check whether your packets are getting to the server or not. Have a look at wireshark or tcpdump.
|
4,055,669 | 5,655,209 | Why does MAP_GROWSDOWN cause SIGBUS errors after upgrading to Centos 5.5? | I was upgrading the OS on one of our build from Centos 5.3 32bit to Centos 5.5 32bit. After doing the package update I rebooted, checked out a clean copy of the source, built and ran the unit tests. All unit tests which rely on our MemMap base class began to fail.
The crash occurs when we attempt to set the value of ... | It looks like MAP_GROWSDOWN has been removed from glibc http://bugs.centos.org/view.php?id=4767 and shouldn't be used.
|
4,055,909 | 4,055,947 | C++: Elegant way to split string and stuff contents into std::vector | I would like to split a string along whitespaces, and I know that the tokens
represent valid integers. I would like to transform the tokens into integers
and populate a vector with them.
I could use boost::split, make a vector of token strings, then use std::transform.
What is your solution? Using boost is acceptable.
| Something like this:
std::istringstream iss("42 4711 ");
std::vector<int> results( std::istream_iterator<int>(iss)
, std::istream_iterator<int>() );
?
|
4,056,176 | 4,056,216 | Template in a Template -- accessing contained type from a template type | I was trying to write a templatized quicksort function. The thought in my head was that I would write a quicksort that can operate on any data structure that has a subscript operator and an order relation on the objects contained within it, so I could do things like
quicksort<deque<int> >();
quicksort<vector<string> >(... | All of the containers have a typedef value_type that you can use to get T:
template <typename ContainerT>
void quicksort(ContainerT& container)
{
typedef typename ContainerT::value_type ElementT;
// etc.
}
That said, wherever possible, algorithms should be implemented using iterators, to further decouple them ... |
4,056,210 | 4,056,232 | Preventing keys of different hash values from landing in same bucket with unordered_set | This might be a silly question, but here goes :
I hashed a dictionary of words into an unordered_set based hash-table. My hash function was made intentionally "bad", in that all strings that contained the same set of letters would hash to the same value. I initially tried to over-ride the normal hash function behaviou... | Different hash values will not necessarily end up in different buckets. Generally a hash table will choose a bucket based on hash_value % number_of_buckets, so hashes that are equal modulo the number of buckets will wind up in the same bucket.
Essentially, you cannot guarantee anything about which hash value appears in... |
4,056,255 | 4,056,462 | Segmentation fault when ANDing enum | I have a class CField and a class CBoard containing a 2d array of CField.
When I do this:
board(0,0)->Is (CField::CHECK)
I get a segfault in Is() method. GDB points me right after the &, so I think it's related to it. What's the cause?
Full code:
http://pastebin.com/vetShYsL - header
http://pastebin.com/pGNPpa8N - sou... | The 2 phase construction of a board is a bit annoying, and you have a bunch of extra code to manage it that you don't really need.
This is the bug though
for (int i = 0; i < x; ++i)
fields [x] = new CField [y];
index fields by i not x
for (int i = 0; i < x; ++i)
fields [i] = new CField ... |
4,056,256 | 4,056,320 | C++: unions with methods? | Is there anything wrong with a union having one or more methods? Or anything to watch out for? (I can see constructors/destructors being problematic for schizophrenic reasons)
| From the C++03 & C++0x (Draft N3092) standards:
9.5 Unions
A union can have member functions (including
constructors and destructors), but not
virtual (10.3) functions. A union
shall not have base classes. A union
shall not be used as a base class.
Initializing the union using the aggregate initializer syn... |
4,056,279 | 4,056,307 | MakeFile Error for running a cpp file in ssh | CC=g++
CFLAGS=-O0
TARGET=./problem2_cpp
OUTFILE=../output/cpp.txt
$(TARGET): problem2.o
$(CC) $(CFLAGS) -o $(TARGET) problem2.o
problem2.o: problem2.cpp
$(CC) $(CFLAGS) -c problem2.cpp
clean:
rm -f *.o $(TARGET) $(OUTFILE)
run: $(TARGET)
$(TARGET) <$(INFILE) >$(OUTFILE)
I am a rather simple makefile to compile,... | quota_ufs: over hard disk limit (pid 20159, uid 58861, inum 5132792, fs /home)
ld: fatal: file ./problem2_cpp: creation interrupted: Disc quota exceeded
You have run out of disk quota on the machine you are using. I suggest deleting old files in your directory, or contacting your (university?) help desk to have your ... |
4,056,348 | 4,056,404 | How can I find the depth of a recursive function in C++ | How can I find the current depth inside a recursive function in C++ without passing in the previous level? i.e. is it possible to know how many times the function was called without using a parameter to keep track of the level and passing that number in as a parameter each time the function is called?
For example my re... | Building on the answer already given by JoshD:
void recursive()
{
static int calls = 0;
static int max_calls = 0;
calls++;
if (calls > max_calls)
max_calls = calls;
recursive();
calls--;
}
This resets the counter after the recursive function is complete, but still tracks the maximum... |
4,056,431 | 4,068,992 | C++ decision tree with pruning | Can you recommend me a good decision tree C++ class with support for continous features and pruning(its very important)? Im writing a simple classifier(two classes) using 9 features. I've been using Waffles recently, but looks like tree is overfitting so i get Precision around 82% but Recall is around 51% which is inac... | Have to answer my own question, as long as no one answered.
I used decision tree implementation from OpenCV library, very flexible implementation and fast enough for my tasks.
|
4,056,450 | 4,057,723 | Sandbox Virtual Machine for an Application (C++ vs. C#) | I'd like to write a sandbox virtual machine for executing a compiled program. How do you think: which of these two languages would be better to use if we consider performance? Or maybe you suggest another one?
| The performance of your VM will be much more affected by how you implement it rather in what language. If you implement it the same way in c# and c++ the performance will be comparable.
The thing that speaks in favor of c++ is that you can execute parts of the native code from your sandboxed application directly. It is... |
4,056,451 | 4,056,503 | Is it necessary to delete elements as an array shrinks? | I'm a student writing a method that removes zeros from the end of an array of ints, in C++. The array is in a struct, and the struct also has an int that keeps track of the length of the array.
The method examines each element starting from the last, until it encounters the first non-zero element, and marks that one as... | If p->elems is a pointer, then so is p->elems + i (assuming the operation is defined, i.e. i is of integral type) - and p->elems + i == &p->elems[i]
Anyhow, you most likely don't want to (and cannot) delete ints from an array of int (be it dynamically or automatically allocated). That is
int* ptr = new int[10];
delete ... |
4,056,527 | 4,056,802 | Draw to HDC with user allocated memory | I have an windowless IViewObject object.
I want to call its Draw function to render into Opengl PBO memory (alternatively OleDraw is simpler).
Right now i first create an HBITMAP using CreateDIBSection (which allocates its own memory) and then copy from this into my PBO memory. However, I'd like to avoid this extra cop... | What you're trying to do is very logical IMHO. However unfortunately AFAIK there's no conventional way to do this.
According to WinAPI DIB sections either allocate their own memory or work with the file mapping. OTOH OpenGL manages its memory in its own way.
There exists an option to create a DIB from any memory block,... |
4,056,604 | 4,058,670 | Trying to make an array of DirectX vertex with out knowing until run time what type they will be | Bit of background for those who don't know DirectX. A vertex is not just an XYZ position, it can have other data in it as well. DirectX uses a system known as Flexible Vertex Format, FVF, to let you define what format you want your vertexs to be in. You define these by passing a number to DirectX that use bitwise or to... | Altering your code, this should do it:
void* Utils::MergeArrays(char *ArrayA, char *ArrayB, int elementSizeA, int elementSizeB, int numElements)
{
char *packedElements = (char*)malloc(numElements* (elementSizeA + elementSizeB));
char *nextElement = packedElements;
for(int i = 0; i < numElements; ++i)
{
... |
4,056,766 | 4,056,854 | C++ casting of templated class | I have a question about templates. I would like to have a templated class that contains, say, an array of either float's or double's.
I can write a clone() function that duplicates it. No problem. However, I would like to have another function called cast() that does a translation back and forth between double and floa... | f3->cast<double>(); // Error here
In this line, the compiler does not know if the < after f3->cast is supposed to mean the beginning of template arguments or if it is a less than comparison operator.
To explicitly specify that it stands for beginning of template argument. The correct way is
f3->template cast<double>(... |
4,056,797 | 4,057,521 | Boost regex incorrect syntax | I am using the Boost library under c++ to parse a load of text. I seem to be having a problem with this string
text text text Seat 6: player_name (11,111) text text text
I am trying to match on the middle bit, the seat number can be anything between 1 and 9, the player_name can be any character a-zA-Z and include num... | You say the player name can include lowercase letters, but that's not what your code says. The code says player_name can only be numbers and uppercase letters. Perhaps in your C# code you set a flag to omit case-sensitivity from the check. In Boost, that's regex_constants::icase; use it when creating the regex object.
... |
4,056,966 | 4,056,986 | C++ basic qt question | Does someone know a fast way to add the ability to rotate and move a 3D model using Qt?
Obviously, I have to make changes to the world matrix based on the mouse and keyboard movements, and hence I should somehow handle the appropriate mouseEvents and keyboardEvens.
For a 3d camera this seems a bit tricky and although I... | This might be what you're looking for. It is an example that loads .obj models and allows you to rotate them with the mouse. It also shows you how to render Qt dialogs within the OpenGL scene.
|
4,057,100 | 4,057,185 | Undefined reference to member functions | I had just thought I resolved a problem, but it seemed another one cropped up--or at least the same problem in another form. Now when I try to rebuild everything as suggested in the answer to that question, all Qt Creator shows in build issues is a one line collect2: ld returned 1 exit status
Here's some of the compile... | I'll try to guess. You are either using namespaces wrong (i.e. put #include directive in the body of namespace). Or you haven't deleted debug and release directories completely as you were advised.
|
4,057,155 | 4,057,178 | Dividing 3D points with xyz coordinates in to 10 domains based on spatial proximity | I have a set of xyz coordinates for points distributed on a arbitrary 3D surface.(about 50000) I need to group these points in to 10 domains each containing approximately 1/10th of data points according to spatial proximity. Basically 10 surface patches on the surface. Thanks.
| Looks like you want a clustering algorithm.
I has luck with k-means++ before.
See http://en.wikipedia.org/wiki/K-means_clustering for the k-means algorithm
and http://en.wikipedia.org/wiki/K-means%2B%2B for the k-means++ variants.
|
4,057,258 | 4,057,372 | Faster than binary search for ordered list | is there an algorithm that is faster than binary search, for searching in sorted values of array?
in my case, I have a sorted values (could be any type values) in an A array, I need to return n if the value I was looking is in range of A[n] and A[n+1]
| You can do better than O(log n) if the values are integers, in which case the best worst-case running time you can achieve, in terms of n, is O(sqrt(log n)). Otherwise, there is no way to beat O(log n) unless there are patterns in the input sequence. There are two approaches used to beat O(log n) in the case of integer... |
4,057,273 | 4,057,292 | How do I catch a C++ exception? | In my C++ app, I'm making a call to System() that crashes the app sometimes (it's a service). I'd like to catch the exception that is thrown and log it. I don't know what exactly to catch, though, and I can't even do a blanket catch:
try
{
system(myCommand);
}
catch (...)
{
Log("Error!"); // this is a custom log ... | If catch(...) isn't catching an exception, an exception isn't being thrown. Not all errors raise exceptions. system is a hold-over from the days of C, and definitely doesn't raise any exceptions.
|
4,057,319 | 4,057,333 | Is setlocale thread-safe function? | I need to change locale in the thread to parse a double with strtod() correctly, I'm using setlocale() for this (C++). Is it thread safe?
Update: Another problem. When I invoke setlocale() in my main() function it doesn't affect in other routines deeper. Why??? There is a lot of code, so it's problematic to write the ... | You need to consult the documentation for whatever implementation you're using. C++ doesn't currently specify anything about threads so it comes down to the implementation (which you haven't yet told us).
For example, my Linux manpage for setlocale has the snippet:
This string may be allocated in static storage.
whic... |
4,057,320 | 4,057,326 | Odd error message when instantiating a template class | I am getting an error I do not understand. There was even a similar question asked on SO that I found, but the fix given is already in my code.
I am getting an error in this line:
ForestNode<NODETYPE> foo = new ForestNode<NODETYPE> ForestNode(bar);
that reads :
\project 4\forest.h|85|error: expected ',' or ';' before... | You have the type name twice in the constructor call, try:
ForestNode<NODETYPE> foo = new ForestNode<NODETYPE>(bar);
|
4,057,389 | 4,057,398 | Boost.Program_options syntax | I'm currently reading the Boost.Program_options tutorial.
Here is some of the code they introduce:
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("compression", po::value<int>(), "set compression level")
;
I understand the... | I suppose desc.get_options() returns an object of a class that defines operator() which in turn returns the same object. So the indented lines are calls to this operator with arguments in brackets.
Looking at boost/program_options/options_description.hpp you can see that the class in question is options_description_eas... |
4,057,445 | 4,057,457 | Using comparator for STL set | Check the following code:
string toLowerCase(const string& str) {
string res(str);
int i;
for (i = 0; i < (int) res.size(); i++)
res[i] = (char) tolower(res[i]);
return res;
}
class LeagueComparator
{
public:
bool operator()(const string& s1, const string& s2)
{
return toLower... | Your comparator, thanks to the toLowerCase, says that "aLeague" == "ALeague". Since (according to your comparator) "aLeague" < "ALeague" == false and "ALeague" < "aLeague" == false, they must be equivalent. And inserting an equivalent element into a set doesn't do anything.
|
4,057,468 | 4,057,472 | Calculating with C/C++ using float | I'm practising with C, writing simple programs. The little program below should just get 3 numbers from the user and multiplicate them. My problem is that i'm a bit confused about the variable type i must use. I want the program to take any number such as 5, 5.673434, 99.123 and so, calculate with them and print ou... | You need to declare the variables as float
float num1, num2, num3;
|
4,057,688 | 4,058,829 | Create automation macro support within an application | I need to get an automation macro like thing within our desktop application. The desktop app will probably be in VB.NET or C#.net.
The reason is to enable the user to record and replay certain tasks that they'd like to automate. Something like macros within office apps and visual studio.
The first thing that comes to m... | Are you thinking of macros that are just for "record-replay" of some consecutive actions? This might be pretty well doable if you use the Command pattern in your UI programming. Then every user action is described by an object (derived from an abstract Command class having a "execute()" method). Now recording and repla... |
4,057,774 | 4,057,813 | Instantiation of objects in conditionals c++ | let's say I want to instantiate a different type of object depending on certain circumstances, so i would instantiate them inside the body of an if statement. The problem is if you want to use that object later, you need to declare it before instantiation. How does one declare a generic object. Is there something si... | Unlike Java, C++ has no "mother" object which all classes inherit from. In order to accomplish what you're talking about, you'd need to use a base pointer of your own class hierarchy.
Animal* a;
if (...) a = new Cat();
else if (...) a = new Dog();
Also, because there's no garbage collection either, it's better to use... |
4,057,948 | 4,058,060 | Initializing a member array in constructor initializer | class C
{
public:
C() : arr({1,2,3}) //doesn't compile
{}
/*
C() : arr{1,2,3} //doesn't compile either
{}
*/
private:
int arr[3];
};
I believe the reason is that arrays can be initialized only with = syntax, that is:
int arr[3] = {1,3,4};
Questions
How can I do what I want to do (that
is, initialize a... |
How can I do what I want to do (that is, initialize an array in a constructor (not assigning elements in the body)). Is it even possible?
Yes. It's using a struct that contains an array. You say you already know about that, but then I don't understand the question. That way, you do initialize an array in the const... |
4,057,985 | 4,063,440 | Disabling stdout buffering of a forked process | I wrote a code in C/C++ which forks a child process, duplicates the stdin/stdout into a pipe ends and calls execvp.
Everything is working fine (i.e. the output from stdin/err/out is captured by the parent process)
The problem is that the child stdout is buffered.
so if the child code looks like this:
printf("Enter any ... | Actually, after struggling with it a bit, it seems like the only solution to this problem is by making the 'parent' process pretending to be a terminal using the OS pseudo terminal API calls.
One should call 'openpty()' before the fork(), and inside the child code, he should call 'login_tty(slave)' the slave is then be... |
4,058,054 | 4,058,061 | How do I check if a element is not present inside of a vector? | This compiles and runs ok on Visual C++ 2010 Express but it only checks against the [2] element: "Fish".
int main()
{
vector<string> words;
string temp;
vector<string> disliked(3);
disliked[0] = "Broccoli";
disliked[1] = "Mushrooms";
disliked[2] = "Fish";
whil... | if (std::find(disliked.begin(), disliked.end(), words[i]) == disliked.end()) {
cout << words[i] << " ";
} else {
cout << "BLEEP" << " ";
}
If you replace std::vector<string> disliked(3); with std::set<string> disliked; it works faster.
std::set<string> disliked;
disliked.insert("Broccoli");
disliked.insert("Mush... |
4,058,151 | 4,058,203 | I think I may have come up with an example of rvalue of array type | C++03 §4.2 N°1:
An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to an rvalue of type “pointer to T.” The result is a pointer to the first element of the array.
What has been confusing in this statement for a long time for me was that I didn't quite understand what an rvalue ... | Yes, you are correct. The expression is an rvalue of array type. This is not a defect - the committee knows about it, and it was also a common issue in C89, which only allows conversion to pointers for lvalues of array types. As a consequence, you could not index or dereference an array like f().a. C99 fixed this, and ... |
4,058,261 | 4,058,285 | SDL changing cursor to Windows default | I'm making a simple windowed game and I want a standard system cursor instead of SDL's black one. Is this possible without manual creation of cursor?
| This is not possible as far as I know. Because SDL works on all major platforms, even those without default cursors, SDL creators decided to always use a custom cursor. Drawing the default system cursor shouldn't be that hard though - just load the .cur file and paint it as a bitmap.
|
4,058,327 | 4,058,340 | Can I determine how much valid memory is addressed by a char * argument? | I have a function like:
// string is a null-terminated char array. Replace all a in the string with b
void ReplaceCharInString(char *string, char a, char b)
{
// loop over the string char by char, to find all "a"s and replace them with "b"
}
I'm doing the defensive programming. The problem is the implementation replie... | No, you cannot check this and have to trust the user of the function to pass an actual correctly null-terminated string.
This is also the way all the C standard library functions like strcpy(), strlen(), ... work.
|
4,058,339 | 4,058,656 | What is 0xFF and why is it shifted 24 times? | #define SwapByte4(ldata) \
(((ldata & 0x000000FF) << 24) | \
((ldata & 0x0000FF00) << 8) | \
((ldata & 0x00FF0000) >> 8) | \
((ldata & 0xFF000000) >> 24))
What does that 0x000000FF represent? I know that decimal 15 is represented in hex as F, but why is it << 24?
| Here is a hex value, 0x12345678, written as binary, and annotated with some bit positions:
|31 24|23 16|15 8|7 bit 0|
+---------------+---------------+---------------+---------------+
|0 0 0 1 0 0 1 0|0 0 1 1 0 1 0 0|0 1 0 1 0 1 1 0|0 1 1 1 1 0 0 0|
+---------------+--------------... |
4,058,608 | 4,058,649 | Beginner template compile error - Having trouble passing function as arg | Most of my classes have lists as private data members. As such, most of them also have adder/remover public members. I noticed I was writing basically the same thing for each of the adders, so I thought I'd turn it into a template.
Here's what I've got:
template <class N, class I>
void add(N element, std::list<N> & con... | Because you want to use a method, you have to use a pointer-to-member-function:
template <class N, class I>
void add(N* element, std::list<N*>& container, I (N::*f)() const,
std::string successmsg, std::string exceptmsg) {
typename std::list<N*>::iterator it;
it = find(container.begin(), container.end(), element);... |
4,058,705 | 4,059,394 | How can I write a variable of a user-defined type into a stream | I dont mean a variable in a class but a default value for the class as a whole.
struct Scalar {
unsigned int value;
void toThePowerOf(int power);
// etc.
}
I'd like to be able to do something like
Scaler foo;
foo.value = 2;
foo.toThePowerOf(2);
std::cout << foo << std::endl; // Outputs 4!
Is that possib... |
I meant a default value for the class, so if you called that object by just its name foo it would return foo.value by default.
It is actually possible to define an implicit conversion from Scalar to int:
struct Scalar
{
unsigned int value;
operator int() const
{
return value;
}
};
int main()... |
4,058,821 | 4,058,929 | C++ backend with C# frontend? | I have a project in which I'll have to process 100s if not 1000s of messages a second, and process/plot this data on graphs accordingly. (The user will search for a set of data in which the graph will be plotted in real time, not literally having to plot 1000s of values on a graph.)
I'm having trouble understanding us... | The simplest way to interop between a C/C++ DLL and a .NET Assembly is through p/invoke. On the C/C++ side, create a DLL as you would any other. On the C# side you create a p/invoke declaration. For example, say your DLL is mydll.dll and it exports a method void Foo():
[DllImport("mydll.dll")]
extern static void Foo();... |
4,058,994 | 4,059,292 | How to release the reference of bind arguments boost::signals2::signal keeps? | I found some objects in my C++ program can't be released due to the Signal2 of boost won't release those arguments in object created by boost::bind. Here is the code to reproduce the problem:
#include <iostream>
#include <string>
#include <boost/bind.hpp>
#include <boost/signals2.hpp>
#include <boost/shared_ptr.hpp>
... | Ensuring release of connections appears to be idiosyncratic per the info here - this is for signals, but the issue remains in signals2.
In your case, the modified version below does what you want, I think:
#include <boost/bind.hpp>
#include <boost/signals2.hpp>
#include <boost/scoped_ptr.hpp>
using namespace std;
us... |
4,059,157 | 4,059,303 | When encoding actually matters? (e.g., string storing, printing?) | Just curious about the encodings that system is using when handling string storing(if it cares) and printing.
Question 1: If I store one-byte string in std::string or two-byte string in std::wstring, will the underlying integer value differ depending on the encoding currently in use? (I remember that Bjarne says that e... |
(I remember that Bjarne says that
encoding is the mapping between char
and integer(s) so char should be
stored as integer(s) in memory)
Not quite. Make sure you understand one important distinction.
A character is the minimum unit of text. A letter, digit, punctuation mark, symbol, space, etc.
A byte is the ... |
4,059,258 | 4,059,266 | Is there a better way to initialize an array? | Given an array map with size of 256, what is the best way to initialize it so that each element is false?
bool map[256];
for (int i=0; i<256; i++)
{
map[i] = false;
}
Thank you
| bool map[256] = { false };
edit: for a reference to the standard as to why this is legal, see the answers below.
|
4,059,326 | 4,059,471 | Move ctor is not called | Am I doing something wrong (again)?
#include <iostream>
using std::cout;
struct Map
{
Map()
{
cout << "Map()\n";
}
Map(const Map& pattern)
{
cout << "Map(const Map& pattern)\n";
}
Map(Map&& tmp)
{
cout << "Map(Map&& tmp)\n";
}
};
Map createMap()
{
retu... | I slightly modified your main routine to understand the output better:
int main()
{
std::cout << "default\n";
Map m;
std::cout << "\ncopy\n";
Map m1(m);
std::cout << "\nmove\n";
Map m2(Map(m1));
std::cout << "\nmove\n";
Map m3(createMap());
}
And here is the output with g++ -fno-elid... |
4,059,328 | 4,059,360 | Slow down a Windows Process? | How can I slow down a Windows Process?
I understand that I need to hook QueryPerformanceCounter but what do I need to do next?
Need help for Delphi or C++
| I am not sure I understand the relationship of hooking QueryPerformanceCounter to slowing down a process that you described. Perhaps if you elaborate in the original question or a comment, I can help you further.
To answer your question, you can use cpustres.exe from the Windows 2000 resource kit to put a load on your ... |
4,059,528 | 4,060,018 | C++ Program crashes when reading object from random access file | I have the following User.h that holds several attributes (strings). User.cpp has all the definitions.
//User.h
#ifndef USER_H
#define USER_H
#include<iostream>
#include <cstring>
using namespace std;
class User{
string username;
public:
User();
string getUsername() const; ... | I think the issue is that you are mixing C++ code with a C mindset.
What you should really be doing here is use the extraction operator, opeartor>>(), along with the C++ IO streams. This, as opposed to using the C standard IO along with the read() function. For writing an object, use the insertion operator operator<<()... |
4,059,686 | 4,059,711 | C++ Gdiplus::Font changing font size and family | Look this code
Gdiplus::Graphics g(hDC);
Gdiplus::Font *f = new Font(L"Times new roman", 16);
Gdiplus::SolidBrush b(Gdiplus::Color(255,0,0,0));
g.DrawString(L"Hello", 5, f, &Gdiplus::StringFormat(), &b);
// Now i want to change font styles
// using f->setSize() or f->setFontFamily().
g.DrawString(L"Hello", 5, f, &Gd... | Nope, you have to ceate a new instance of the Font class to alter the style.
|
4,059,742 | 4,711,689 | Line Counter for VS 2010 | I'm looking for a line counting tool like Project Line Counter by Oz Solomon: Project Line Counter. This add-in worked perfectly for me with VS 2005 and 2008. But, unfortunately, Oz has no time to develop it further or to adapt it to VS 2010.
Do you know some great line counting tool for C++ code that perferably (but n... | This is a project based on Project Line Counter by Oz Solomon, and it improves it in some regards but the line-counting algorithms seems to be the same:
http://www.codeproject.com/KB/macros/LineCounterAddin.aspx
It has an update for VS 2010 made by it's users (see the comments):
http://shiz.wussie.nl/LineCounterAddIn20... |
4,059,743 | 12,836,779 | How declare return type as inner class of template typename? | How declare this:
template<typename T>
(T::ABC)& get();
it gives error:
error: expected constructor, destructor, or type conversion before ‘&’ token
| The correct form is without parentheses
typename T::ABC
because the form with parentheses
(typename T::ABC)
is a cast operator and not a type!
Moreover, the keyword typename is required because T:ABC is a "dependent type": if you don't use typename, the expression T:ABC is interpreted as if ABC were a member of the c... |
4,059,773 | 4,059,879 | Generate XML documentation comments for /// in Visual Studio 2010 C++ | I need comment my function prototype (written in C/C++) with summary, returns, param tags. How can I persuade Visual Studio to insert xml tags after three forward slashes like in C#? I found one solution. When I rename xx.h xx.cs in C++ project, I can use /// for generating xml comments (IntelliSense in xml comments wo... | This functionality isn't buit-in. You can try using Visual Studio add-ins. I haven't used Atomineer Utils Pro Documentation myself, but it looks promising. It generates documentation comments and supports C++. It costs $10 though.
|
4,059,775 | 4,059,934 | Convert ISO-8859-1 strings to UTF-8 in C/C++ | You would think this would be readily available, but I'm having a hard time finding a simple library function that will convert a C or C++ string from ISO-8859-1 coding to UTF-8. I'm reading data that is in 8-bit ISO-8859-1 encoding, but need to convert it to a UTF-8 string for use in an SQLite database and eventually ... | If your source encoding will always be ISO-8859-1, this is trivial. Here's a loop:
unsigned char *in, *out;
while (*in)
if (*in<128) *out++=*in++;
else *out++=0xc2+(*in>0xbf), *out++=(*in++&0x3f)+0x80;
For safety you need to ensure that the output buffer is twice as large as the input buffer, or else include a... |
4,059,932 | 4,059,936 | What is the meaning of a const at end of a member function? | What exactly does the const keyword in C++ mean when it's written at the end of a member function (after the argument list)?
| It means that *this is const inside that member function, i.e. it doesn't alter the object.
The keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of... |
4,060,082 | 4,060,090 | Why can't the type be deduced in this template function? | template<typename T>
std::istream & read(std::istream & istr, typename std::enable_if<std::is_pod<T>::value, T>::type & value)
{
return istr.read( reinterpret_cast<char*>(&value), sizeof(T));
}
int main()
{
int x;
read(cin, x); // error here
}
error C2783: 'std::istream &read(std::istream &,std::enable_... | template<typename T>
std::istream & read(std::istream & istr, T value,
typename std::enable_if<std::is_pod<T>::value>::type* = 0)
{
return istr.read( reinterpret_cast<char*>(&value), sizeof(T));
}
Or
template<typename T>
typename std::enable_if<std::is_pod<T>::value, std::istream>::type &
read... |
4,060,097 | 4,060,161 | After a sequence of new/delete on structs, I seem to have memory loss | I have a linked list of structs each of which contains an integer and a pointer to the next struct. Before populating this struct by a sequence of new commands, I note down the memory used (say Mem_1) by this program in Windows Task Manager under "Mem Usage". The actual linked list creation occurs next. (See void popul... | The number you are looking at unfortunately does not reflect what you think it does: the net amount of memory that your program has allocated using new calls that are unmatched by delete is probably less than what the operating system (OS) thinks your process owns (that's the number you are viewing here).
This is bec... |
4,060,210 | 4,060,263 | C++ How to find char in a char array by using find function? | How to find char in a char array by using find function? If I just for loop the vowel then I could have gotten the answer but I'm asked to use std::find.. Thanks.
bool IsVowel (char c) {
char vowel[] = {'a', 'e', 'i', 'o', 'u'};
bool rtn = std::find(vowel, vowel + 5, c);
std::cout << " Trac... | bool IsVowel (char c) {
char vowel[] = {'a', 'e', 'i', 'o', 'u'};
char* end = vowel + sizeof(vowel) / sizeof(vowel[0]);
char* position = std::find(vowel, end, c);
return (position != end);
}
|
4,060,213 | 4,060,253 | Why does ptr_fun(tolower) doesn't compile in mingw? | I'm trying to compile the following program using Qt Creator 2.0.1:
void f()
{
string a = "abc";
transform(a.begin(), a.end(), a.begin(), ptr_fun(tolower));
}
mingw throws the following error:
no matching function for call to ptr_fun( < unresolved overloaded function type > )
That function compiles fine with V... | The problem is the ambiguity introduced by the function template
template <class charT> charT tolower(charT c, const locale& loc);
I guess that mingw has included <locale> indirectly from one of the headers your program includes, whereas VC++ didn't.
You can fix this by disambiguating tolower with a cast:
typedef int... |
4,060,256 | 4,060,270 | How to keep alive a program in C++? | I'm using Visual C++ 2010 Express and I just started learning C++.
So when I want to run this code:
#include <iostream>
using namespace std;
int main(){
cout << "Hello World! ";
return 0;
}
It works, but the program exits immediately after I started it, how should I keep the program alive?
| If it's just to read the output, you don't need the program to stay "alive", just run it from a command prompt window and the output will remain visible. You can also use a debugger to break execution at a particular point.
There are plenty of ways, good and bad, to do it with code:
#include <iostream>
using namespace ... |
4,060,273 | 4,060,344 | Why aren't objects being pushed to this vector (when it's a member of a struct)? | I have the following code, which loops through an array of menuoptions and on each iteration, creates a ScaledRect object and pushes it to a vector. This vector is a member of a struct.
I have verified that the ScaledRect is created with the correct values, yet when I print back the contents of the regions vector ( in... | This is utterly wrong:
size_t numbytes = GetSizeForInterfaceObj();
char memory = new char[numbytes];
pfunc(memory);
Even if we "fix" it:
size_t numbytes = GetSizeForInterfaceObj();
char* memory = new char[numbytes]; // note pointer
pfunc((interface*)memory); // and cast
Your object has never been constructed, so th... |
4,060,363 | 4,060,387 | C++ How to have "NOT" (!) in Predicate? | It might be a stupid question but just wonder if there is any workaround. :)
Is there any way to have "Not" in Predicate?
Example:
std::remove_if(s.begin(), s.end(), !IsCorrect);
// ^
Or, Do I have to create IsNotCorrect function anyways?
| You can do it using std::not1, which negates a unary predicate:
#include <functional>
std::remove_if(s.begin(), s.end(), std::not1(std::ptr_fun(IsCorrect)));
If IsCorrect is an Adaptable Function then you don't need ptr_fun, but if it's just a plain function then you do.
|
4,060,411 | 4,060,428 | Does std::string use string interning? | I'm especially interested of windows, mingw.
Thanks.
Update:
First, I thought everyone is familiar with string interning.
http://en.wikipedia.org/wiki/String_interning
Second, my problem is in detail:
I knocked up a string class for practice. Nothing fancy you know, i just store the size and a char * in a class.
I use ... | Simply put, no. String interning is not feasible with mutable strings, such as all std::string-objects.
|
4,060,483 | 4,060,497 | Why is the 'Declare before use' rule not required inside a class? | I'm wondering why the declare-before-use rule of C++ doesn't hold inside a class.
Look at this example:
#ifdef BASE
struct Base {
#endif
struct B;
struct A {
B *b;
A(){ b->foo(); }
};
struct B {
void foo() {}
};
#ifdef BASE
};
#endif
int main( ) { return 0; }
If BASE is de... | That's because member functions are compiled only after the whole class definition has been parsed by the compiler, even when the function definition is written inline, whereas regular functions are compiled immediatedly after being read. The C++ standard requires this behaviour.
|
4,060,558 | 4,060,590 | How to extract the largest object, based on an attribute, from a vector? | Let's say I have a bunch of Donut objects, and each of these donuts has a public integer attribute diameter. If I have a vector of donuts, how can I extract the donut with the smallest or largest diameter?
| You use std::min_element and std::max_element. For example, given a std::vector<int>:
std::vector<int> v;
std::vector<int>::iterator it = std::max_element(v.begin(), v.end());
// 'it' points to the largest element in 'v'
If you want to compare elements using something other than operator< (which is used by default), ... |
4,060,601 | 4,060,616 | make sounds (beep) with c++ | How to make the hardware beep sound with c++?
| Print the special character ASCII BEL (code 7)
cout << '\a';
Source
|
4,060,902 | 4,061,039 | C# iterators and pointers? | I know there are no pointers in C#, but I am trying to figure out how to do the following, which I would have done with pointers (or better yet, iterators) in C++ (I am taking a course in C#, but I already know C++).
We got an assignment to write a simple "store" program (inventory, transactions, etc.). My first idea (... | You don't need to do anything special to use references, they are used by default in C#.
I'm assuming you'd do something like this in C++:
class Sale {
public:
void AddItem(Item* i) {
items.push_back(i);
}
private:
std::vector<Item*> items;
};
In C#, since it uses references rather than pass b... |
4,061,000 | 4,063,794 | How to enumerate a BOOST_ENUM with BOOST_FOREACH? | Can somebody please explain me how to enumerate a BOOST_ENUM using BOOST_FOREACH ?
The example below show that I got it to work with std::for_each, but not with BOOST_FOREACH.
Sample code :
BOOST_ENUM_VALUES( MyEnum,
const char *,
(xMin)("xMin")
(xMax)("xMax")
(yMin)("yMin")
(yMax)("yMax")
... | Your example code above compiles and runs just fine for me with gcc 4.5.1 and vc2010 (after adding the corresponding #include's, that is). I tried with enum_rev4.6 from the vault. What compilation errors do you see?
|
4,061,128 | 4,061,157 | How to pass 2-D vector to a function in C++? | If it is passed, is it passed by value or by reference?
void printMatrix(vector<vector<int>> *matrix);
...
vector<vector<int>> matrix(3, vector<int>(3,0));
printMatrix(&matrix1);
| Since your function declaration:
void printMatrix(vector< vector<int> > *matrix)
specifies a pointer, it is essentially passed by reference. However, in C++, it's better to avoid pointers and pass a reference directly:
void printMatrix(vector< vector<int> > &matrix)
and
printMatrix(matrix1); // Function call
This lo... |
4,061,162 | 4,061,262 | Calling primitive operator-functions explicitly in C++ | int a, b, c;
//do stuff. For e.g., cin >> b >> c;
c = a + b; //works
c = operator+(a,b); //fails to compile, 'operator+' not defined.
This on the other hand works -
class Foo
{
int x;
public:
Foo(int x):x(x) {}
Foo friend operator+(const Foo& f, const Foo& g)
{
return Foo(f.x + g.x);
}
}; ... | Firstly, invoking built-in operators as functions will not work simply because the language specification never says that such functions exist. Built-in operators are just operators. There are no implementing functions behind them simply because the language specification never suggests their existence. Function-based ... |
4,061,211 | 4,061,413 | Where to find C++ reference for Internet Explorer extension | I've just started building an extension for internet explorer using c++. I haven't been able to find the reference for it, where is it?
| Browser Extensions reference on MSDN
|
4,061,237 | 4,061,265 | How to specify color using a VARIANT | I need to set the color of an HTML element, I've managed to get a reference to the style but I now need to pass a VARIANT to the put_color method and I can't find information regarding how you construct a variant.
How would I go about specifying the color #ffaaaa for the put_color call?
CComPtr<IHTMLStyle> spStyle = ht... | You need to wrap the colour string in a BSTR value, which is one of the types accepted by a VARIANT:
VARIANT color;
color.vt = VT_BSTR;
color.bstrVal = SysAllocString(TEXT("#ffaaaa"));
spStyle->put_color(color);
VariantClear(&color);
|
4,061,289 | 4,061,317 | How do tabs work for text boxes? | I'm making a game gui api and I'm wondering how to implement tabs. I'm using freetype for text. When I try to render '\t' It looks like a square. I'm wondering how tabs are implemented because they are not a fixed width.
Thanks
| For a fixed-width font you could compute how many spaces to the next tab stop, but the general solution is to stop rendering when you hit a tab, move to the next tabstop, and then render the text that comes after the tab character starting from there. Where the tabstops are is up to you, but a good default is probably ... |
4,061,345 | 4,063,188 | How to get the actual COM port number with SetupDiGetDeviceRegistryProperty | I'm trying to get a list of available COM ports with the "Windows 2000"-method explained here:
http://www.codeproject.com/KB/system/setupdi.aspx
My current code: http://pastebin.ca/1977670
This is what I get:
\\?\ftdibus#vid_0403+pid_6001+ftf479xra#0000#{86e0d1e0-8089-11d0-9ce4-08003e301f73}
USB Serial Port (COM13)
USB... | You can use SetupDiOpenDevRegKey to open the device's registry and query the "PortName" value; this will give you back something like "COM4". There are a few more ways to query COM ports.
|
4,061,438 | 4,061,458 | What do I need to do before deleting elements in a vector of pointers to dynamically allocated objects? | I have a vector that I fill with pointers to objects. I am trying to learn good memory management, and have a few general questions:
Is it true that when I am done with the vector, I must loop through it and call delete on each pointer?
Why don't I have to call delete on the vector or any other variable I declare with... |
Yes
Vectors are implemented using template memory allocators that take care of the memory management for you, so they are somewhat special. But as a general rule of thumb, you don't have to call delete on variables that aren't declared with the new keyword because of the difference between stack and heap allocation. I... |
4,061,514 | 4,061,522 | C++ object created with new, destroyed with free(); How bad is this? | I am working on modifying a relatively large C++ program, where unfortunately it is not always clear whether someone before me used C or C++ syntax (this is in the electrical engineering department at a university, and we EEs are always tempted to use C for everything, and unfortunately in this case, people can actuall... | Yes it does matter.
For memory obtained using new you must use delete.
For memory obtained using malloc you must use free.
new and malloc may use different data structures internally to keep track of what and where it has allocated memory. So in order to free memory, you have to call that corresponding function that ... |
4,061,562 | 4,062,500 | VS2008 Compile error with <winsock2.h> | Getting heaps (105) of redefine & syntax errors when trying to compile my VS2008 c++ project with <winsock2.h> included. Running Windows 7 64bit.
I have googled and searched and the answer seems pretty uniform but it doesn't seem to work for me.
Tried putting #include <winsock2.h> before #include <windows.h>. Also trie... | I have a "WinsockWrapper.h" header which helps me ensure consistency... The gist of it is;
#ifndef _WINDOWS_
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#endif
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
Include this before anything else which might pull in windows.h in a... |
4,061,643 | 4,061,664 | utf-8 encoding a std::string? | I use a drawing api which takes in a const char* to a utf-8 encoded string. Doing myStdString.cstr() does not work, the api fails to draw the string.
for example:
sd::stringsomeText = "■□▢▣▤▥▦▧▨▩▪▫▬▭▮▯▰▱";
will render ???????????????
So how do I get the std::string to act properly?
Thanks
| Try using std::codecvt_utf8 to write the string to a stringstream and then pass the result (stringstream::str) to the API.
|
4,061,741 | 4,061,746 | Compilation error in usage of templates | template <class T>
class Test
{
public:
template<class T>
void f(); //If i define function here itself, error is not reported.
};
template <class T>
void Test<T>::f()
{
} //Error here.
int main()
{
Test<float> ob;
ob.f<int>();
}
It produces below error.
error C2244: 'Test<T>::f' : unable to match... | Change as
template <class T>
class Test
{
public:
template<class U>
void f();
};
template <class T>
template<class U>
void Test<T>::f()
{
}
|
4,061,808 | 4,061,833 | Stringstream write() problem while "overwriting" | Currently, I have a stringstream called Data. I am seeking to the beginning of the stringstream by using:
Data.seekp(0, std::ios::beg);
Then, I try writing 2 integers to the first 8 bytes of the stringstream (previously, the first 8 bytes were set to 0)
Data.write(reinterpret_cast<char*>(&dataLength),sizeof(int));
Dat... | char* b = const_cast<char*>(Data.str().c_str());
Data.str() is a temporary, which is destroyed at the end of this statement; the value of that temporary's c_str() can only be used while the temporary is alive (and you've made no modifications to it, the invalidation rules are complex for std::string). You can never u... |
4,061,818 | 4,061,861 | size of std::vector with struct elements | I'm having trouble getting the right size of a vector with struct elements. The element class is defined like this (I didn't omit any detail even though I think the only relevant fact is that it is a class containing an int and two doubles):
class Interval
{
public:
Interval(int _i = 0, scalar _l = 0, scalar _r = 0... | Edit: Now that you've provided more information, perhaps we can shed some light on this confusing behavior.
You've violated the One Definition Rule. The results of doing this aren't really defined, but we can make some educated guesses based on your observed results.
Template functions are always declared inline, as th... |
4,061,874 | 4,061,888 | Deleting a character from a string | I wanted to write a code that would delete a given character from a string. I have come up with the following snippet.
Now, while this does my work, it is giving me a worst case complexity of O(n^2). Can anyone help me on improving this.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void Push(char *, int i... | #include <cstring>
#include <algorithm>
#include <iostream>
int main() {
using namespace std;
char s[] = "helelo";
cout << s << '\n';
char *end = s + strlen(s);
end = remove(s, end, 'e');
*end = '\0';
cout << s << '\n'; // hllo
return 0;
}
Note you can't modify string literals, so I used a char ar... |
4,061,929 | 4,061,953 | Linker error LNK2038: mismatch detected in Release mode | I am trying to port a small app of mine from Win XP and VS 2005 to Win 7 and VS 2010.
The app compiles and runs smoothly in Debug mode, however in Release mode I get the following error:
pcrecpp.lib(pcrecpp.obj) : error LNK2038: mismatch detected for
'_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in LoginD... | Your app is being compiled in release mode, but you're linking against the debug version of PCRE, which had /MTd (or similar) set, thus causing the mismatch in iterator debugging level in the CRT.
Recompile PCRE in release mode to match your own application.
The detect_mismatch pragma in VS 2010 is what causes this err... |
4,061,964 | 12,810,489 | Seamless scrolling tilemaps | I'm working on a top-down rpg, and want to implement seamless scrolling maps. That is, as the player explores the world, there is no loading screen between maps and no "doors" to the next area.
I have two ways to break down the world. At the top level, I have "zones" which is simply a collection of 9 "maps"(These zone... | This is exactly like what I'm trying to do with a game I'm writing in FreeBASIC. What I'm doing is slightly different, but maybe it can be of some help.
I have a 1024^2 world map (so I can generate it fractally). Each land square on the world map is a REGION map (a miniature kingdom with a procedural history), but I ma... |
4,062,045 | 4,062,051 | Clearing terminal in Linux with C++ code | Okay, I have been researching on how to do this, but say I am running a program that has a whole bit of output on the terminal, how would I clear the screen from within my program so that I can keep my program running?
I know I can just type clear in terminal and it clears it fine, but like I said, for this program it ... | These are ANSI escape codes. The first one (\033[2J) clears the entire screen (J) from top to bottom (2). The second code (\033[1;1H) positions the cursor at row 1, column 1.
All ANSI escapes begin with the sequence ESC[, have zero or more parameters delimited by ;, and end with a command letter (J and H in your case).... |
4,062,106 | 4,062,130 | Suppress system("ping") output in C++ | I have written a simple program that pings three sites and then reacts to whether they are reachable or not.
My question is: can I suppress system("ping ")'s output? I have written my code in C++ as I know that language the best. Currently the code opens the ping.exe running the system command. If I can prevent the out... | Try doing system("ping host > nul") (nul is windows equivalent of UNIX /dev/null).
|
4,062,126 | 4,062,133 | Can 2 pthread condition variables share the same mutex? | I went through the documentation in http://www.opengroup.org/onlinepubs/009695399/functions/pthread_cond_wait.html but this is not mentioned explicitly. Any prompt response will be very appreciated.
| Yes. This is sometimes a good idea if you have separate conditions you'd like to wait on. For instance, you might have a queue and condition variables for both "not full" and "not empty" etc... Someone putting data on the queue waits for "not full". Someone taking data off the queue waits for "not empty". They all... |
4,062,189 | 4,062,320 | How to prevent arrow keys from changing the UI state? | I am developing a Tetris game using C++ in combination with the plain old WinAPI, GDI and GDI+. The applications window contains a few UI controls along with a static control that is used for painting the game state. I am using a keyboard hook so that I can respond to the arrow keys to move the current block and the sp... | If you're using a WH_KEYBOARD_LL or a WH_KEYBOARD keyboard hook, you can return 1 from the hookproc to prevent the key from being passed to the rest of the system.
Do no call the next hookproc in that case.
However, this could play havoc with things that use hooks and come after you in the hook chain.
If you're writing... |
4,062,382 | 4,062,446 | Return from a C++0x lambda caller directly | I've just rewritten the following C89 code, that returns from the current function:
// make sure the inode isn't open
{
size_t i;
for (i = 0; i < ARRAY_LEN(g_cpfs->htab); ++i)
{
struct Handle const *const handle = &g_cpfs->htab[i];
if (handle_valid(handle))
{
if (handle->... | You don't; std::for_each isn't structured to handle an early return. You could throw an exception...
Or don't use a lambda:
for (auto const &handle : g_cpfs->htab) {
// code that was in lambda body
}
|
4,062,388 | 4,062,442 | Explicit template specialization issue | template <class T>
class Test
{
public:
template<class U> void f(); //generic function
template<> void f<char>(); //Specialization for char.
};
template <class T>
template<class U>
void Test<T>::f() //Definition of generic function
{
}
template<>
template<> void Test<char>::f<char>(){} //Definition of sp... | C++03, §14.7.3/2:
An explicit specialization shall be declared in the namespace of which the
template is a member, or, for member templates, in the namespace of which
the enclosing class or enclosing class template is a member.
An explicit specialization of a member function, member class or static data
member of a cla... |
4,062,396 | 4,062,417 | How to generate truly random numbers (NOT pseudo) in Linux | What is the (best) way to create a secure random numbers in Linux (C/ C++ code), more random than the general rand() results, and not pseudo as OpenSSL BN_rand?
In Windows I found CryptGenRandom() as a good option. Is there any equivalent in Linux?
Thank you in advance.
| you can read from /dev/random which is populated with an entropy pool. There is some good info on the wikipedia site on it: http://en.wikipedia.org/wiki//dev/random
|
4,062,465 | 4,062,487 | How can templated code find the length of a string whose type is a template parameter, in C++? | Consider this code:
template <typename T>
class String
{
public:
...
String(T* initStr)
{
size_t initStrLen;
if (initStr != NULL)
{
printf_s("%s\n", typeid(T) == typeid(char) ? "char" : "wchar_t");
if (typeid(T) == typeid(char))
{
strlen((T*)initStr);
}
else if (typeid(T) == typeid(wchar... | You can do this e.g. by introducing a helper function as illustrated below:
#include <iostream>
#include <string.h>
size_t GetLength(const char* s) { return strlen(s); }
size_t GetLength(const wchar_t* s) { return wcslen(s); }
template <typename T>
void PrintLength(T s)
{
std::cout << GetLength(s) << std::endl;
}... |
4,062,503 | 4,062,533 | stl allocator, copy constructor of other type, rebind | The STL allocators require this constructor form (20.1.5): X a(b); with the requirement that Y(a) == b;
In the standard implementation this implies, and is implemented as:
template<class U> allocator( const allocator<U> & o ) throw()
I'm having trouble understanding why this requirement exists. I understand that all... | To allow construction from other allocators, as containers need to use a different allocator type than you specify. Lists and maps, for example, allocate their internal node type rather than the value_type they expose.
The code looks similar to:
template<class T, class Alloc=std::allocator<T> >
struct Container {
ty... |
4,062,672 | 4,062,759 | Free GUI framework to create a single exe? | I'm looking for free and easy GUI framework that let me create single exe
without dependency (like .Net framework) and to be not GPL
as a side note .. im using Qt and its great but i have to be LGPL to use it that means lots of fat dlls . is there any alternative?
p.s
how did the Dropbox client made of? i know its p... |
I'm looking for free and easy GUI framework that let me create single exe without dependency (like .Net framework) and to be not GPL
There is no such thing. Three most popular frameworks Qt, GTKmm, wxWidgets are LGPL.
However you can link statically and provide full source code that allows user to replace/update the ... |
4,062,947 | 4,062,965 | using user input such as YES and NO to control program flow in C++ | I'm making a small program that uses a if else statement, but instead of using numbers to control the flow i want to be able to make the control work with with yes and no;
for example:
cout << "would you like to continue?" << endl;
cout << "\nYES or NO" << endl;
int input =0;
cin >> input;
string Yes = "YES";
string No... | You're not reading in a string, you're reading in an int.
Try this:
string input;
instead of
int input = 0;
Also, C++ is case-sensitive, so you can't define a variable called Yes and then try to use it as yes. They need to be in the same case.
btw, your second if statement should be an else if, otherwise if you type ... |
4,062,981 | 4,063,070 | Converting class function pointer to void* or vice versa | Im trying to compare the address of two functions for equality. Type of my stored function is known. This system normally works, consider the following code (written as sample not from the program):
virtual bool compare(void *fn2) {
void (*fn)(int);
if(fn==fn2)
return true;
}
However when class functions cam... | Posix requires the ability to convert function pointers to void*. Standard C++ does not support it.
Member function pointers are not pointers in the ordinary sense, they're more like offsets (even for a non-virtual member function).
Both implementations you show for compare would have Undefined Behavior even if the com... |
4,063,051 | 4,063,104 | possible to have a Timeout on ReadFile()? | while(GetExitCodeProcess(processInfo.hProcess, &exitCode)
&& exitCode == STILL_ACTIVE)
{
ReadFile(defaultSTDIN, chBuf, 1, &dwRead, 0);
WriteFile(writingEnd, chBuf, 1, &dwWritten, 0);
}
The problem with the code above is that even when the child process referenced through processInfo.hProcess has exited... | What you need is to read the file asynchronously using the FILE_FLAG_OVERLAPPED flag when opening the file, and specifying an OVERLAPPED structure to the ReadFile function. Then you could wait on both the read operation and the process termination, and act appropriately.
|
4,063,130 | 4,063,199 | Recording and charting boot process information in Linux | I need to write a command line tool that records the boot process information in Linux, and then renders it in a chart format (a textual chart would do). How do I programmatically obtain the this boot process information? Languages that I am allowed to use are C and C++.
Thanks in advance. :-)
| Doesn't [link text][1] pretty much already do this? Or do you need to write an initlog replacement?
I don't know what kind of "chart" you would make from such data, but have a look at gnuplot to help you with that part.
edit: I had the wrong tool mentioned originally.
[1]: http://linux.about.com/library/cmd/blcmdl1_ini... |
4,063,378 | 5,212,523 | C++ rendering or game engine for Android. | I'm developing an Android application and I need to use a render engine to show some objects that I made with Blend.
I'm wondering if there is a C++ game engine or render engine to show my models.
Is there anyone?
Thanks.
| Yes. Take a look at http://www.cuteandroid.com/open-source-android-2d-or-3d-game-engine-for-android-developers-plus for game engines.
Just for rendering, it looks like this might help: http://www.rozengain.com/blog/2010/05/17/loading-3d-models-with-the-min3d-framework-for-android/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.