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 |
|---|---|---|---|---|
3,937,263 | 3,937,364 | Can I remove items from a ComboBox without changing the index of other items? | I have a CComboBox control with several items and I need to remove some of them, but the indexes of the remaining items should be preserved.
When the combo box is populated, the item data is set like so:
index = mycombo.AddString(temp);
mycombo.SetItemData(index, static_cast<DWORD>(count));
where count is a loop count... | Adding or removing items does not change the number you passed to SetItemData(). GetItemData() returns the same number. You however need to pass the index of the item to DeleteString(). When lower numbered items were deleted before then the index will no longer match GetItemData(). If you lost track of the index of... |
3,937,418 | 3,937,448 | How many threads can I spawn using boost in c++? | And what happens when I try to spawn too many?
I'm getting the following error when I spawn more than about 900 threads:
terminate called after throwing an instance of 'dining 1
boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::thread_resource_error>
>dining 3
'
dining 2
what():... | Remember that each thread needs to reserve stack space. That is why there is a limit on the number of threads you can spawn. It looks like you are either hitting this limit or boost is stopping you from hitting this limit.
Here is a link to the most recent boost documentation that documents the behavior you are seeing... |
3,937,535 | 3,937,561 | when i need pass by pointer (and not by reference) | Can you give me an example when I can't pass argument by reference and I need to use pointer. I've found an example, but I'm not sure.
Suppose you have a class D derived from the base class B. You need pointer if you want do so:
void function(B* b){...}
int main{
D* d;
function(d);
}
| The single time where you can not use a reference and must use a pointer is if you allow the concept of "no argument" by passing a null pointer.
However, you might want to use pointers as arguments when you are actually storing a pointer to whatever was passed. Most C++ developpers will notice that you aren't using a r... |
3,937,770 | 3,937,899 | How to create sound from an array of double and play it on speaker | I have an array of double (size more than 60k entries), I have the frequency value. Now I want to create a sound from it using C/C++ which I can play on speaker. My OS is linux.
Thanks. I hope I am clear enough.
| http://www.linuxjournal.com/article/6735
This is a link to an article in Linux Journal about programming with the ALSA (Advance Linux Sound Architecture). It contains some example code.
|
3,937,897 | 3,937,935 | Does it make a difference if I make an enum in a class static? | Basically, if I don't do all objects get a copy of all the enum values?
ps: as always, references for your answer are always welcome...
| With the enum keyword you are actually defining a type, not defining storage like a data member.
It's like defining an inner class, like this:
class X
{
private:
class InnerClass
{
...
};
};
The InnerClass definition is just a definition. It just defines the type within the c... |
3,938,036 | 3,938,171 | Rationale of enforcing some operators to be members | There are 4 operators in C++ which can be overloaded but cannot be overloaded as freestanding (aka nonmember, standalone) functions. These operators are:
operator =
operator ()
operator ->
operator []
This thread explains perfectly well the rationale behind prohibiting operator = to be a nonmember function. Any idea... | The four operators mentioned in the original posting, =, (), -> and [], must indeed be implemented as non-static member functions (by respectively C++98 §13.5.3/1, §13.5.4/1, §13.5.5/1 and §13.5.6/1).
Bjarne Stroustrup's rationale was, as I recall from earlier debates on the subject, to retain some sanity in the langua... |
3,938,064 | 3,938,084 | Invalid conversion from ‘char*’ to ‘char’ | My code, when compiled, returns the error invalid conversion from ‘char*’ to ‘char’, and identifies the second last line, return char32 as the problem. I've searched the Internet and this site and haven't found anything that has helped. I've found the error goes away and the code compiles if I replace the problem line ... | There are many problems here.
If you really want to return a single character that should be
return char32[0];
or whichever character you want, by index. This is the same as *char32 by the way. An array variable can be treated as a pointer to the first array in the element, if no index is used. Although since char32 ... |
3,938,307 | 3,938,340 | Serializing C-style structs (using C++) | Is it evil to serialize struct objects using memcpy?
In one of my projects I am doing the following: I memcpy a struct object, base64 encode it, and write it to file. I do the inverse when parsing the data. It seems to work OK, but in certain situations (for example when using the WINDOWPLACEMENT for the HWND of Windo... | You will run into problems if you need to transfer these files between machines that do not all share the same endianness and word size, or if you add/remove slots from the structs in future versions and need to retain binary compatibility.
|
3,938,325 | 3,938,394 | xml to c++: handling escape characters <= | I am using xsl to convert data from xml into C++ code. I am running into problems when I have <= or >= in the xml file that needs to be converted to C++ code.
For example if I have (in .xml file)
<Check>max(x,y) <= 20 </Check>
and the .xsl file is
if(<xsl:value-of select="Check"/>") {
...
}
But this does not c... | Have you set an xsl:output element in your stylehsheet? By default, XSLT thinks its output is XML, and will escape characters. Try this:
<xsl:output method="text" />
|
3,938,337 | 3,938,417 | CUDA counting, reduction and thread warps | I'm trying to create a cuda program that counts the number of true values (defined by non-zero values) in a long vector through a reduction algorithm. I'm getting funny results. I get either 0 or (ceil(N/threadsPerBlock)*threadsPerBlock), neither is correct.
__global__ void count_reduce_logical(int * l, int * cntl, ... | In your reduction you're doing:
cache[cidx] += cache[cidx];
Don't you want to be poking at the other half of the block's local values?
|
3,938,414 | 3,938,573 | nonrecursive mergesort in C++ | I wrote the entire thing, but i get vague errors. I don't know what's wrong....ugh.Also, you may ask why non-recursive well my teacher has it that way for the test.
void nonrec_mergesort(vector <int> & a, vector <int> & b, int s, int r)
{
int m = 1;
while (m <= r)
{
int i = 0;
while(s < (r-... | This link should answer your quetsions about bottom up merge sort, but you have not provided enough information to easily assist you.
http://www.algorithmist.com/index.php/Merge_sort
Input: array a[] indexed from 0 to n-1.
m = 1
while m <= n do
i = 0
while i < n-m do
merge subarrays... |
3,938,437 | 3,938,511 | What's the correct way to use const in C++? | const correctness has me somewhat confused.
What rule of thumb do you use to decide when something should be const or not?
e.g. consider this example
class MyClass
{
string ToString(); // this one?
const string& ToString(); // or this?
const string& ToString() const; // or this?
char* ToString(); // What abou... | Where you use const depends on the purpose of the function. As James suggests in his comment (which is worth putting as an answer), put const anywhere you can:
If the function is intended to modify state within it's object instance, don't put const at the end of the signature.
If the function is intended to modify one ... |
3,938,834 | 3,939,751 | NumberFormat/DecimalFormat treats certain floating-point values as longs instead of doubles | NumberFormat/DecimalFormat doesn't seem to parse strings with the "#.0" format (where # is any number) as a double.
The following code illustrates this:
#include <cstdio>
#include <iostream>
#include <unicode/decimfmt.h>
#include <unicode/numfmt.h>
#include <unicode/unistr.h>
#include <unicode/ustream.h>
int main() {
... | You can call formattable.getDouble(status) - the only reason getType returns long is that the particular value will fit in a long.
As to format, if you call f->setMinimumFractionDigits(1); before format, you will get "2.0" with your code, setting the min digits to 2 gives "2.00" etc.
hth
|
3,938,838 | 3,938,847 | Erasing from a std::vector while doing a for each? | The proper way to iterate is to use iterators. However, I think by erasing, the iterator is invalidated.
Basically what I want to do is:
for(iterator it = begin; it != end; ++it)
{
if(it->somecondition() )
{
erase it
}
}
How could I do this without v[i] method?
Thanks
struct RemoveTimedEvent
{
bo... | erase() returns a new iterator:
for(iterator it = begin; it != end(container) /* !!! */;)
{
if (it->somecondition())
{
it = vec.erase(it); // Returns the new iterator to continue from.
}
else
{
++it;
}
}
Note that we can no longer compare it against a precalculated end, because... |
3,938,862 | 3,939,063 | C++: Trouble with parsing XML file (MXML library) | I am having an issue with the following code.
It uses the Mini-XML library to extract elements from an xml file.
It compiles and runs fine, except that it is unable to get the last "radius element," returning NULL instead (it crashes if I don't check to see if subnode is not NULL).
//Start loading <ssys> elements
mxml_... | Well I'm guessing you're talking about Mini-XML, which I honestly have no experience with. What I do see is that you're iterator is one step ahead of your name. I think you want something more like:
node = mxmlFindElement(Systems_elem, tree, "ssys", NULL, NULL, MXML_DESCEND);
while (node) {
ssys_elem.push_back(node... |
3,939,111 | 3,939,177 | Is there any way to write a class such that no class can be inherited from it? | From link http://www.coolinterview.com/interview/10842/
Is there any way to write a class such that no class can be inherited from it ?
From suggestions in the above link, i tried below code
class A
{
A(){}
~A(){}
A(const A&);
A& operator=(const A&);
};
class B: public A
{
};
The above code doesn't pr... | There is no equivalent to the final keyword in Java or C♯'s sealed in C++. You can certainly prevent inheritance by making the class constructors private, or by following liaK's link and having a class subclass a class that has private constructors and is its friend.
In general though:
You can just make your destructor... |
3,939,151 | 3,939,172 | Cross dependencies without forward declaring all used functions? | I have class A (in A.h) which depends on class B in (B.h) and vice versa. Forward declaring the used functions works, but this means I have to update everywhere where I forward declared those functions in the future, ex, if I remove, or change argument in those functions they must all be updated to reflect change. I do... | If you only need to work with pointers or references to a class at the declaration level, you can do it like this:
A.h
class B; // forward class declaration
class A {
A(B &);
};
B.h
class A;
class B {
B(A &);
};
B.cpp
#include "B.h"
#include "A.h" // now we get the full declaration of A
B::B(A &a) {
a.... |
3,939,199 | 3,962,146 | Initialize costly value in map with minimum lock contention (C++) | Suppose we have a map that is shared between multiple threads. It represents a node in some hierarchical structure (say, a directory in a file system) that is stored on disk. Constructing a Value is expensive both in time and in memory. This is the classic 'initialize on demand' problem, with a twist: we're initializin... | Your trouble with scheme #3 is how to keep track of the placeholder objects. If you're willing to give up a bit of parallelism, you can do it more easily - allocate a single lock which will serialize value creation with each map. Then it goes:
lookup(map, key):
1. Grab read lock on map
2. lookup key in map, unloc... |
3,939,251 | 3,939,269 | Should unimplemented base class functions be 0'd? | which of the following is better practice?
class Foo {
virtual void unimplementedFunc() = 0;
};
Or
class Foo {
virtual void unimplementedFunc();
};
//in cpp
void Foo::unimplementedFunc()
{
//not implemented in base
}
Thanks
| class Foo {
virtual void unimplementedFunc() = 0;
};
You have a pure virtual function inside Foo, so Foo is an abstract class. In other words you cannot instantiate Foo. Most derived classes are required to provide the implementation of the virtual function.
On the other hand the second version declares a virtual func... |
3,939,350 | 3,939,360 | c++ Increment operator |
Possible Duplicate:
Difference between i++ and ++i in a loop?
Is there a difference between i++ and ++i ?
| i++ is postincrement and ++i is preincrement. The former allows you to use the value of i in an expression and then increments i at the end. The later increments i first and then allows you to use it. For example:
int value_of_i_before_increment=i++;
and
int value_of_i_after_increment=++i;
|
3,939,531 | 3,939,565 | "file not found " error while creating a static library in c using gcc - linux | I have a file hello.c
#include<stdio.h>
void hello()
{
printf("Hello!\n");
}
A header hello.h
#ifndef _hello_
#define _hello_
void hello();
#endif
main.c
#include<stdio.h>
#include "hello.h"
int main()
{
hello();
return 0;
}
I am currently in the folder /home/user/name/programs
I am trying to build a ... | Change the library name to start with lib
ar rcs libmy.a hello.o
^^^^^^^
gcc -static main.c -L/home/user/name.programs -lmy -o hello
^^^^^
And its not searching in /usr/bin,. The error is split by the linker (ld) which resides in /usr/bin.
|
3,939,697 | 3,939,718 | C++ struct array copy | I want to copy elements of a struct array to another by using memcpy. I believe this is miserably causing my program to fail for some reason. Also how can I free the memory in the end ?
struct FaultCodes
{
string troubleFound;
string causeCode;
string actionCode;
string paymentCode;
string suppCode;
u_int16... | You are only allowed to use memcpy in case the objects you're copying are so-called PODs (plain old data structures). But your struct contains std::string objects which are not PODs. Thus, your whole struct is not a POD.
Use std::copy from the algorithm header instead.
|
3,939,704 | 3,940,157 | In xcode when including cmath get error: '::acos' has not been declared, etc | I get the following errors when trying to build a small and simple project that includes <cmath> in Xcode:
cmath: '*' has not been declared
'::acos' has not been declared
In file included from /Xcode4/Projects/libraryLAFMath/Classes/libraryLAFMath.cp
In file included from /Xcode4/Projects/libraryLAFMath/Classes/library... | There is a file I have in my project named Math.h with a capital M, and it seems the compiler gets confused and tries to include Math.h instead of math.h.
|
3,939,910 | 3,940,082 | Why declaration/definition must both be in source file for template class in c++? | Anyone can elaborate the reason?
| Source files are compiled independently of one another into executable code, then later linked in to the main program. Template functions on the other hand, cannot be compiled without the template parameters. So, the file that uses them needs to have that code in order for it to be compiled. Therefore the functions ... |
3,940,013 | 3,940,028 | How many header files are there in c++ standard? | In C89 there're 15 header files:
<assert.h> <locale.h> <stddef.h> <ctype.h> <math.h>
<stdio.h> <errno.h> <setjmp.h> <stdlib.h> <float.h>
<signal.h> <string.h> <limits.h> <stdarg.h> <time.h>
What about the c++ standard?
| 33 C++-specific ones:
<algorithm> <iomanip> <list> <queue> <streambuf>
<bitset> <ios> <locale> <set> <string>
<complex> <iosfwd> <map> <sstream> <typeinfo>
<deque> <iostream> <memory> <stack> <utility>
<exception> <istream> <new> ... |
3,940,283 | 3,940,424 | [C++]Does my COM server require synchronization? | I have developed my first COM component (yes, a newbie in the realm of COM development), initialization is done with COINIT_MULTITHREADED. Also, this COM component is a local server executable. But, I did not add any synchronization code to this component. What do you think: do I have to add CRITICAL_SECTIONs to code o... | Since you specified COINIT_MULTITHREADED, COM allows several simultaneous calls to your server and thus you need to do the synchronization yourself.
Use COINIT_APPARTMENTHREADED if you want COM to serialize the calls.
See MSDN for the details.
|
3,940,389 | 3,940,396 | How many versions of the C++ Standards are there? | In C there's C89, C99, and C11; what about C++? Is there any upgrade since it came out?
|
C++98 (ISO/IEC 14882:1998) is the first edition.
C++03 (ISO/IEC 14882:2003) is the second edition and often considered a bugfix, but it has many changes.
C++11 is the third edition.
C++14 is the fourth edition.
C++17 is the latest edition (as of 2017).
You can download PDFs of the standards and drafts.
|
3,940,555 | 3,940,645 | How can a C/C++ process know if it runs in background? | I have a method in my process that should be run only if the process is not in background.
How can I dynamically test if the current process is in background ?
Thanks
| Check out Unix FAQ: How can a process detect if it's running in the background?
General answer is: You can't tell if you're running in the background.
But you can check if stdin is a terminal: if(isatty(0)) { ... }
|
3,940,612 | 3,942,676 | C++ DGRAM socket get the RECEIVER address | In C++,
how can I get the receiver address of the UDP packet which I have received using recvfrom. I know that it should be the same host on which I am receiving the packet, but I need to extract it from the received packet, in order to verify something. How can I do this?
I found that one way of doing this is:
int... | On Linux you want to use IP_PKTINFO option, see ip(7), and the recvmsg(2) call.
Stevens has examples of doing this but with IP_RECVDSTADDR and IP_RECVIF options that are not available on Linux.
|
3,940,628 | 3,941,702 | String to int using boost spirit | I hear that spirit is really fast at converting string to int.
I am however unable to create a simple function that can do so. Something like
int string_to_int(string& s) {
/*?????*/
}
Can anybody use boost spirit to fill in this function.
By the way I am working on boost 1.34 and not the latest version.
| There are several ways to achieve this:
#include <boost/spirit/include/qi_parse.hpp>
#include <boost/spirit/include/qi_numeric.hpp>
namespace qi = boost::spirit::qi;
std::string s("123");
int result = 0;
qi::parse(s.begin(), s.end(), qi::int_, result);
or a shorter:
#include <boost/spirit/include/qi_parse.hpp>
#incl... |
3,940,633 | 3,940,642 | Why there's no dedicated compiler for c or c++? | Seems all compilers can deal with both c and c++,like gcc ,msvc...
Is it because these 2 languages are exactly very much alike?
| Actually, GCC (GNU Compiler Collection) has two different front-ends, gcc and g++. To specify C++, you can also use a .cpp (or a few others) extension, or -x c++, when executing gcc. However, this requires extra options (like linking in the C++ standard library).
cl, Microsoft's C++ compiler, does not support modern ... |
3,940,720 | 3,941,284 | Is there anything wrong with this scheme for error logging? | I wrote this interface:
//The idea is to use EHPrint to construct the error msg and then raise an error or
//a warning, etc. This removes the need to implement all 3 'Raise' functions
//as taking variable param list reducing code.
class ErrorHandler ... | Most logging libraries that support multiple levels of logmessages use only one function for generating the messages and this function takes an additional parameter indicating the level of the log message.
In your structure, that could look like this:
class ErrorHandler ... |
3,940,747 | 3,941,299 | Query about N- Queen solving? | I solved the N- Queen problem with the condition that there can only be one queen per column. So I place a queen in a square in first column, then move onto the next column and place a queen in a square not attacked by the queen on board.
I am able to find all solutions with this approach but it starts taking a long ti... | Well, you can only check for a unique solution once you have a solution. The place to check is at the point you increment the count variable. At this point, compare the current board to a set of unique boards and if it's not in the set then add the new solution to it.
As for your speed, your solution has a bottleneck w... |
3,940,854 | 3,940,904 | Is there anyway to initialize an object from an outer scope in an inner scope? | For example:
int main()
{
{
// I want this array to be part of the inner scope
string s[] = {"Ben","Joe","Bob","Matt"};
// And I want to use it to initialize this vector, but I want this
// vector to be visible in the outer scope
vector<string> names(s,s+4);
}
}
Is ther... | If you want the vector to be visible in the outer scope, you must declare it in the outer scope. Which means that you also have to initialize it there.
The only way to declare it without initializing is by using a pointer:
int main()
{
vector<string> * names = 0;
{
string s[] = {"Ben", "Joe", "Bob", "Matt"};
... |
3,940,876 | 3,941,580 | Saving image data of the fax job | I'm using WinFax.dll to send and recieve faxes in my application and it works rather well for now. The problem is that I want to Save the image information in a FaxJob but the output is not any recognizable format.
I have tried with Tiff, Gif, Bmp, Png and Jpg but it is not working so I thought maybe there is a proble... | I'm having trouble finding doc for WinFax.dll - so the first thing I would suggest is to fill the buffer with 0's before calling Marshal.Copy - then you will know for sure if the buffer is being filled. If it is being filled, then, you will need to look at the binary data in the file, trying to guess what format it is ... |
3,940,893 | 3,940,943 | Does WaitForMultipleObjects cause problems in a thread creating STA COM objects? | I have a thread which creates COM objects that use the STA model.
This thread's Run function puts it in an infinite WaitForMultipleObjects.
Is it possible that the infinite WaitForMultipleObjects could prevent other threads from marshaling calls to the COM objects owned by this thread?
Basically, I'm asking if WaitFor... | Yes, problems are possible - see this KB article. Basically if your thread is an STA thread it should not call functions that can block for long periods of time since while the thread is blocked it doesn't pump and dispatch messages and this can prevent proper marshalling functioning.
|
3,940,906 | 3,941,017 | C++ UDP sockets packet queuing | I am using the same UDP socket for sending and receiving data. I am wondering if packet queuing for DGRAM sockets is already present, or do we have to handle it separately.
If the user code has to handle queueing, how is it done? Do we have separate threads to recvfrom for the socket and put the packet in the recive... | There is a packet queue. However when the packet queue is filled then UDP packets start getting discarded. When they are discarded they are lost forever so make sure you keep reading data!
|
3,940,908 | 3,941,398 | can the safe bool idiom be implemented without having to derive from a safe_bool class? | Is there a trick to get the safe bool idiom completely working without having to derive from a class that does the actual implementation?
With 'completely working', I mean the class having an operator allowing it to be tested as if it were a boolean but in a safe way:
MyTestableClass a;
MyOtherTestableClass b;
//this... | This should work:
class MyTestableClass
{
private:
void non_comparable_type() {}
public:
typedef void (MyTestableClass::* bool_type)();
operator bool_type () const { return (someCondition ? &MyTestableClass::non_comparable_type : 0); }
};
class MyOtherTestableClass
{
private:
void non_comparable_type() {}
pub... |
3,941,016 | 3,941,026 | Multiple C++ deletion of a memory pointed by multiple objects | Another C++ pointer deletion question is in the following example:
class Foo {
public:
int *p;
~Foo() {
delete p; p = NULL;
}
};
Foo *f1 = new Foo();
Foo *f2 = new Foo();
f1->p = new int(1);
f2->p = f1->p;
delete f2; // ok
delete f1; // no error?
Why I did not get error when calling "delete f1"? d... | It is a VERY bad thing to do. However C++ won't necessarily do anything here. It is "un-defined" behaviour. That doesn't mean it will crash but it will, most probably, cause bad shit (tm) to happen.
Edit: Furthermore in your 2nd example the fact it crashes is just a part of "undefined" behaviour. It is undefined as... |
3,941,124 | 3,941,137 | How to comment a few lines, with comments inside | I have a program like this
int main(){
char c;
int i; /* counter */
double d;
return 0;
}
if I want to comment out char, int and double, and just have return uncommented, can I do it? the comment that's already there stops the comment..
Is there an easy/fast way to comment that out?
| int main(){
#if 0
char c;
int i; /* counter */
double d;
#endif
return 0;
}
Not strictly a comment, but the effect is what you want and it's easy to revert.
This also scales well to larger code blocks, especially if you have an editor that can match the start and end of the #if..#endif.
|
3,941,179 | 3,941,754 | Memory usage of C++ application on Windows | I have an application that does some Monte Carlo simulation. For each run, a 12MB file is loaded into a std::vector<MyData>. The object which loads and stores the data is referenced by a boost::shared_ptr which is removed from the stack when the run finishes.
I see the memory usage of the application grow in Windows Ta... | Thanks everybody for your hints. It turned out that it actually WAS a memory leak caused a lacking virtual destructor of my AbstractSensorDataSource class which was storing the loaded data.
|
3,941,252 | 3,941,353 | How to read and change HTTP traffic on-the-fly on Windows? | I need a method that would allow me to read all the HTTP traffic on a local machine, and to change this traffic on-the-fly. Basically, I need to change the content on any web page opened in any browser at the machine.
Any thoughts?
| For debugging/troubleshooting, or in production?
For debugging. fiddler2 lets you do this with scripts
For production use, you probably want to implement a Layered Service Provider (which I assume Fiddler2 does)
|
3,941,548 | 3,941,572 | string filtering on c++ | given a string literal in c++ i have to remove toxic words like stupid etc by ###.
Suppose i have my toxic words in an array like
char[][]={"...",".."...and more...}
and my string is like
char str[]="......."
any particular library func that could help me here.
thanks in advance for help
| boost string algorithms
Example:
string str1="Hello Dolly, Hello World!"
replace_first(str1, "Dolly", "Jane"); // str1 == "Hello Jane, Hello World!"
replace_last(str1, "Hello", "Goodbye"); // str1 == "Hello Jane, Goodbye World!"
erase_all(str1, " "); // str1 == "HelloJane,GoodbyeWorld!"
erase_head(str1, 6); // str1 ==... |
3,941,721 | 3,941,755 | What does a C++ program require to run? | This question has been bothering me for a while now. Let's consider the two following programs:
#incude <iostream>
int main()
{
std::cout << "Hello, World!";
}
and
int main()
{
int x = 5;
int y = x*x;
}
Windows:
The first example, naturally, requires some system .dll's for the console. I understand that. Wh... | C programs on Windows require CRT libraries that come with Windows. C++ sometimes require so called "C++ redistributable". They can be embedded in app via linking but this will make EXE bigger.
|
3,942,123 | 3,942,173 | c++ (non-built in/class) static member | #include <iostream>
#include <string>
class c1
{
public:
static std::string m1;
static unsigned int m2;
};
//std::string c1::m1 = std::string;
unsigned int c1::m2 = 0;
void main()
{
c1 a;
//std::cout<<a.m1<<std::endl;
std::cout<<a.m2<<std::endl;
}
In this program enabling the two remarked lines causes an er... | The error says it all, you are using the type std::string as the value to be assigned.
To fix this you can do:
std::string c1::m1 = std::string();
^^
or just
std::string c1::m1;
|
3,942,291 | 3,942,332 | C/C++ reliability of memcpy sizeof(typname) cross application over TCP | I had been doing some file IO in a project i am currently working on and so far I have been reading in a whole block of data using the following fast and convenient method:
struct Header { ... };
class Data { ... };
// note that I have not used compiler directives to pack/align/order bytes
// partly because I don't kno... | No, that's not guaranteed at all. There is a specific network byte order and as far as I know, both WinAPI and POSIX provide local to network translation functions. In addition, the alignment you can control with compiler directives. But you have to explicitly take care of both of these things.
|
3,942,307 | 3,942,327 | C++ - Issue dynamic commands to an active process | I need to write a piece of code which will invoke a process and dynamically issue commands to the process. For example, I may have to run FTP and then when the process is up, I've to issue ftp commands to this process. I need to do this in C++. I don't have a single clue of where to start.
| It depends on what you mean issue commands to a process.
If you want to feed the started process's stdin, you can do it with the handle of the input stream which will be given to you when you create the process.
If you want to notify the started process about something you could use named Events.
If you want to pass ... |
3,942,426 | 3,942,493 | How to template'ize variable NAMES, not types? | my question is about how to template'ize the name of a class member that should be used.
Maybe a simplified & pseudo example:
/**
Does something with a specified member of every element in a List.
*/
template<membername MEMBER> // <-- How to define such thing?
void doSomething(std::vector<MyClass> all){
for( i=0;... | Template parameters are restricted to types, integer constants, pointers/references to functions or objects with external linkage and member pointers -- but no identifiers.
But you could use a member pointer as template parameter:
template<int MyClass::* MemPtr>
void doSomething(std::vector<MyClass> & all) {
for( i=... |
3,942,781 | 13,751,388 | How to generate a monochrome bit mask for a 32bit bitmap | Under Win32, it is a common technique to generate a monochrome bitmask from a bitmap for transparency use by doing the following:
SetBkColor(hdcSource, clrTransparency);
VERIFY(BitBlt(hdcMask, 0, 0, bm.bmWidth, bm.bmHeight, hdcSource, 0, 0, SRCCOPY));
This assumes that hdcSource is a memory DC holding the source image... | The method that worked for me was to convert the bitmap from 32 bit to 24 bit first.
1. CreateCompatibleDC
2. CreateDIBSection with 24 as the biBitCount.
3. SelectObject
4. BitBlt from 32bit DC to 24 bit. This removes alpha.
5. BitBlt from 24 bit DC to the monochrome DC works as expected.
On my machine this executes f... |
3,943,412 | 3,945,013 | Can I link MSVCRT statically with mingw? | I have C program I compile with mingw on Windows. It works fine but requires MSVCRT.DLL. I want to link that statically (like I can do in Visual Studio). Is this possible?
I tried -static flag to gcc and it didn't make any change.
What about C++ program using also standard C++ library?
| I believe that MinGW doesn't use the static runtime library for copyright reasons.
You can maybe try to use newlib (http://sourceware.org/newlib/) to create an executable that doesn't link to msvcrt.dll
|
3,943,629 | 3,943,682 | const and no const methods in c++? | I have a program and many of its classes have some operators and methods with the keyword const like the followings:
operator const char* () const;
operator char* ();
void Save(const char *name) const;
void Load(const char *name);
First: what does it mean const at the end of the method declaration?, is it the same lik... | 'const' at the end tells the compiler that this method does not change any member variables - that it is safe to call this method on const instances. So, Save could be called on a const instance, since it won't change that instance. Load on the other hand, will change the instance so can't be used on const instances.
T... |
3,943,780 | 3,943,940 | How to make a webbrowser in C++ without dependencies? | How can I use IE control or some kind of webbrowser in c++ but without any external dependencies? I mean can be done with pure win api or something like that?
I know the basics of c++ and the methods I know to use the webbrowser control needs the c++ libs to work.
Edit:
Sorry my question is unclear, im such a noob some... | Hosting Internet Explorer:
c++: http://www.mvps.org/user32/#webhost.cab
c: http://www.codeproject.com/KB/COM/cwebpage.aspx
It is also possible to host WebKit or Gecko...
Writing your own from scratch using only GDI etc is probably not a good idea.
|
3,944,060 | 3,944,142 | How to clone multiple inheritance object? | I have defined a Cloneable interface:
struct Cloneable
{
virtual Cloneable * clone(void) const = 0;
}
I have also some other interface classes (content not relevant to issue):
struct Interface
{
};
struct Useful_Goodies
{
};
I have created a leaf object which inherits from the above classes:
struct Leaf : public C... | Having your clone function return a Cloneable * is correct.
You will get an ambiguous conversion if one of your interfaces also derives from Cloneable.
Edit: Alf points out in the comments that not only is it possible for Leaf::clone to return a Leaf*, it's actually preferable for it to do so. I stand corrected.
|
3,944,196 | 3,944,323 | Rearranging array elements | Not sure if it is a duplicate. Given a data structure having first N integers and next N chars. A = i1 i2 i3 ... iN c1 c2 c3 ... cN. I need an in-place algorithm to rearrange the elements as A = i1 c1 i2 c2 ... iN cN.
| Your problem is equivalent to transposing a 2xN matrix in-place. You can read the theory here: http://en.wikipedia.org/wiki/In-place_matrix_transposition
Maybe in the special case of 2xN matrix a simpler algorithm exists, however I can't think of any. The general idea is to follow the cycles of the permutation.
|
3,944,501 | 3,944,524 | Is it allowed to assign to a dereferenced this (*this)? | I'm currently refreshing my C++ skills and was wondering if it is possible to assign something to *this.
I know assigning to this is forbidden, but can't find the same information for my case.
An example:
class Foo {
int x;
public:
Foo(int x) : x(x) {}
Foo incr() { return Foo(x+1); }
void incr_() { (*this) = in... | void incr() { return Foo(x+1); }
This is invalid. You cannot return a Foo object from a function having void return type.
void incr_() {
(*this) = incr(); // This invokes Foo& operator = (const Foo& ) (compiler synthesized)
}
This is fine.
|
3,944,505 | 3,944,774 | Detecting signed overflow in C/C++ | At first glance, this question may seem like a duplicate of How to detect integer overflow?, however it is actually significantly different.
I've found that while detecting an unsigned integer overflow is pretty trivial, detecting a signed overflow in C/C++ is actually more difficult than most people think.
The most ob... | Your approach with subtraction is correct and well-defined. A compiler cannot optimize it away.
Another correct approach, if you have a larger integer type available, is to perform the arithmetic in the larger type and then check that the result fits in the smaller type when converting it back
int sum(int a, int b)
{
... |
3,944,717 | 3,948,221 | Pass an array back from a JNI function to without copying it | I am trying to use JNI to process large chunks of data using C++ however I am having trouble understanding weather the function SetArrayRegion will duplicate an array element by element or if it can just leave the data in place and return it to the calling java function.
The following documentation is where I have be... | Generally when you pass data via JNI it will be copied across the JNI boundary. If you want an efficient mechanism for passing data from native space up to Java space then you should look at how to access NIO direct byte buffers. This can provide a section of memory that can be shared between native code and Java cod... |
3,944,726 | 3,945,022 | Changing TabControl tab title text background color c++ | I am using Visual Studio 2005, C++, and I have a tabcontrol with a couple tabs. I have changed the color of each tab to have a back color of Transparent, to match the color of the rest of the program (Control grey), however the color behind the text for the title of the tab is white. Is there any way to change this?
| A tab control draws itself according to the currently selected windows theme. Which ignores a custom color. This isn't something you ought to change, you typically want to honor the user's attempt to style the windows according to her selected preference.
If you really do want to override it then you can use custom d... |
3,944,806 | 3,944,869 | C++ is Virtual destructor still needed if there are no data members in derived? | Suppose I have this code
class Base{
public:
int getVal();
private:
int a, b;
};
class Derived::public Base{
public:
void printVal();
};
int main(){
Base *b = new Derived();
delete b;
}
I know a virtual destructor would delete things properly, but is it bad to delete wit... | For primitive-type data, your example will most likely work in practice. As a matter of fact, incurring a vtable could actually hinder performance (so there may be some legitimate use here), but it is technically undefined, per 5.3-5.4:
If the static type of the operand [of
the delete operator] is different from
... |
3,944,808 | 3,944,889 | Allocating memory for delayed event arguments | Here is my issue.
I have a class to create timed events. It takes in:
A function pointer of void (*func)(void* arg)
A void* to the argument
A delay
The issue is I may want to create on-the-fly variables that I dont want to be a static variable in the class, or a global variable. If either of these are not met, I cant d... | Why would you not use boost::shared_ptr?
It offers storage duration you require since an underlying object will be destructed only when all shared_ptrs pointing to it will have been destructed.
Also it offers full thread safety.
|
3,945,003 | 3,945,677 | MsgWaitForMultipleObjects sometimes returns WAIT_FAILED with no GetLastError value | I have a thread that creates COM objects that require a single threaded apartment.
Originally, this thread's main function put it into a WaitForMultipleObjects loop. Evidently this is a problem, because it prevents the COM message pump from doing it's job.
I replaced this with MsgWaitForMultipleObjects as a solution, b... | That shouldn't be happening, and I sure can't explain exactly why it does. I do have a few pointers, however.
First, you're not calling TranslateMessage() before DispatchMessage() in your message pump. That's bad juju, and you don't want bad juju anywhere near MsgWaitForMultipleObjects().
You also might want to try exp... |
3,945,167 | 3,945,308 | Why does free crash here? | The following crashes when it gets to free: (there is reasoning for using void*).
bool s = true;
void* arg = &s;
argument = malloc(sizeof(arg));
memcpy(argument,arg,sizeof(arg));
free(argument);
argument here is a void*
why does free crash the application?
Thanks
| Your problem is most likely elsewhere.
Since you have some misconceptions about sizeof (pointer) I suspect you have a buffer overflow/underflow elsewhere in your program which is resulting in corruption of heap headers, then free crashes when it tries to iterate across the corrupted heap.
Others are correct when they p... |
3,945,404 | 3,945,439 | In a multithreaded c++ program using boost, is there any way to get a pointer to the current thread? | I need to know the identity of the current thread to keep track of which threads are making certain requests to a shared data structure.
| You can use boost::this_thread::get_id() to get a boost::thread::id representing the thread.
I don't think you can get a pointer to a boost::thread object, because the thread doesn't necessarily have one attached. And it cannot make one because it might have one attached.
|
3,945,453 | 3,945,558 | File extraction doesn't seem to advance to the next word in the file | I think this has happened to me before. This isA3.txt:
%INSERT
MARK 29
DAVID 21
JOHN 44
JOHN 51
LARRY 39
MARK 21
DAVID 18
JOHN 28
MARK 35
DONALD 41
PHIL 26
Even though I use sourcefile >> reader at the end of the loop, the program keeps outputting "reader: MARK", meaning the sourcefile >> reader; statement isn't work... | sourcefile >> node -> id; fails, and after that none of the input operations from sourcefile succeed, as failbit becomes set in the sourcefile stream. sourcefile >> node -> id; fails because it tries to read an integer but encounters "DAVID" in the stream. That happens because sourcefile >> reader; consumes "MARK", sou... |
3,945,587 | 3,945,610 | is this C++ getter-like syntax wrong? | Say i have the following class :
class Abc {
int id;
public:
int getID() { return id; }
int setID(int id) { this->id = id; }
};
Is there any logical error in this ? I seem to be getting unexpected results (read : wrong values of id). I know this is not the way to write a getter .. but still there s... | A few notes:
int getID() should be a const method.
Why does setID() have an int return type? It doesn't return a value. How does this even compile?
Are you sure the unexpected results are because of the getter/setter? Do you have a short test program to demonstrate the problem?
EDIT: Now that you posted your code, I ... |
3,945,899 | 3,945,920 | should I include a header that is already included via other headers? | I had only just noticed my programs using the string class were compiling without including the <string> header. It turns out that <iostream> includes <ios_base> which in turn includes <string>.
Is this bad practice and should I explicitly include <string>? Even if it's just a case of clarity?
Is it safe to assume this... | You should explicitly include whatever standard library headers you need.
It is not specified which standard library headers are included by other standard library headers, so such details will differ between compilers.
One case where you can rely on a header being included by another header is if a class in one head... |
3,946,123 | 3,946,132 | C++ macro - capitalize string | I'm using preprocessor macros to declare some repetitive variables, specifically:
QuitCallbackType quitCallback;
LossCallbackType lossCallback;
PauseCallbackType pauseCallback;
KeyCallbackType keyCallback;
MouseCallbackType mouseCallback;
I'd like to use a preprocessor macro to do it, a la
CREATE_CALLBACK_STORAGE(quit... | The macro preprocessor doesn't have the ability to take substrings or capitalize a letter. Sorry.
If you could change your naming scheme you might have more success. For example:
QuitCallbackType _QuitCallback;
Edit: I've been warned not to use leading underscores, but the idea still applies:
QuitCallbackType callba... |
3,946,260 | 3,946,314 | C++ : Read form text file and convert to int problem? | I have this code that reads from marks.txt file.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main () {
string name,result;
int number1;
ifstream myfile ("marks.txt");
if (myfile.is_open())
{
while ( !myfile.eof() )
{
getline (myfile,name,... | Note that you're passing \t (tab character) as the delimiter to getline. Are you sure you are using a tab in your input file? If you use a space or any other character, all the input will go into name and your result will be empty, which will leave number1 undefined. I suspect that's the reason you're getting 36 out of... |
3,946,543 | 3,948,616 | UML and favourite IDE | I've just downloaded Visual Paradigm for UML and it looks quite ok. Does anyone have any experience with it? Or maybe someone has his own favourite IDE which is worth using and wouldn't mind sharing this knowledge? Do not want to use IDE which is written in JAVA or C# for patriotic reasons.
| I would recommend you Visual Paradigm. It is has very intuitive interface and it is easy to use. I use it at the moment. But if you want to try something else this page could be helpful http://en.wikipedia.org/wiki/List_of_UML_programs.
|
3,946,558 | 3,946,710 | C++: Read from text file and separate into variable | I have this in a text file:
John 20 30 40
mike 30 20 10
How do i read from the text file and separate them into variable name, var1, var2, var3.
This is my attempt, seems it doesnt work. Help please.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main () {
strin... | Something like this should work (I don't have a compiler handy, so you may need to tweak this a little):
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
ifstream inputFile("marks.txt");
string line;
while (getline(inputFile, line))
{
istringstream ss(line);
s... |
3,946,598 | 3,946,616 | C++ Constant preprocessor macros and templates | So say I have the following very simple macro, along with a bit of code to output it:
#define SIMPLEHASH(STRING) STRING[1] + STRING[2] + STRING[3]
std::cout << SIMPLEHASH("Blah");
This outputs 309, and if you view the assembly you can see:
00131094 mov ecx,dword ptr [__imp_std::cout (132050h)]
0013109A pus... | Macros are evaluated before the source is fully parsed and preprocessing has nothing at all to do with templates.
The problem is that the template argument with which you instantiate Printer must be a constant expression and you cannot use a string literal in a constant expression.
|
3,946,876 | 3,946,905 | Iterating through a tree | I'm trying to figure out how I can iterate in reverse, and forward through this, or atleast call a method in reverse.
Here is how it works.
Widgets have a std::vector of Widget* which are that control's children. The child vector is z ordered which means that child[0] is behind child[1] (in render order). Each control ... | Forward iteration:
void blah_forward(const Widget *p)
{
p->do_something();
std::for_each(p->children.begin(), p->children.end(), blah_forward);
}
Reverse iteration:
void blah_reverse(const Widget *p)
{
std::for_each(p->children.rbegin(), p->children.rend(), blah_reverse);
p->do_something();
}
(unteste... |
3,946,955 | 3,946,978 | Unable to resolve overloaded class methods in template delegate | Background: I'm using a delegation technique to abstract access to arbitrary object methods, but I'm having some issues where the linker is concerned. Consider the following class, ContextNode.
template <class ObjectType, class GetType, class SetType>
class ContextNode: public ContextNodeBase {
public:
ContextNo... | You can use a cast to disambiguate an overloaded function name:
(int (Thing::*)(void))(&Thing::value)
(void (Thing::*)(const int&))(&Thing::value)
|
3,947,003 | 3,947,016 | Removing something from a STL container without deconstructing it | Ok, I'm using C++ STL containers (currently vector<customType*>).
Now I need to remove elements from the container,
but using erase deconstructs the object, which is bad, since I'm taking it off one, and putting it onto a variable doing some processing then onto another one.
At the moment my code is quite nasty, and I'... | If you have a container of pointers (which it sounds like you do since you are assigning NULL to "erased" elements), then erasing an element from the container does not delete the pointed-to object. You are responsible for doing that yourself.
If you have a container of objects (well, non-pointer objects), then you ne... |
3,947,031 | 3,947,180 | CPP:How to pause resume a running script in cmd line console using mouse? | I am in desperate need of help.... :). I am running a script from cmd line console. It does a sequence of operations. whats the best way to pause the script in between to check the results and resume it back using mouse????? or any key
I would appreciate for your reply back,
-Abishek
| If I understand your question correctly, and if your program is writing to the standard output (the console window) and you are running on Windows:
You can turn on 'quick edit' in the console window by editing the cmd.exe window properties.
Open a command prompt (start | run | cmd.exe)
Click the upper left corner of ... |
3,947,038 | 3,947,135 | How can I override the close button on a third-party application so that it minimizes instead? | I would like to override the close button on a third-party application so that it causes the application to be minimized instead. I do not have source code for the target application.
Can I write such thing in C#? Or do I need to use C++?
How do I write this kind of hook? Do I need a process running or would a driver... | You can do it in both C++ and C#. To do this, you would have to hook into the applications message loop and override the WM_CLOSE message to WM_MINIMIZE. To hook into any process that's running you can use:
Microsoft Detours (Commercial and not free if I remember correctly) (http://research.microsoft.com/en-us/project... |
3,947,067 | 3,947,076 | Why could an enum type be used without defined | I am using VC2008 as my complier, and it is surprised to me that an enum could be used without defined:
void func(enum EnumType type)
{
}
Code above could be compiled and run without a problem, could anyone explain why it works?
Update:
I could define an empty enum in C++, as follow:
enum EnumType {};
| This is evidently a nonstandard Visual C++ language extension.
You cannot forward declare an enum in standard C++.
|
3,947,127 | 3,947,149 | Accessing an object's attributes correctly out of a vector and clearing it out | I'm unfamiliar with OO in C++.
I've been pushing instances of the MyPoint class into
vector <MyPoint> trianglePoints;
like this:
trianglePoints.push_back(MyPoint(x,y));
This is my definition of MyPoint:
class MyPoint {
public:
float x;
float y;
MyPoint(float x, float y) //constructor
{
t... | a)
trianglePoints[0].x
trianglePoints[0].y
trianglePoints[1].x
trianglePoints[1].y
trianglePoints[2].x
trianglePoints[2].y
b)
Yes, the class uses the default destructor.
|
3,947,159 | 3,947,725 | define double constant as hexadecimal? | I would like to have the closest number below 1.0 as a floating point. By reading wikipedia's article on IEEE-754 I have managed to find out that the binary representation for 1.0 is 3FF0000000000000, so the closest double value is actually 0x3FEFFFFFFFFFFFFF.
The only way I know of to initialize a double with this bin... | Hexadecimal float and double literals do exist.
The syntax is 0x1.(mantissa)p(exponent in decimal)
In your case the syntax would be
double x = 0x1.fffffffffffffp-1
|
3,947,172 | 3,947,211 | Send data with boost::asio::socket_base | Why does socket_base not have a send() method? Basically, I would like to use boost::asio's sockets like linux socket descriptors: whether the underlying socket is UDP or TCP it doesn't matter, you can call read(), write(), sendto(), etc... on them.
Is there a more proper solution than just writing a wrapper class arou... | You need to use a particular type of socket, like boost::asio::ip::tcp::socket, which is a stream-based TCP socket, or boost::asio::ip::udp::socket, which is for datagrams. The socket_base class is simply a base class which stores common functionality. The actual socket classes contain all the transfer functions you'... |
3,947,183 | 3,947,502 | Can I override an overload of an operator and return a different type? | class A{
public:
virtual char &operator[](int);
protected:
..
};
class B:A{
public:
A* &operator[](int);
protected:
}
Can I change the return type when I overload an overload of an operator?
thanks!
//EDIT
Okay, so now that we established that this wont work how can I build a work around?
Lets sa... | The reason that a polymorphic function can't return different types in different classes isn't because someone on the C++ committee decided that it was "taboo", but because any code that used that function's return value couldn't compile.
By creating an inheritance heirarchy, you're able to access derived objects throu... |
3,947,385 | 3,947,393 | Why am I getting vector iterators incompatible? | I'm doing the following and getting that debug error:
AguiWidgetBase* AguiWidgetContainer::recursiveGetWidgetUnderMouse(
AguiWidgetBase* root, const AguiMouseEventArgs &mouse)
{
AguiWidgetBase* currentNode = root;
bool foundsomething = true;
while(foundsomething)
{
foundsomething = false;
... | You are reassigning the end position which is being checked by your iterator.
2 comments:
Put the brackets around your if statements. You're allowed not to do it but it makes the code more readable if you do and reminds you to indent.
add a break statement to the inner if so that you don't need to continue traversing... |
3,947,651 | 4,463,717 | Using C++0x TR1 random in a class, for low overhead | I'm using VC 2010 and trying to keep the overhead and duplicated code of certain functions low, by placing the random definitions in the constructor of each class instance, then calling as necessary from there. What I have now, simplified, is:
#include <random>
#include <Windows.h>
mt19937 eng(GetTickCount());
class C... | bind() is used in c++0x instead of variate_generator<>:
#include <functional> // bind
#include <iostream>
#include <vector>
#include <random>
namespace {
std::random_device generate_seed;
std::mt19937 eng(generate_seed());
class Cycles {
int line;
std::normal_distribution<> rand_norm;
std::functi... |
3,947,653 | 3,947,665 | Differing between function argument names and class variable names | class line
{
public:
line(int Width)
: width(Width)
{
}
private:
int width;
};
I could name Width something like wantedWidth, but I'm just wondering, is there a convention for this or a better way? I don't want to use Hungarian notation.
| Yes there's a convention, hundreds of them. Mine is to simply postfix my member names with an underscore.
|
3,947,960 | 3,947,986 | LNK2019 and LNK1120 with functions in an external file | I have taken out some functions from a source file into another since I want to use them also in other files. The current structure is as follows
utils/extFuncs.h
#ifndef _extFuncs_h
#define _extFuncs_h
inline int someFunction (float v);
#endif
utils/extFuncs.cpp
#include "utils/extFuncs.h"
inline int someFunction (fl... | someFunction is declared inline, so it must be defined in your header file:
utils/extFuncs.h
#ifndef _extFuncs_h
#define _extFuncs_h
inline int someFunction (float v)
{
return 42;
}
#endif
|
3,948,035 | 3,948,607 | Detail learning of c++ design patterns | Thanks for your valuable time.
I want to learn c++ design patterns. I searched on web but I was not getting documents which gives me better details about design patterns. I was getting good details but those were in different URL's, I required all the information in one place only so that it will be better to know wha... | Vince Huston has a sketchy website... but it neatly illustrate implementations of all the Design Patterns mentionned in the GOF book in C++.
Check it out :)
Each pattern is presented with several sections:
name (thanks Lou for pointing it out :P)
intent
problem (that it solves)
structure summary (with a nice diagram)
... |
3,948,111 | 3,948,345 | Need a short, complicated C++ code and a longer, understandable version | In this question, I tried to give an example of two ways of doing the same thing in C++: one short but complicated "fancy" piece of code; and a longer but more readable and understandable way of doing the same thing. The question asks whether it's better to have a well-commented fancy piece of code or a self-commented ... | How about this?
//direct formula for xoring all numbers from 1 to N
int Sum = (N & (N % 2 ? 0 : ~0) | ( ((N & 2)>>1) ^ (N & 1) ) );
instead of:
int Sum = 0;
for (int i = 1; i < N; ++i)
{
Sum ^= i; //or Sum = Sum ^ i;
}
Formula taken from here
|
3,948,158 | 3,949,485 | How to add node at some specific index in a linked list? | void insertLoc(int n, int i)
inserts a node with info n after the ith location in the list. If the ith location does not exist in the list then the program should exit with an error message.
Can anyone help me with the code please...
#include<iostream>
#include<process.h>
using namespace std;
struct node {
int i... | See insertLoc method below. I changed the size method to return count instead of printing it on the screen. A list class shouldn't print to the screen...just manage the list. If something about the list needs to be printed on the screen, it would be better to have main (or some other code) call methods on the list c... |
3,948,211 | 3,948,260 | Organizing files in Visual C++ project | I'm writing a project in Visual C++ 2010 Express edition. Everything was fine before I tried to add new source file in the project. Then when I tried to include one of the header files the compiler said that the class declared in this header is not found in other source file which includes the same header file.
This is... | Have you included OSGFComponent.h and Game.h in the osgfdrawablecomponent.h header file ?
|
3,948,233 | 3,948,273 | Calculating co-ordinates for a sprite in C++ | I am trying to calculate the angle of movement for a sprite in C++.
Although at the moment I am just using the console to output my results.
My problem is that when My results are shown in the console, I cannot get the x axis to go into minus numbers.
Unfortunately I have only just learned about basic trig so I have no... | Change to:
mySprite.x += floor(cos(mySprite.angle*PI/180)*mySprite.speed + 0.5);
mySprite.y += floor(sin(mySprite.angle*PI/180)*mySprite.speed + 0.5);
And read this (or any other guide you like) to understand why.
|
3,948,290 | 3,948,314 | What is the safe way to fill multidimensional array using std::fill? | Here is what I am using:
class something
{
char flags[26][80];
} a;
std::fill(&a.flags[0][0], &a.flags[0][0] + 26 * 80, 0);
(Update: I should have made it clear earlier that I am using this inside a class.)
| The simple way to initialize to 0 the array is in the definition:
char flags[26][80] = {};
If you want to use std::fill, or you want to reset the array, I find this a little better:
char flags[26][80];
std::fill( &flags[0][0], &flags[0][0] + sizeof(flags) /* / sizeof(flags[0][0]) */, 0 );
The fill expressed in terms ... |
3,948,374 | 3,948,398 | Windows aplication that lives only in the taskbar | I'm new to windows programming (any win 32 API).
I want to create a windows application that listens to the clipborad all the time and reacts to keyboard shortcuts (for example you copy text from the ClipBoard and press Ctrl-F and something is done on the text in the clipboard).
I know how to make a window app in win32... | It can be another windows application in which the form's ShowInTaskbar property is set to false and you add a NotifyIcon component to put it into tray. Here is an article from CodeProject. You can find many more on codeproject or on other programming related sites.
|
3,948,600 | 3,949,460 | Check if windows shell has finished loading startup programs | How can i programatically check if the windows shell (explorer) has loaded all startup programs & the user login process is over ?
| There is a somewhat documented event you can wait for, but it is signaled when explorer has started loading. On XP this event is called "msgina: ShellReadyEvent" and "ShellDesktopSwitchEvent" on Vista. I linked to the sources of some alternative shells in a post related to this event.
Another alternative would be to li... |
3,948,645 | 3,948,666 | Name convention for deleting data in C++ | Assume I have some C++ method which returns back a pointer to an object. Something in the header file that looks like this:
uint8_t* getData(void);
This guy returns a byte array, but there is nothing that says if this is a dynamic or statically generated piece of data (local to the class or created with new).
Is there... | My conventions are:
uint8_t* getData();
is statically allocated, or at least it's not my responsibility for deleting this data. However if it's an array I would write:
pair<uint8_t*,uint8_t*> getData();
Or define a container for that.
auto_ptr<uint8_t> getData();
unique_ptr<uint8_t> getData();
allocates single objec... |
3,948,658 | 3,948,674 | Why my prog can't run correctly? | // Calculate the quarters of a set of integers
#include <iostream>
#include <vector>
#include <algorithm>
#include <conio.h>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::sort;
int main()
{
// Ask for a set of integers
cout << "Please input a set of integers: "
<< endl;
// Rea... | int_set_quarter's size is 0 and you index on it.
Change
vector<double> int_set_quarter;
to
vector<double> int_set_quarter(size);
|
3,948,663 | 3,949,278 | Does it ever make sense to overload unary operator &? | So, C++ allows overloading the unary operator &(address). Are you aware of any real-world example when operator & was rightfully overloaded? And a second, more specific question, are you aware of any real-world example when operator & was rightfully overloaded while preserving address semantics? TIA
| I've got 207 real-world examples of operator &(): Code search 1, Code search 2.
Including SafeInt<> (to get the underlying naked integer), boost::gil (apparently also to yield the raw data), Mozilla (that say "it is risky to define operator&, but, hey, we know what we're doing."), wxWidgets, Armagetron and lots of more... |
3,948,702 | 3,961,485 | Set_union/Set_intersect for more than two sets in c++ | I know those commands are for two sets.
Does there any simple and fast way to do this for more then two sets.
I think I can use some kind of loop for this but maybe there are better way.
Thank you
| For set union, if you are going to see which of M sets has the smallest value that will take M-1 comparisons. So now we pop off this value and go again. If N is the total number items in all the sets our algorithm this way is O(NM) (ignore that it's M-1 for Big-O notation).
Where we might be able to optimise is as foll... |
3,948,711 | 3,948,832 | print a screenshot of the desktop and convert in to a matrix of pixels[0,1] | I want to build a program that prints the current screen (every few seconds) and searches for symbol in it.
I already have the function that knows how to find a given symbol in a larger function, however I do not have the followings:
How can i capture the current screen (print screen).
How do i convert the picture int... | I just did a google search and came up with this, and this. HTH
|
3,949,046 | 3,949,057 | Passing PChar / *char between C++ and Delphi DLL | I have a C++ program, that calls Delphi DLL to initialize a buffer that contains chars.
I am testing out the interface to make sure the data are passed correctly:
In C++ program:
char * pMsg = (char*)malloc(3); //allocate buffer
Init(pMsg * char); //Delphi DLL function
In Delphi DLL:
procedure Init(pMsg:PChar);
var
... | Delphi does not use NULL-terminated strings so you need to slap a 0 at the end, as C/C++ uses that to determine where the string data ends (Pascal uses the size of the string at the beginning IIRC).
The usual character is '\0' - escape value 0.
Don't forget to return 4 characters, not 3.
|
3,949,329 | 3,949,769 | Issue while designing B+Tree template class in C++ | I'm trying to write a generic C++ implementation of B+Tree. My problem comes from the fact that there are two kinds of nodes in a B+Tree; the internal nodes, which contain keys and pointers to child nodes, and leaf nodes, which contain keys and values, and pointers in an internal node can either point to other interna... | The simplest way:
bool mIsInternalPointer;
union {
InternalNode<T>* mInternalNode;
LeafNode<T>* mLeafNode;
};
This can be somewhat simplified by using boost::variant :)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.