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,351,132 | 3,351,406 | Is there a better way to run a c++ makefile from a c# project? | I have a project in c# which uses bindings to use some c++ code. The c++ code consists of multiple DLL's which are compiled using a makefile. Currently I'm trying to run the makefile using a pre build event which calls nmake. However to get it to find nmake I need to have a line in it like the following:
"$(DevEnvDir).... | I often build non VS-project (sometimes with nmake, sometimes with other build tools) as a part of a larger solution build.
I tend to make a simple batch file, which sets up the environment and then runs the make.
I call the batch file from a build event (often post-build on my stuff) - usually with a CD on the fron... |
3,351,181 | 3,351,379 | Breaking cyclic dependency in C++ | I have the following cyclic dependency problem I am trying to solve:
typedef std::map<int, my_class> my_map;
class my_class {
...
private:
my_map::iterator iter;
};
class otherclass{
public:
my_map::iterator getIter();
private:
my_map map;
};
The compiler does not like this, since my_class was not decla... | class my_class;
typedef std::map < int, my_class* > my_map;
~~~~~~~~~~ use pointer here!
|
3,351,280 | 3,351,627 | C++0x Lambda to function pointer in VS 2010 | I am trying to use a lambda to pass in place of a function pointer but VS2010 can't seem to convert it. I have tried using std::function like this and it crashes and I have no idea if I am doing this right!
#include <windows.h>
#include <conio.h>
#include <functional>
#include <iostream>
#include <concrt.h>
void m... | This feature of lambda's was added after VS2010 implemented them, so they don't exist in it yet.
Here's a possible generic work-around, very untested:
#include <functional>
#include <iostream>
namespace detail
{
// helper specializations,
// define forwarding methods
template <typename Lambda, typename Fun... |
3,351,283 | 3,351,324 | Force application to close on Windows CE using C++ | How can I force an application, say myapp.exe, to close using C++ on Windows CE from a different application?
The scenario is that I have a previous installation of some software that does not behave properly when upgrading to a new version. I therefore need to kill a process (from the updater) before continuing the up... | TerminateProcess? (MSDN)
BOOL TerminateProcess( HANDLE hProcess,
DWORD uExitCode );
You will need the HANDLE to the process which you can easily obtain using the Toolhelp32 APIs. An eample of their use to enumerate all processes on the system can be found here.
|
3,351,511 | 3,351,611 | Help Integration in Qt/C++ Application | I am using Qt 4.6 so do C++.
I have a User Manual (.chm) for my application which has the help required for the users to run the application. Now I want this help to be integrated into my application, so that when the user selects for help from the application, the user manual will be opened with the corresponding he... | Yes, it's possible. The help system infrastructure was designed to integrate with normal Win32 development in Visual Studio, but this is not technically necessary. Basically you just call HtmlHelp(GetDesktopWindow(), "Yourhelp.chm", HH_HELP_CONTEXT, IDYourCurrentContext);.
|
3,351,940 | 3,351,994 | detecting the memory page size | Is there a portable way to detect (programmatically) the memory page size using C or C++ code ?
| Since Boost is a pretty portable library you could use mapped_region::get_page_size() function to retrieve the memory page size.
As for C++ Standard it gives no such a possibility.
|
3,352,196 | 3,352,233 | operations on files in c++ | for example we have created file in c++ how to write content in this file and then output on screen?
| Taken from here.
Writing:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Reading:
#include <iostream>
#include <fstream>
#include <string>
using namespace std... |
3,352,382 | 3,352,449 | problem with reading program arguments in Visual Studio C++ | I'm running C++ program in VS2005, and I've set only one argument in project properties-> debug-> command line args, and it's named profile1.dll for example.
here's a code snippet
cout<<"number of arguments:" << argc<<endl;
for (int i=0; i<argc; i++)
cout << "argument " << i << ": " << argv[i] << endl;
In th... | Does the name of your exe start with C? If you expect a string and you only get one character, it's usually because you've discovered that the Western alphabet in UTF-16 Unicode effectively puts a 0 between alternating ANSI chars. Are you compiling for Unicode ?
|
3,352,402 | 3,354,096 | Memory Management + containers | Friends
Containers have automatic memory management mechanism .
When values are inserted using copy Constructor and when values are removed , destructor is called for each value.
After the no of elements are read, what stage desctuctor gets called ?
How does a container class handle memory when elements are read not... | Containers don't have memory management, objects have memory management.
obj a;
{
std::vector<obj> b;
b.push_back( a );//copy of 'a' taken here
}//copy of 'a' in vector destructed here because the copy goes out of scope not specifically the vector
//'a' still exists
alternatively
obj* a = new obj;
{
std::... |
3,352,554 | 3,352,678 | Solve this Error ,while using 'export' keyword in templates? | Program :main.cpp
struct X {
int x;
};
export template <class T> T const& min(T const&, T const&);
int main()
{
return min(2, 3);
}
x.cpp
struct X {
int x;
};
export template <class T> T const& min(T const &a, T const &b) {
return a<b ? a : b;
}
error:Compiling with g... | Looks like your compiler doesn't support separate template compilation. It is a common practice not use separate compilation with templates and distribute templates in header files. Besides that, I spotted several issues.
Remove export keyword from the declaration. This should take care of call of overloaded ‘min(int,... |
3,352,765 | 3,352,826 | operator== with double dispatch in C++ | How should one implement
operator==(const Base& base)
to compare subclasses s.t. the calls would be properly dispatched when called as
Base* base1 = new Derived1();
Base* base2 = new Derived2();
base1->operator==(*base2)?
|
Implement operator== as a free standing function.
Have it call a virtual method on one of the arguments (e.g. IsEqual())
That gets you to the point where you have
Derived1::IsEqual(const Base& base)
Called. From here you have some options
Use RTTI to dynamic_cast<> base to Derived1
If the number of derived is smal... |
3,352,838 | 3,352,921 | How can I get the address of the buffer allocated by vector::reserve()? | I have a std::vector of values for which I know the maximum size, but the actual size will vary during usage:
void setupBuffer(const size_t maxSize) {
myVector.reserve(maxSize);
}
void addToBuffer(const Value& v) {
myVector.push_back(v);
if (myVector.size() == maxSize) {
// process data...
myVector.clea... | The vector buffer will not be moved after a call to reserve unless you exceed the reserved capacity. Your problem is getting the pointer to the first element. The obvious answer is to push a single fake entry into the vector, get the pointer to it, and then remove it.
A nicer approach would be if the library accepted ... |
3,353,325 | 3,353,441 | Are there any other keywords that can be accessed using the global namespace scope resolution operator? | The global new and delete can be used like normal, but you can also prefix the :: operator to them and it will work the same.
Are there any other keywords that have this same behaviour?
| Yes, you can also scope operator keyword, like ::operator+(a, b).
I believe new, delete and operator are the only ones in standard C++ that allow this.
|
3,353,482 | 3,394,170 | Boost serialization fails in release mode while working in debug | I am using boost serialization with xml files with a C++ program.
When I test my program in debug mode, it is working fine.
Then I try with the exact same file in release mode, but my program fails when loading the files. I even tried to generate the xml files with my program in release mode, load them back, and it cr... | The issue was due to the fact that I was compiling using
Multi-threaded Debug DLL (/MDd)
instead of
Multi-threaded DLL (/MD)
in release mode.
|
3,353,769 | 3,400,745 | MFC Ribbon - get base element clicked from command | I have a CMFCRibbonUndoButton on the ribbon of an MFC application. I have a handler for when its ID is clicked (ON_COMMAND(ID_EDIT_UNDO, ...)). However, when the button is also in the quick access toolbar (QAT), there are apparently two CMFCRubbonUndoButtons which each keep their own state. In the command handler, I... |
Is there a way in my ON_COMMAND handler to get the CMFCRibbonBaseElement* that fired the event?
Not directly, no. The WM_COMMAND message is sent from CMFCRibbonBaseElement::NotifyCommand, and this message doesn't include the pointer in its parameters.
To be able to tell which Undo button was clicked from the ON_COMMA... |
3,353,790 | 3,353,886 | how write this code in c++ | i have following code
uint32 joaat_hash(uchar *key, size_t len)
{
uint32 hash = 0;
size_t i;
for (i = 0; i < len; i++)
{
hash += key[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return has... | That, to me, seems to already be a C++ code. I wonder why you think it's not.
But since C++ doesn't have uint and uchar explicitly defined you'll need to either have this piece of code before that function.
typedef unsigned int uint32;
typedef unsigned char uchar;
Otherwise, rewrite the function like:
unsigned int joaa... |
3,353,831 | 3,353,959 | Resolving a Circular Dependency between Template Classes | I have two classes, Foo<T> and Bar<T>, derived from Base. Each overrides a method virtual Base* convert(ID) const, where ID is an instance of a type that uniquely identifies a particular instantiation of Foo or Bar (pretend it's an enum). The problem is that Foo::convert() needs to be able to return a Bar instance, and... | What you need to do is seperate the class declarations from the implementation. So something like
template <class T> class Foo : public Base
{
public:
Base* convert(ID) const;
}
template <class T> class Bar : public Base
{
public:
Base* convert(ID) const;
}
template <class T> Base* Foo<T>::convert(I... |
3,353,949 | 3,354,031 | Convert TCHAR * -> std::wstring in both unicode and non-unicode environments | I have some code in a library which has to internally work with wstring, that's all nice and fine. But it's called with a TCHAR string parameter, from both unicode and non-unicode projects, and I'm having trouble finding a neat conversion for both cases.
I see some ATL conversions and so on but can't see the right way,... | Assuming TCHAR expands to wchar_t in Unicode builds:
inline std::wstring convert2widestr(const wchar_t* const psz)
{
return psz;
}
inline std::wstring convert2widestr(const char* const psz)
{
std::size_t len = std::strlen(psz);
if( psz.empty() ) return std::wstring();
std::vector<wchar_t> result;
const int l... |
3,354,125 | 3,354,193 | io operation using same stream object | I want to perform I/O operation in c++. I want to store a pointer to fstream object and using that same fstream I want to read and write to that file. Is it possible without using two different objects i.e ifstream for reading and ofstream for writing.
| Yes, fstream can be used for reading and writing. Is this what you want to accomplish?
// Your fstream object
std::fstream a("coco.txt");
// Buffer
char foo[100];
// Write
a<<"Hello"<<endl;
// Rewind
a.seekg(0,ios::beg);
// Read
a>>foo;
// Display
std::cout<<foo;
// Clean up
a.close();
|
3,354,145 | 3,355,362 | Problem with ifstream::setbuf in VS2008 | What changes are needed when porting "setbuf" in VS2005 to VS2008?
I have to modify a project in VS2005 to VS2008 to be able to build it. Below is the line of code that needs to be compiled in VS2008.
std::ifstream In;
In.setbuf(FileBuffer, BUFFER_REGION_SIZE);
When I compile the above code in VS2008, I see the b... | Did you try something like In.rdbuf()->pubsetbuf(FileBuffer, BUFFER_REGION_SIZE);?
See http://www.cplusplus.com/reference/iostream/streambuf/pubsetbuf/
|
3,354,175 | 3,379,011 | How to move multiple rectangles as collision response? | I'm trying to make a game (using irrlicht engine with c++) where you can trap your enemy using boxes. But I just don't get how to detect what should be moved when a collision between the user and one or more boxes is detected. Another thing is that there will also be some objects called bricks which will be able to blo... | Is this a sort of Sokoban game where the player can move in 8 directions, and is able to move several boxes at once? Is the play field viewed from birds eye view like in Sokoban, or are they falling boxes that we see in the example (side view, like in Tetris)? Is the friction between boxes and player infinite (in anoth... |
3,354,230 | 3,354,349 | C++ error in ios_base.h |
/usr/include/c++/4.4/bits/ios_base.h: In member function ‘std::basic_ios >& std::basic_ios >::operator=(const std::basic_ios >&)’:
/usr/include/c++/4.4/bits/ios_base.h:793: error: ‘std::ios_base& std::ios_base::operator=(const std::ios_base&)’ is private
/usr/include/c++/4.4/iosfwd:47: error: within this context
... | You are trying to copy or assign a stream (descendant of std::istream or std::ostream). Streams, however, cannot be copied or assigned.
Edit
Change your code to:
std::ofstream myOutStream(myCurrentLogName.c_str(), std::ios::app);
|
3,354,346 | 3,354,393 | STL iterators and 'const' | I have a problem with what appears to be some sort of implicit casting to const when I use iterators. I'm not really sure which code is relevant (if I did I probably wouldn't be asking this question!) so I will try my best to illustrate my problem.
typedef set<SmallObject> Container; //not const
void Larg... | Sets and maps keep the elements in order according to the sort condition. For user code not to break invariants, the key of the map and the whole element in the set must be constant. Your problem is that the stored element is not a SmallObject but a const SmallObject.
If this was not limited you could have:
int init[] ... |
3,354,390 | 3,355,235 | How do I specify include directories using NMake? | I'm trying to use nmake to build the libfcg (http://www.fastcgi.com/), however I'm getting the following error:
..\include\fcgios.h(23) : fatal error C1083: Cannot open include file: 'windows.h': No such file or directory
I have the Widows SDK installed and the Windows.h file is present in this directory:
C:\Program F... | Pass -I"include dir" as command line option to cl.
|
3,354,490 | 3,354,522 | Strange visual studio 2008 C++ compiler error | I have three lines of code:
//int pi;
activation->structSize = sizeof(rmsActivationT);
int pi; //program wont compile with this here
every time I uncomment the second int pi and comment the first int pi I get this error: syntax error : missing ';' before 'type'. When i uncomment this first int pi and comment the se... | Are you, perhaps, compiling the code as C instead of C++? C (prior to C99, which Visual Studio doesn't support) required that all definitions in a block precede any other statements.
|
3,354,562 | 3,354,674 | Error 10061 while trying to connect to my own computer | I'm just testing out some basic networking code written in Visual C++. I have a client app and a server app that don't do anything fancy, since I'm just testing - basically, the client sends ASCII-encoded strings to the server and the server sends it back all in caps.
Everything works fine when I run both programs on m... | Ensure your server is not binding to a specific IP address; it should bind to IPAddress.Any on a specific port.
If that doesn't solve the problem, run the server and examine the output of netstat -a for your port.
|
3,354,694 | 3,354,720 | Static variables in C++ | I ran into a interesting issue today. Check out this pseudo-code:
void Loop()
{
static int x = 1;
printf("%d", x);
x++;
}
void main(void)
{
while(true)
{
Loop();
}
}
Even though x is static, why doesn't this code just print "1" every time? I am reinitializing x to 1 on every iteration be... | The initialization of a static variable only happens the first time. After that, the instance is shared across all calls to the function.
|
3,354,765 | 3,354,799 | Running c++ from Java problem | I need to compile and run a c++ program from java. I am using
Process a = Runtime.getRuntime().exec ("g++ -g function.cpp -o function");
Process b = Runtime.getRuntime().exec ("./function");
the problem is that the output I get from the c++ program is not correct but If I compile and run it myself in the command line i... | There is one definite and one probable problem that I see here. The definite problem is that Runtime.exec() does not wait for the process to complete. So you will need to add
a.waitFor();
before calling b.
The possible issue is that depending on how you are invoking this application, the current working directory may... |
3,354,938 | 3,355,007 | Openmp usage in C++ object constructors | Can I use openmp in C++ objects' constructors?
What will be done, when there will be a global static object with such constructor?
| yes. imagine this to be the same as calling OpenMP function from constructor.
A second point, I do not know, it may depend on implementation. I am fairly certain the pthreads implementation should be okay for global static objects. http://www.terboven.com/download/poster_A0_portrait_neu_formatiert.pdf
Static initial... |
3,354,966 | 3,461,602 | How do I obtain a value of an HTML field with C#/C++ | I'm using HtmlElement to get an HTML element by it's ID and trying to display this value and return it (as a String). The problem is that it sees it as an Object.
I have a webBrowser in the code with an HTML file that has:
<label id="Address" text="asdf"></label>
In my C++ header file I have
HtmlElement^ element =... | OK I finally figured out the problem after switching projects and coming back to it after a while.
I forgot the 'System::Object^ sender' part in my header file. Now all the HtmlElement stuff works.:
public: System::String^ GetAddress(System::Object^ sender)
Thanks for all your help.
|
3,355,372 | 3,355,464 | Cannot find C++ library when linking, error compliling the `boost::program_options` example | I am trying to compile the multiple_sources.cpp to compile on my computer. I am running Xubuntu Lucid Lynx fully updated.
It will compile without issue with g++ -c multiple_sources.cpp but when I try to link and make an exectuable with g++ multiple_sources.o I get:
multiple_sources.cpp:(.text+0x3d): undefined reference... | The -l param is wrong; get rid of the lib pre-fix and use -lboost_program_options.
The linker expects all libraries to begin with lib, and for you to leave that off when specifying the library.
You could also include the full path to the library in the list of files, without -l (e.g. g++ multiple_sources.cpp /usr/lib/l... |
3,355,379 | 3,355,465 | How do I find out if a .exe is running in c++? | How can you find out if an executable is running on Windows given the process name, e.g. program.exe?
| The C++ standard library has no such support. You need an operating system API to do this. If this is Windows then you'd use CreateToolhelp32Snapshot(), followed by Process32First and Process32Next to iterate the running processes. Beware of the inevitable race condition, the process could have exited by the time yo... |
3,355,683 | 3,356,421 | c++ stack trace from unhandled exception? | This question has been asked before and there have been windows-specific answers but no satisfactory gcc answer. I can use set_terminate() to set a function that will be called (in place of terminate()) when an unhandled exception is thrown. I know how to use the backtrace library to generate a stack trace from a given... | Edited Answer:
You can use std::set_terminate
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <execinfo.h>
void
handler()
{
void *trace_elems[20];
int trace_elem_count(backtrace( trace_elems, 20 ));
char **stack_syms(backtrace_symbols( trace_elems, trace_elem_count ));
for ( int i... |
3,355,876 | 3,355,888 | C++ can't create vector | This is weird. I created a vector just fine in one class but can't create it in another class. He's a representation of what I have:
main.h
#include <Windows.h>
#include <ShellAPI.h>
#include <vector>
#include <string>
#include <iostream>
#include "taco.h"
class MyClass
{
public:
int someint;
vector<int> myO... | Try:
std::vector<int> otherOrder;
vector is part of the std namespace. This means that whenever you use a vector in a header file, you should include the std:: prefix.
The reason that you can sometimes get away with forgetting it is that some included files may have using namespace std; in them, allowing you to leave... |
3,356,026 | 3,356,096 | How can I count in a different number base in C++? | My 15 year old little brother is starting out programming, and he wrote a neat little program that outputs all combination of letters and numbers that are six digits or less. His code was a sextuple-nested for loop that updated the elements of a six level char array. It looked bad, but was certainly fast! I showed h... | Try this:
char buffer[1024];
for(int i = 0; i < 1000000; i++)
cout << itoa ( i, buffer, 36);
Here it is without itoa (if you don't have it)
cout << setbase (36);
for(int i = 0; i < 1000000; i++)
cout << i << endl;
cout << setbase (10); // if you intend to keep using cout
|
3,356,200 | 3,356,225 | Using Java to wrap over C++ | I have a project written in C++ and I'm looking to write a Java GUI as an interface to it. The choice of Java is fixed so I'd need to learn how to be able to call the C++ code from Java. Rewriting the C++ code is not an option. I'd like input on:
What tools can I use to achieve this wrapping.
How much of the C++ code... | You should look for JNI - Java Native Interface
|
3,356,456 | 3,357,579 | How to deal with different ownership strategies for a pointer member? | Consider the following class structure:
class Filter
{
virtual void filter() = 0;
virtual ~Filter() { }
};
class FilterChain : public Filter
{
FilterChain(collection<Filter*> filters)
{
// copies "filters" to some internal list
// (the pointers are copied, not the filters themselves)
... | Smart pointers here are not overkill: obviously you have a design problem that one way or another needs careful consideration of object lifetimes and ownership. This would be especially true if you want the ability to re-patch filters in the filter graph at runtime, or the ability to create compound FilterChain object... |
3,356,530 | 3,356,714 | Raw Binary Tree Database or MongoDb/MySQL/Etc? | I will be storing terabytes of information, before indexes, and after compression methods.
Should I code up a Binary Tree Database by hand using sort files etc, or use something like MongoDB or even something like MySQL?
I am worried about (space) cost per record with things like MySQL and other DB's that are around. ... | There are new non-relational databases that are becoming popular these days, that specialize in managing large-scale data.
Check out Hadoop or Cassandra, both of these are at the Apache Project.
|
3,356,661 | 3,356,721 | Getting a byte value using stringstream | I've got this (incorrect) sample code for getting a value out of stringstream and storing it in a byte-sized variable (it needs to be in a single byte var, not an int):
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char** argv)
{
stringstream ss( "1" );
unsigned char c;
s... | The most C++-ish way is certainly to parse the value properly by reading into another integral type, and then cast to a byte type (since reading into a char will never parse – it will always just read the next character):
typedef unsigned char byte_t;
unsigned int value;
ss >> value;
if (value > numeric_limits<byte_t>... |
3,356,700 | 3,356,759 | What's wrong here? - ISO C++ forbids declaration of 'Circle' with no type | maybe you can help me get this right.
I have a class that is used to draw a circle, but the compiler sends me this message:
In file included from ./Includes.h:19,
from ./Circle.h:8,
from ./Circle.cpp:5:
./GameApp.h:24: error: ISO C++ forbids declaration of 'Circle' with no type
./GameA... | Do not use one-massive-include-to-include-everything (except for precompiled headers). It will almost certainly result in headaches.
Include what you need, and no more. It will solve your problem.
You can forward declare Circle, as DanDan suggested, but fixing your inclusion problem will help you more in the long run... |
3,356,872 | 3,356,975 | Fast nbody algorithms / solutions (with opengl/c++/??) | I'm working on a (c++, opengl) project where I need to have lots of particles which influence eachother, if I'm correct this is called a nbody problem. Does someone knows what solutions there are for algorithms like this.
I know the barnes hut algorithm and maybe I can peek around openCL, though I'm not just wondering ... | Kd-trees are ideal for finding all objects (particles in this case) at a maximum distance. If the tree is balanced look ups are O(log n).
|
3,356,926 | 3,356,963 | Why do we need compiler defined constructor? | The compiler defined constructor is empty and does not initialize the member variables. Then why does the compiler create one?
Also what is the difference if any between a compiler defined constructor and an user defined empty constructor?
| The presence or absence of a constructor affects how users of the class can instantiate the object. If the compiler didn't create a default constructor, then you wouldn't be able to use a class or struct unless you created your own constructor.
|
3,357,169 | 3,357,248 | Member versus global array access performance | Consider the following situation:
class MyFoo {
public:
MyFoo();
~MyFoo();
void doSomething(void);
private:
unsigned short things[10];
};
class MyBar {
public:
MyBar(unsigned short* globalThings);
~MyBar();
void doSomething(void);
private:
unsigned short* things;
};
MyFoo::MyFoo() {
int i;
for (... | Because anything can modify your gt array, there may be some optimizations performed on MyFoo that are unavaible to MyBar (though, in this particular example, I don't see any)
Since gt lives locally (we used to call that the DATA segment, but I'm not sure if that still applies), while things lives in the heap (along wi... |
3,357,180 | 3,357,249 | Large matrix inversion methods | Hi I've been doing some research about matrix inversion (linear algebra) and I wanted to use C++ template programming for the algorithm , what i found out is that there are number of methods like: Gauss-Jordan Elimination or LU Decomposition and I found the function LU_factorize (c++ boost library)
I want to know if t... | As you mention, the standard approach is to perform a LU factorization and then solve for the identity. This can be implemented using the LAPACK library, for example, with dgetrf (factor) and dgetri (compute inverse). Most other linear algebra libraries have roughly equivalent functions.
There are some slower methods... |
3,357,344 | 3,357,375 | question about string to file | here is code
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
ofstream out("test", ios::out | ios::binary);
if(!out) {
cout << "Cannot open output file.\n";
return 1;
}
double num = 100.45;
char str[] = "www.java2s.com";
out.write((char *) &num, siz... | write takes two parameters, a char* and a length.
&num is actually a double*. It's the value we want, but it's the wrong type, and the compiler would complain. The (char*) tells the compiler to treat this as a char*. Basically, it says to the compiler "Shutup. I know what I'm doing".
sizeof(double) is the size of th... |
3,357,382 | 3,357,416 | Access a value from a separate function | class FinalList {
Location List[20];
int MaxSize;
int Size;
public:
FinalList()
{
MaxSize = 20;
}
void RunIt();
void Show();
void Mean();
void Menu();
};
void FinalList::Mean()
{
int K;
double Total;
double Average;
for(K=0 ; K < Size ; K++)
... | You can either store it in an instance variable (like you're doing with MaxSize) or make Mean() return the average value instead of just printing it out.
If you make Mean() return the average, then you can call it in your Show() function like this:
cout << "Average: " << Mean() << endl;
|
3,357,500 | 3,357,517 | Syntax error with template in c++ | I have following code:
#include <iostream>
using namespace std;
template<class T>
T max(T *data,int len){
int i;
T Max=data[0];
for (int i=1;i<len;i++){
if (data[i]>max){
Max=data[i];
}
}
return Max;
}
int mai(){
int i[]={12,34,10,9,56,78,30};
int len=sizeof(i... | C++ is case-sensitive.
#include <iostream>
// Note the omission of `using namespace std;`. The declaration can
// introduce clashes if one of your functions happen to have the same name
// as the functions in the std namespace.
template<class T>
T max(T *data,int len) {
//int i; <-- Not needed? The for loop alr... |
3,357,573 | 3,357,966 | Crazy C++ Vector iterator | I declare:
typedef std::tr1::shared_ptr<ClassA> SharedPtr;
And then:
std::vector<SharedPtr> mList;
And:
typedef std::vector<SharedPtr>::iterator ListIterator;
The return of mList.size() is 0, but when I use iterators, it iterates over the vector which is empty ! This is how I use the iterator:
for(ListIterator it = ... | I've solved the problem, the object class B was being destroyed after some scope. Anyway, thank you guys !
|
3,357,614 | 3,357,684 | Result of bitwise operator in C++ | Testing a couple of compilers (Comeau, g++) confirms that the result of a bitwise operator of some "integer type" is an int:
void foo( unsigned char );
void foo( unsigned short );
unsigned char a, b;
foo (a | b);
I would have expected the type of "a | b" to be an unsigned char, as both operands are unsigned char, bu... | This is in fact standard C++ behavior (ISO/IEC 14882):
5.13/1 Bitwise inclusive OR operator
The usual arithmetic conversions are
performed; the result is the bitwise
inclusive OR function of its operands.
The operator applies only to integral
or enumeration operands.
5/9 Usual arithmetic conversions
Many binar... |
3,357,777 | 3,357,796 | Memory allocation confusion | I created a class A and wrote the following function foo()
class A
{
public:
int a;
};
A * foo()
{
A a1;
return &a1;
}
int main()
{
A * a2;
a2 = foo();
return 0;
}
The compiler gave me a warning as a1 is a local variable and I am returning its address from the stack (so its value can change unpredictably).
Now I cha... |
Now the compiler does not give any warning.
The compiler isn't giving any warning because you've added sufficient complexity to fool the analysis that it does of your code.
You are still returning a pointer to a local variable, and you cannot use that pointer after the function has returned.
|
3,358,045 | 3,358,072 | How are malloc and free implemented? | I want to implement my own dynamic memory management system in order to add new features that help to manage memory in C++.
I use Windows (XP) and Linux (Ubuntu).
What is needed to implement functions like 'malloc' and 'free'?
I think that I have to use lowest level system calls.
For Windows, I have found the functions... | On linux, malloc and free are not system calls. malloc/free obtains memory from the kernel by extending and shrinking(if it can) the data segment using the brk system calls as well as obtaining anonymous memory with mmap - and malloc manages memory within those regions. Some basic information any many great references... |
3,358,175 | 3,358,451 | C++ Reference for Programmer Returning from Java | Here's my situation: I taught myself C++ (albeit rather badly), and was later taught how to use Java in college. Returning to C++, I find myself confused by several things that differ from C++ to Java, for example memory management and avoiding memory leaks.
What would be the best mode of returning to programming in C+... | If you never properly learned C++ (you say you learned it "badly"), start over. Forget everything about Java, because trying to use Java idioms and techniques in C++ is just a recipe for bugs and memory leaks and very inefficient code. The differences between the languages are fairly big.
So get a good book teaching C+... |
3,358,322 | 3,358,357 | Iterate and erase elments from std::set | I have a std::set and I need to erase similar adjacent elements:
DnaSet::const_iterator next = dna_list.begin();
DnaSet::const_iterator actual = next;
++next;
while(next != dna_list.end()) // cycle over pairs, dna_list is the set
{
if (similar(*actual, *next))
{
Dna dna_temp(*actual); // copy construc... | Use actual = next rather than ++actual.
Once you erase actual, it is an invalid iterator, so ++actual will behave strangely. next should remain intact, so assigning actual to next should work.
|
3,358,733 | 3,360,015 | Conditionals in Visual Studio 2010 Project files | In a Visual Studio 2010 C++ project file, is it possible to use conditionals to determine the presence of a library, and alter preprocessor flags, etc appropriately?
To be more concrete, say we have a directory C:\libraries\MKL, i would like to #define MKL and add mkl_dll.lib as an additional dependency if that directo... | The following, when pasted into the bottom of an F# project, has the suggested effect (if c:\temp\foo.txt exists, then a #define for THE_FILE_EXISTS is added). I expect that only minor modifications would be needed for a C++ project, since they both use MSBuild. This is a little hacky maybe, it is the first thing I g... |
3,358,969 | 3,358,995 | Practical pointer usage in c++ | Most of my C++ programming experience has been projects for school. In that way, our usage of external libraries (ie boost) has been either prohibited or discouraged. Therefore we could not use smart pointers unless we wanted to write our own, which was usually beyond the scope of the projects. I'm just wondering in re... | On legacy code there's usually a lot of manual memory management. If someone hadn't take the time to refactor it you can find a lot of naked news and deletes, just happily waiting to leak somewhere.
I believe most recent, well written, software in C++ usually do use smart pointers, RAII, and so on. Manual memory manage... |
3,359,133 | 3,359,139 | Setting all array elements to an integer | I have an array,
int a[size];
I want to set all the array elements to 1
because some of the indexes in the array are already set to 1 so would it better checking each element using a conditional statement like,
for (int index = 0; index < size; index++)
{
if (a[index] != 1)
a[index] = 1;
}
or set all the ind... | Just set all the elements to 1. Code for simplicity and readability first. If you find that the code runs too slow, profile it to see where improvements need to be made (although I highly doubt performance problems can come from setting elements of an array of integers to a certain value).
|
3,359,608 | 3,359,979 | Looking for an elegant and efficient C++ matrix library | Greetings,
googling for that subject brings, e.g., MTL, exmat, LAPACK and also here. I also seem to remember that Microsoft Research released one, but can't put my hands on it.
I look for advice from someone who actually used (or developed...) one of those, hoping to achieve a Matlab experience inside C++ (as much as p... | Have a look at Armadillo, the docs have a syntax conversion table for Matlab users and there are benchmarks against other C++ matrix libraries in the website. I find it very user friendly.
|
3,359,627 | 3,359,781 | create file on desktop in c++ | I know that to create a file in c++ we use following code
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream out;
out.open("exemple.txt");
return 0;
}
My question is the following, I want to create example.txt file on desktop or in an other directory. To simplify it let's ta... | The main problem with your code is that the '\' is the escape character in C/C++.
So when you put the string: "C:\Users\David\Desktop" The slashes are escaping the next character and thus they are not actually part of the string and what the executable gets is "C:UsersDavidDesktop" to compensate for this there are tw... |
3,359,795 | 3,360,370 | Lockless reader/writer | I have some data that is both read and updated by multiple threads. Both reads and writes must be atomic. I was thinking of doing it like this:
// Values must be read and updated atomically
struct SValues
{
double a;
double b;
double c;
double d;
};
class Test
{
public:
Test()
{
m_pValu... | What you have written is essentially a spinlock. If you're going to do that, then you might as well just use a mutex, such as boost::mutex. If you really want a spinlock, use a system-provided one, or one from a library rather than writing your own.
Other possibilities include doing some form of copy-on-write. Store th... |
3,359,922 | 3,360,350 | SDL_WaitEvent: How to kill everything in queue? | I'm using this in my main loop:
if (SDL_WaitEvent(&event)) {
switch (event.type) {
case SDL_MOUSEBUTTONDOWN:
mainClicker(event.button.x, event.button.y);
break;
..... etc
Everything works fine, but:
In "screen 1" user does stuff and clicks a button. The app then does... | After you process the event to active the result screen, call this before processing the next event:
SDL_EventState(SDL_MOUSEBUTTONDOWN, SDL_IGNORE);
After the result screen has loaded, call:
SDL_EventState(SDL_MOUSEBUTTONDOWN, SDL_ENABLE);
|
3,359,954 | 3,359,982 | c++ convert class to boolean | With all of the fundamental types of C++, one can simply query:
if(varname)
and the type is converted to a boolean for evaluation. Is there any way to replicate this functionality in a user-defined class? One of my classes is identified by an integer, although it has a number of other members, and I'd like to be able ... | You can define a user-defined conversion operator. This must be a member function, e.g.:
class MyClass {
operator int() const
{ return your_number; }
// other fields
};
You can also implement operator bool. However, I would STRONGLY suggest against defining conversion operators to integer types (including bool)... |
3,360,129 | 3,368,201 | Getting value from two dimensional Safearray in C++ | Am relatively new to the world of C++. I wish to access the data from a multi-dimensional SAFEARRAY. However when I try to retrieve the value, I get the error 0xC0000005: Access violation reading location 0x40e3e300. Attached below is my code and the marked line is where it errors out. Hopefully someone can shed some l... | Guys, managed to resolve it. Nothing fancy but here it is.
SAFEARRAY *ArrayCrosstabInfo = GetMainFrame().m_epsComHelper->GetCrosstab(m_arrayFieldnames,start,end);
int lOffset = 2;
long index[2];
long lUBoundX;
long lUBoundY;
SafeArrayGetUBound(ArrayCrosstabInfo, 1, &lUBoundX);
SafeArrayGetUBound(ArrayC... |
3,360,478 | 3,360,537 | C++ reinterpret_cast | I don't know why this simple code is not working:
int main()
{
const char* c = "ret";
typedef unsigned char GOK_UINT8;
typedef GOK_UINT8* pGOK_UINT8;
const pGOK_UINT8 y = reinterpret_cast<const GOK_UINT8*>(c);
return 0;
}
Can someone tell me why the reinterpret_cast does not work?
|
Can someone tell me why the reinterpret_cast should not work?
AFAICS, the reinterpret_cast should work fine, but the assignment afterwards should cause an error.
That's because a const GOK_UINT8* is a non-const pointer to const GOK_UINT8 objects, while a const pGOK_UINT8 is a const pointer to non-const objects.
The ... |
3,360,548 | 3,370,017 | Console output in a Qt GUI app? | I have a Qt GUI application running on Windows that allows command-line options to be passed and under some circumstances I want to output a message to the console and then quit, for example:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
if (someCommandLineParam)
{
std::cout << "Hello, world... | Windows does not really support dual mode applications.
To see console output you need to create a console application
CONFIG += console
However, if you double click on the program to start the GUI mode version then you will get a console window appearing, which is probably not what you want. To prevent the console w... |
3,360,638 | 3,411,098 | What C++ string classes/systems exist that have good unicode support and a decent interface? | Using strings in C++ development is always a bit more complicated than in languages like Java or scripting languages. I think some of the complexity comes from a performance focus in C++ and some is just historical.
I know of the following major string systems and would like to find out if there are others and what spe... |
Using strings in C++ development is
always a bit more complicated than in
languages like Java or scripting
languages. I think some of the
complexity comes from a performance
focus in C++ and some is just
historical.
I'd say it's all historical. In particular, two pieces of history:
C was developed back ... |
3,360,828 | 3,360,862 | plugin pattern with .dll. how can I extract plugin interface from dll? | I have an application that's suppose to be realized in plugin pattern.
Plugins are located in dll files and I'm loading them on the fly, depending on the parameter given from a user via command line. That is, if user wants to use plugin1 he types that name as a parameter in command line when running the app and I am su... | You will have to store the interface definition in a common location (separate .h file in say \inc subdirectory) and you will have to recompile all the libraries once you change the interface. There's no way around that in C++. If you need the ability to uniquely indentify interfaces you can use something like COM and ... |
3,360,892 | 3,360,909 | Multiple Inheritance Template Class | class messageA {
};
class messageB {
};
template<class T>
class queue {
public:
virtual ~queue() {}
void submit(T& x) {}
};
class A : public queue<messageA>, public queue<messageB>
{
};
int main()
{
A aa;
aa.submit(messageA());
aa.submit(messageB());
}
My first thought is, the above code should... | I have no compiler right now, but I guess one inheritance could hide the other : The compiler will use Koenig Lookup to find the right symbol, and if I remember correctly, once the compiler find a suitable symbol (i.e., a method called "submit"), it will stop searching for others in parent and/or outer scopes.
In this ... |
3,360,915 | 6,515,684 | making a web services query using gSoap with query arguments | I'm attempting to convert a soap query written for C# into a gSoap query in Visual C++.
The C# query adds an XML node's to the query call, in order to pass parameters to the query:
XmlNode queryOpts = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
queryOpts.InnerXml = "<DateInUtc>TRUE</DateInUtc>";
Here's... | I'm assuming you've already discovered the answer to this, but I'll post some notes for posterity.
Here's a simple C++ demo for sending and XML doc to a ASP.NET web method.
int _tmain(int argc, _TCHAR* argv[])
{
Service1SoapProxy proxy;
_WebServiceNS1__HelloWorld helloWorld;
_WebServiceNS1__HelloWorld_xml ... |
3,361,049 | 3,361,108 | QT and SQLITE problem during building | I'm developing a simple application to use sqlite, the problem is that the following code
/*
...
*/
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("hellogoodbye");
if (!db.open()) {
QMessageBox::critical(0, qApp->tr("Impossibile aprire il database"),
... | Did you add QT += sql to the project file ?
|
3,361,059 | 3,361,176 | How to get an accurate 1ms Timer Tick under WinXP | I try to call a function every 1 ms. The problem is, I like to do this with windows. So I tried the multimediatimer API.
Multimediatimer API
Source
idTimer = timeSetEvent(
1,
0,
TimerProc,
0,
TIME_PERIODIC|TIME_CALLBACK_FUNCTION );
My result was that most of the time the 1 ms was ok, but... | Without going to a real-time OS, you cannot expect to have your function called every 1 ms.
On Windows that is NOT a real-time OS (for Linux it is similar), a program that repeatedly read a current time with microsecond precision, and store consecutive differences in an histogram have a non-empty bin for >10 ms! This m... |
3,361,347 | 3,361,446 | Design for using all subclasses together in a container in C++ | I have just read an article about the Curiously Recurring Template Pattern. And you can use it simulate virtual functions with templates.
For example:
template<class T>
struct A
{
void func() { static_cast<T*>(this)->func(); }
};
struct B : public A<B>
{
void func() { cout << "B" << endl; }
};`
However, if we... | You could do this:
class NonTemplateBase
{
};
template<class T>
struct A : public NonTemplateBase
{
void func() { static_cast<T*>(this)->func(); }
};
and then create a vector of pointers to NonTemplateBase (i.e. std::vector<NonTemplateBase *>).
However, I'm guessing you want to be able to call func() or other mem... |
3,361,365 | 3,361,393 | How do I keep a constant definition in a header file and not have it linked into every library? | Here's the scenario. We use Visual C++ 9. There's a C++ library intended to be used by many other libraries. Its interface is in a header:
#pragma once
//CommonLibraryHeader.h
CSomeClass GetSomeClassFunction(); //is defined in some .cpp file
const CSomeClass MagicValue( 100, 200 ); //some predefined value that the pre... | You could use the trick that is often used with DLL's that export classes and functions: use a #define that is defined only when the DLL you want to include the code in is built, but not defined in the others, and do an #if that either calls the constructor or defines it as extern, as appropriate.
|
3,361,405 | 3,361,555 | GUI with C++ ? or C# and Java the way to go? | I am nearly done with a course about using OOP in C++ and all the programs we wrote in that course were console applications . I also finished a university course in C programming so I think I have solid C programming basics and now is the time to make a big step towards GUI .
I did a lot of googling and each time I r... | The fastest way is to use C# and WPF. It's fast and simple for small applications but can be pretty complex in my opinion and there is a lot to learn. At least you are future proof, Microsoft is pushing WPF themselves finally. (Visual Studio uses it, and there will be a lot more versions to come)
The only real downside... |
3,361,514 | 3,361,523 | Comparing two Hexadecimal values in C++ | I want to compare two hexadecimal(stored in long)
below is my code
long constant = 80040e14;
if(constant == 80040e14)
cout<<"Success"<<endl;
else
cout<<"Fail!!"<<endl;
In this code flow control always returns to else part, can anyone please suggest how to proceed with the comparison.
Thanks
Santhosha K
| Prefix your constants with '0x'.
Your constant only has 'e' in it and the compiler will treat numbers of the form: NNNeEEE as scientific notation. Using the '0x' prefix tells the compiler that the following characters are in hexadecimal notation.
In your code, 80040e14 is 8004000000000000000 which is way too big to fit... |
3,361,678 | 3,362,636 | How can I optimize a calculation-intensive C++ program with a known bottleneck? | I am developing some scientific software for my university. It is being written in C++ on Windows (VS2008). The algorithm must calculate some values for a large number of matrix pairs, that is, at the core resides a loop iterating over the matrices, collecting some data, e.g.:
sumA = sumAsq = sumB = sumBsq = diffsum = ... | If you use the "pause" technique, it should tell you more than just that you're in that loop. It should tell you where in the loop.
Never guess when you can just find out. That said, here's my guess :-) You are doing all the summing in floating-point variables, but getting the original numbers as integer characters, ri... |
3,361,805 | 3,362,151 | C++ passing struct or object by value | I have this:
enum Units { Pounds, Kilos };
struct Configuration
{
const Units units;
const char *name;
inline Configuration(Units pUnits, char *pName) : units(pUnits)
{
name = strdup(pName);
}
inline ~Configuration() { free((void *)name); }
};
I was passing one of these to a method l... | You didn't provide your own copy constructor or assignment operator. So, when you make a copy or an assignment, the compiler-generated copy constructors and assignment operators are used which actually don't do the right thing in this case. They simply copy every member so you end up with two Configuration objects refe... |
3,361,926 | 3,362,171 | Why are cv-qualifiers in template parameters ignored? | I had some code that was failing to compile, which amounts to something
like what's shown below. After some digging around, I came across
paragraph 14.1 note 5, which states:
The top-level cv-qualifiers on the template-parameter are ignored
when determining its type.
My code looks like this:
#include <iostrea... | The problem with your code is that the function call is ambiguous. The const Bar & can match either the value or the const reference. G++ says:
xx.cpp:24: error: call of overloaded 'Func(const Bar&)' is ambiguous
This has nothing specifically to do with templates - you would get the same error if you overloaded a non-... |
3,362,254 | 3,362,568 | C/C++ optimization: negate doubles fast | I need to negate very large number of doubles quickly. If bit_generator generates 0, then the sign must be changed. If bit_generator generates 1, then nothing happens. The loop is run many times over and bit_generator is extremely fast. On my platform case 2 is noticeably faster than case 1. Looks like my CPU doesn't ... | Unless you want to resize the vector in the loop, lift the v.size() out of the for expression, i.e.
const unsigned SZ=v.size();
for (size_t i=0; i<SZ; ++i)
if (bit_generator()==0)
v[i] = -v[i];
If the compiler can't see what happens in bit_generator(), then it might be very hard for the compiler to prove t... |
3,362,860 | 3,362,944 | convert NTP time to Human-readable time | i have managed to make a NTP request and retrieve the server time from it's NTP response.
i want to convert this number to a Human-readable time, writing in C++.
can some one help me ?
as example you can look at:
http://www.4webhelp.net/us/timestamp.php?action=stamp&stamp=771554255&timezone=0
once you set the timestamp... | It's not C++, but here's a perl implementation. Converting this into C++ should be no big deal:
http://www.ntp.org/ntpfaq/NTP-s-related.htm#AEN6780
# usage: perl n2u.pl timestamp
# timestamp is either decimal: [0-9]+.?[0-9]*
# or hex: (0x)?[0-9]+.?(0x)?[0-9]*
# Seconds between 1900-01-01 and 1970-01-01
my $NTP2UNIX =... |
3,362,895 | 9,417,542 | Visual Studio application running extremely slow with debug | I have a native C++ program which runs more than 20 times slower when started with Debug (F5), but runs at normal speed when using start without debug (Ctrl + F5).
It does not matter whether I use a debug or release build. Also if I use WinDbg the program is a magnitude slower.
Is there some setting I did choose wrong ... | Set the _NO_DEBUG_HEAP environment variable to 1 (as seen on http://preshing.com/20110717/the-windows-heap-is-slow-when-launched-from-the-debugger).
This can be done from inside Visual Studio, too.
Now this is just a workaround, and I'm curious to know how to refactor a program which suffers from this kind of problem. ... |
3,362,919 | 3,363,599 | using stat to detect whether a file exists (slow?) | I'm using code like the following to check whether a file has been created before continuing, thing is the file is showing up in the file browser much before it is being detected by stat... is there a problem with doing this?
//... do something
struct stat buf;
while(stat("myfile.txt", &buf))
sleep(1);
//... do so... | The "stat" system call is collecting different information about the file, such as, for example, a number of hard links pointing to it or its "inode" number. You might want to look at the "access" system call which you can use to perform existence check only by specifying "F_OK" flag in "mode".
There is, however, a lit... |
3,362,983 | 3,365,215 | Why might HttpOpenRequest fail with error 122? | The following code
fRequestHandle = HttpOpenRequestA(
fConnectHandle,
"POST", url.c_str(),
NULL, NULL, NULL,
INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE,
0);
is returning NULL with GetLastError() returning 122. A s... | In general, your url should be 2k or less in size. Since you are performing a POST, you are heading in the right direction, its just that for the bulk of your data, you want to pass that as the body of the HTTP request like in this example:
POST /login.jsp HTTP/1.1
Host: www.mysite.com
User-Agent: Mozilla/4.0
Content-... |
3,363,121 | 3,363,150 | how to declare templated map::iterator within a templated class. following code Says ; expected when compiled | the following code says
error: expected ‘;’ before ‘forwit’
error: expected ‘;’ before ‘revit’
template<class T>
class mapping {
public:
map<T,int> forw;
map<int,T> rev;
int curr;
//typeof(forw)::iterator temp;
map<T,int>::iterator forwit;
map<int,T>::iterator revit;
};
// }; // JVC: Th... | To help the compiler understand you are talking about a type in a templated context, you have to help it writing typename.
In your case
typename map<T,int>::iterator forwit;
|
3,363,289 | 3,363,310 | modulus operator in c++ driving me mad | my names joe and im running into a few issues with the modulus in c++
heres the problem:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//In short, this is what i am trying to do:
//divide two numbers, and get both the quotient
//and the remainder
//however, as an example, this below produces... | I get the correct answer...
The quotient is 5 and the remainder is 10
Press any key to continue . . .
I think the bug is probably located between the keyboard and the chair ... =P
|
3,363,398 | 48,523,639 | g++ linking order dependency when linking c code to c++ code | Prior to today I had always believed that the order that objects and libraries were passed to g++ during the linking stage was unimportant. Then, today, I tried to link from c++ code to c code. I wrapped all the C headers in an extern "C" block but the linker still had difficulties finding symbols which I knew were in ... | You can use --start-group archives --end-group
and write the 2 dependent libraries instead of archives:
gcc main.o -L. -Wl,--start-group -lobj_A -lobj_b -Wl,--end-group
|
3,363,592 | 3,363,773 | Update program by writing to the currently executing file | I am writing a c++ program which sooner or later will need to be updated. I want this to require as little interaction with the user as possible since the program runs constantly in the background and never terminates. I know that under normal circumstances, you can't write to a file that's being executed, so this is m... | Most programs using auto-update features use another executable to take over execution in order to avoid that problem.
However I see a somewhat simple solution:
old program downloads new program into a temporary location
old program starts new program (possibly with a special parameter) and terminates itself
new progr... |
3,363,714 | 3,363,738 | Cost of passing variables to functions | I am unsure about how function calls are translated and I am afraid that passed variables are copied into local variables when they don't need to be. I could avoid unnecessary copying by using global variables, but that cannot be a good solution...
1) When variables are not changed in the target function, would it be b... | Don't worry about the performance issues at this point.
Focus on the algorithmic cost of your function, not the trivial things: guessing performance issues is a bad idea.
If you really encounter performance issues and have maintainable code, it will still be time to improve it.
Now to really answer the question:
You ma... |
3,363,789 | 3,363,829 | question about reinterpret_cast | i have following code
#include <iostream>
using namespace std;
int main(){
int i;
char *p="this is a string";
i=reinterpret_cast<int>(p);
cout<<i<<"\n":
return 0;
}
output is:
7648
please explain reinterpret_cast
| reinterpret_cast<> here will convert without checking the p pointer to an int but you can't make any assumption what this int would represent. The only thing you can do, is convert this pointer back to what it was.
On a more practical note, it is likely that your compiler will put the address p points to into the int v... |
3,364,193 | 3,364,271 | Using RAII with C++ streams and STL containers? | I'm trying to use RAII concepts with an STL container of ofstream objects. For example:
int main(int argc, char**argv)
{
std::deque<std::ofstream> sList;
sList.push_back(std::ofstream()); // tried variations such as *(new ofstream())
sList[0].open("test1.txt");
sList[0] << "This is a test";
sList[0].close()... | In the interest of keeping a file from being written to in multiple places in various parts of the system, streams are noncopyable. A smart pointer is probably the way to go here.
|
3,364,290 | 3,364,373 | Hash Map with Two keys - Finding all elements linked to one key. C++ | I have an object Line which contains 2 objects of type Point called Point1 and Point2. I want to create a HashMap containing lines and whose keys are std::pair<Point1, Point2>.
What I'd like to do is find all the Lines with are referenced (for instance) by Point1, i.e. with key std::pair<Point1, Anything>. I don't care... | It sounds like what you really want is an std::multimap (or std::unordered_multimap), with individual points as the keys, and lines (pair<point, point>) as the associated values. Alternatively, since the key holds the first point, you this could be done as a std::multimap<point, point>, to avoid storing Point1 twice, o... |
3,364,554 | 3,364,576 | Can this be done with OpenGL? | I'm making a vector drawing application with OpenGL. Is there a way to implement a clipping mask? Ex: if I have Circle A and Circle B, I only want to see the part of circle B which intersects into Circle A's space. Is there a way to do this that isn't very expensif, I do not want to kill my application. Thanks
| Jex,
A quick google search for "clipping mask in openGL" had this as the first result.
|
3,364,589 | 3,364,620 | Find what directory the running process EXE is stored in |
Possible Duplicate:
How to get the application executable name in Windows (C++ Win32 or C++/CLI)?
I can find what directory the process is running in using GetCurrentDirectory(), but what about finding the directory the executabke resides in?
| GetModuleFileName or GetModuleFileNameEx.
|
3,364,722 | 3,365,221 | Accessing protected member of template parameter | I have a template class for which I need to access a protected member function of the template parameter, like this:
class Foo
{
protected:
void foo() {}
};
template<typename T>
class Bar
{
public:
static void bar(T& self){self.foo();}
};
...
Foo f;
Bar<Foo>::bar(f);
My problem is getting access to the protec... | OK, this is a "rot in hell" hack. You can abuse the fact that you can form pointers-to-members pointing to protected base members from a derived class.
class Foo
{
protected:
void foo() {}
};
// Helper template to bypass protected access control
// for a member function called foo, taking no parameters
// and retu... |
3,364,932 | 3,365,125 | Is there a way to send a CString to a CFile without writing an actual file? | I have data stored in a CString and it needs to be parsed by an XML parser library. The problem is the XML parser takes in a CFile. It's not ideal to write out the CString to a text file and then reload it into a CFile. Is there any way to directly send the CString to the CFile without making an intermediate output fil... | You should be able to use CMemFile to accomplish this. It inherits from CFile and allows you to specify an arbitrary buffer for data. The following sample code should work:
CString strData;
CMemFile memFile( (BYTE*)strData.GetBuffer() , (strData.GetLength() + 1) * sizeof(TCHAR) );
//Do something with memFile
strData.... |
3,364,939 | 3,367,330 | Subtractive blending with OpenGL? | I would like to for example draw shapes A, B, C then set the blender, then draw shape D and everywhere where shape D is, the scene shows my background color of (1,1,1,0). Thanks
| Much simpler than other answers :
Display shapes A, B and C the normal way
glDisable(GL_DEPTH_TEST);
glDisable(GL_ALPHA_TEST);
glDisable(GL_BLEND);
Display shape D with color (1,1,1,0)
and you're done.
|
3,364,964 | 3,423,594 | Regarding Hardware Access using C++ and VB.net | I currently have basic knowledge of C++ and VB.Net.
For our college project i plan to do something related to Accessing Hardware.
I would like to know about some Libraries and functions that can be used to access the monitor and hard disk (Master Boot Record actually) using:
C++
VB.Net
| Got the Answer for C++ using WIN APIs and call these programs in VB
|
3,365,182 | 3,365,259 | how to search the computer for files and folders | i need a way to search the computer for files like Windows Explorer. i want my program to search lets say hard drive c:. i need it to search C:\ for folders and files (just the ones you could see in c:\ then if the user clicks on a file on the list like the folder test (C:\test) it would search test and let the user se... | Since you mentioned windows, the most straight forward winapi way to do it is with FindFirstFile and FindNextFile functions.
edit: Here's an example that shows you how to enumerate all files/folders in a directory.
#include <Windows.h>
#include <iostream>
int main()
{
WIN32_FIND_DATA file;
HANDLE search_handl... |
3,365,269 | 3,367,546 | Method to quickly set up event forward in wxWidgets? | I am developing a GUI that has a canvas and a bunch of controls and crap surrounding it. I want to allow the canvas's event handler a chance to handle events like key presses and such when it doesn't have focus. I want the rest to continue working as normal.
Basically what I want to set up is to tell the frame, "Any ... | You can use the ProcessEvent method.
On the event handlers you want to forward, add
/* Let the canvas process this event too */
canvas->ProcessEvent(aEvent);
where "canvas" is a static global pointer to your canvas, and "aEvent" is the event object received by your handler.
This way you can even simulate events! That... |
3,365,340 | 3,365,406 | Is wrapping STL idioms for readability a good idea? | I'm currently working on a C++ project that needs to have as few external dependencies as possible, and thus I'm pretty much sticking to STL and Boost. Until now, I've been almost exclusively living in Qt-land when it comes to C++. In general I tend to use C# and Python when I can.
Today I wanted to check whether a std... | There is nothing wrong in writing the utility functions that will help you and will make your code cleaner. Other people do the same. Boost library is the biggest set of such utility functions and classes.
More to say C++ Standard explicitly proposes to extend the Standard Library (17.3.1.2/1):
The library can be exte... |
3,365,376 | 3,365,684 | QtSql: QSqlRecord doesn't keep the table prefixes | I'm working on a small application in Qt and I'm using the SQL library together with SQLite as the database. So far this has worked out well. The QSqlQuery class only provides a method for getting column values by index instead of field name. However, using the record() function the current row on the query can be turn... | The field name is totally dependent on the driver; so the issue is really with SQLite itself, which might be doing the 'correct' thing after all (correct, as in SQL standards, which I haven't checked).
Anyway, easy solution: just give your fields an alias in the SQL itself, though, you can't, and really shouldn't, use ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.