question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
5,179,553 | 5,179,603 | Initialization of references | I wrote the following code, and I was expecting to get
5
6
6
6, but I got 5 6 5 0 instead. It seems that "val" gets the reference correctly in the beginning, but then it gets lost. Does anybody know where is my mistake?
class Count {
public:
void add() {
val++;
}
void print() {
cout << va... | Your constructor should take the parameter by reference, not by value.
|
5,179,570 | 5,179,604 | Find index of an element in a vector given a pointer to that element | I have a vector of structs, like so: std::vector<mystruct> elems.
If I then have a mystruct pointer, which I know is pointing to one of the elements of elems, how can I get its index within elems?
| ptr - &elems[0];
As of C++03, vector storage is required to be contiguous, and the definition of "contiguous" in the standard is that &v[n] == &v[0] + n;
[Edit: from a fairly theoretical portability point of view, beware that implementations are permitted to define SIZE_MAX and ptrdiff_t such that it's possible to subt... |
5,179,770 | 5,179,808 | C++ multiplatform library to playback /record audio (.wav, .ogg) | I have a multiplatform application and want to add audio annotations functionality.
I am looking for audio playback /recording library that is:
multiplatform (Windows, Linux, Mac)
simple and fast to integrate into existing project
do not use cygwin for Windows build
has C++ bindings
I saw gstreamer but I have the fee... | Did you look into SDL? That should be able to play OGG files and WAV files.
|
5,179,854 | 5,179,973 | Virtual inheritance in C++ | I found this in a website while reading about virtual inheritance in c++
When multiple inheritance is used, it is sometimes necessary to use virtual inheritance. A good example for this is the standard iostream class hierarchy:
//Note: this is a simplified description of iostream classes
class ostream: virtual public... | Basically, if virtual inheritance is not used, base members are actually part of derived class instances. Memory for the base members is allocated in each instance, and no further indirection is necessary to access them:
class Base {
public:
int base_member;
};
class Derived: public Base {
public:
int derived_... |
5,179,906 | 5,180,707 | Embedding Mono vs Google V8? | We want to add scripting to a project.
We are hesitating which script engine to use.
I have used in the past V8 and it's quite impressive. I have used Mono as well but in toy-projects or prototypes only.
The constraints are :
speed of execution.
easy integration.
must work on windows.
64-bit support.
compiles under ... | There is an MSVS solution file included into Mono distribution, it is enough for building a library (but you won't be able to build .DLLs, better pick them from a binary distribution). See mkbundle for a way to embed .NET DLLs into a single binary. As for scripting itself, you can either embed Mono C# compiler (it is n... |
5,179,927 | 5,179,997 | Help with copying an object in C++ mfc | i have this code which doesnt work:
void CAnalyzerIF::SetData(int i_iIters, const CParameterSet* i_CParameterSet)
{
const CParameterSet ParameterSet=(*i_CParameterSet); //thous are the problem
const CParameterSet* pCParameterSet=&ParameterSet; //lines
// ... now im sending the pCParameterSet to other class
}... | If you need to clone the i_CParametreSet you need:
The class CParamterSet declaring a
"copy constructor"
Copy the instance data by hand (
probably does not works due to
protected private members )
You should also pay attention on the class content and decide if you need a Shallow Copy or a Deep Copy of the class i... |
5,179,966 | 5,179,998 | Cannot pass a pointer to a function | I have removed all the unwanted segments. I am trying to pass pointers to an overloaded operator and use templates too. But this is still not working.
#include<iostream.h>
#include<conio.h>
class Test{
private:
int a;
public:
Test (){}
Test(int k){
a=k... | Firstly, t1 is a pointer, and you are calling the add method incorrectly - should be t1->add(t2). Secondly, the sum() methods takes arguments which are not pointers, i.e. the template parameter is deduced as Test rather than Test*, hence you need to change the signature to something like:
template <typename T>
T* sum(T... |
5,180,034 | 5,180,061 | boost::variant and printing methods of elements in vector | std::vector< boost::variant<std::string, int> > vec;
std::string s1("abacus");
int i1 = 42;
vec.push_back(s1);
vec.push_back(i1);
std::cout << vec.at(0).size() << "\n";
when I try to run this code, I get the following error:
main.cpp:68: error: ‘class boost::variant<std::basic_string<char, std::char_traits<char>... |
being a string it should have a size() method
It’s not a string – it’s a variant. You first need to tell the compiler that you know there’s a string inside – i.e. retrieve it using boost::get<std::string>(vec[0]).
Be sure to read the Boost.Variant tutorial.
|
5,180,208 | 5,180,392 | Does the VS2008 C++ optimizer sometimes produce slower code? | Following on from a previous question, I've been playing around with optimizer settings in my release build to see what benefits are to be gleaned from using compiler optimization. Up until now, I've been using /Ob1 (only inline where inline is explicitly given), and /Oi (Enable intrinsic functions). I tried changing... | The documentation for /Ot states:
If you use /Os or /Ot, then you must also specify /Og to optimize the code.
So you might want to always pass /Og with /Ot in your tests.
That said, /Ot favors fast code at the expense of program size, and can produce very large binaries, especially with heavy inlining. Large binaries... |
5,180,357 | 5,180,417 | Why do C++ template definitions need to be in the header? |
Possible Duplicate:
Why should the implementation and the declaration of a template class be in the same header file?
e.g when defining a template class why do the implementations of the class methods need to be in the header? Why can't they be in a implementation file (cpp/cxx)?
| A template class is not a class, it's a template that can be used to create a class. When you instantiate such a class, e.g. MyTemplate<int>, the compiler creates the class on the spot. In order to create it, it has to see all the templated member functions (so that it can use the templates to create actual member func... |
5,180,437 | 5,180,769 | Subclassing Button Control within a Class | I created my own custom GUI button class for use in Windows Mobile apps. Realizing that I needed some finer control and to remove the double-click annoyance, I figured all I need to do is subclass it like I always have.
But, being that I have encapsulated everything into a Class though, seems to have complicated the m... | You're trying to pass a member function to an outside entity to call it, and that's impossible.
Try to imagine that someone is calling CallWindowProc(MyEditHandle, ...). On which object (instance) of CButtonUXnav should Button_WndProc operate on? What would be its this pointer?
If you really want to have the callback f... |
5,180,675 | 5,180,721 | Cause for this difference..from C++ to C? | i wonder why is this happening all the time...!!
I wrote two programs one in c and the other in c++.. Both performs the same action. i.e prints numbers from 1 to 2000000. Also i am setting the timer at the begtinning of execution.. and after printing all the numbers time elapsed is also printed..
The time elapsed for ... | The difference between the two programs is that the C++ version uses endl, which not only inserts a newline but flushes the buffer. The slow part of doing any output is flushing the buffer.
Both programs would probably be about the same speed if you made your C++ program use
count << i << "\n";
The following two prog... |
5,180,914 | 5,182,255 | llvm ir back to human-readable source language? | Is there an easy way of going from llvm ir to working source code?
Specifically, I'd like to start with some simple C++ code that merely modifies PODs (mainly arrays of ints, floats, etc), convert it to llvm ir, perform some simple analysis and translation on it and then convert it back into C++ code?
It don't really m... | There is an issue here... it might not be possible to easily represent the IR back into the language.
I mean, you'll probably be able to get some representation, but it might be less readable.
The issue is that the IR is not concerned with high-level semantic, and without it...
I'd rather advise you to learn to read th... |
5,181,145 | 5,710,733 | Test in a C++ static library project with NetBeans | I'm writing a static library in C++ with NetBeans (6.9.1).
I compiled the project main source files with no errors but I don't know how to add a test to it.
I chose File -> New -> C/C++ Tests -> C++ Simple Test and added the static library and the include directory to its properties but when I try to compile the test,... | I've been trying to get around this one for a while. Apparently it's a bug, due to be fixed by Netbeans 7.0. http://netbeans.org/bugzilla/show_bug.cgi?id=188854
|
5,181,183 | 5,181,270 | boost::shared_ptr and Inheritance | I am facing a situation in which I have a std::vector of boost::shared_ptrs of a base class. During the course of my program I need to store shared pointers to derived class objects in that vector too and at some time later in the program, need to retrieve those shared pointers.
Following code illustrates my problem:
#... | Use dynamic_pointer_cast
|
5,181,299 | 5,181,785 | Uniform Initialization Syntax in complex hierarchy construction? | I'm using GCC 4.4.5.
Here is the reproduction of my problem :
#include <vector>
class Test
{
public:
Test( int a, int b = 42 ) : m_a( a ), m_b( b ) {}
private:
int m_a;
int m_b;
};
typedef std::vector<Test> TestList;
class TestMaster
{
public:
TestMaster( TestList tests = TestList() ) : m_te... | You've got too many levels of construction going on. Initializer lists only work at one level, so you need to tell it that you want the list to apply to the TestList parameter of TestMaster:
TestMaster test_master(TestList({42,54,94}))
and then the same in the constructor of TestManager:
TestManager()
: TestMaster... |
5,181,356 | 5,181,427 | Call C++ programs from C# /WPF | Can someone point me to a full example of how to run compiled C++ programs (executables) from C#.
Thanks in advance.
| I think that what you want is like that:
Process myProcess = new Process();
try
{
myProcess.StartInfo.UseShellExecute = false;
// You can start any process; HelloWorld is a do-nothing example.
myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.... |
5,181,419 | 5,182,256 | Communication between applications | I have 3 choices to use : sockets, activeX, com , in order to communicate between applications on one computer. Which is faster ?
| As long as this runs on one machine, interprocess communication is fundamentally throttled by the bus bandwidth. A memory-to-memory copy, whether that's done in the TCP/IP stack, the named pipe support code or shared memory. Which makes them all equally efficient.
One detail matters though, the amount of data that's ... |
5,181,497 | 5,183,506 | QListWidget moving to end of list automatically | I have a QListWidget that has many items added to it, however i want the QListWidget to auto-scroll to the last item everytime a new item is added to it.Is this even possible?
| listWidget->scrollToBottom() would work
|
5,181,512 | 5,181,586 | pipe fork and execvp analogs in windows | This is simple demonstration of pipe fork exec trio using in unix.
#include <stdio.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
int outfd[2];
if(pipe(outfd)!=0)
{
exit(1);
}
pid_t pid = fork();
if(pid == 0)
{
//child
close(outfd... | fork() and execvp() have no direct equivalent in Windows. The combination of fork and exec would map to CreateProcess (or _spawnvp if you use MSVC). For the redirection, you need CreatePipe and DuplicateHandle, this is covered decently in this MSDN article
|
5,181,874 | 5,181,958 | Why aren't my "double" values printed the way I expected them? | Can I represent the following co-ordinate triplets using variable type "double"?
512685.93 5403444.22 305.63,
512685.91 5403445.72 305.55,
512685.90 5403447.12 305.54, ...
Those values correspond to x, y & z in my input file. After doing some process by my program, I got the output file with following values as:
51... | Look at how you print the values, likely the values are still fine but your output mechanism limits precision.
|
5,182,122 | 5,182,188 | Pointers to elements of STL containers | Given an STL container (you may also take boost::unordered_map and boost::multi_index_container into account) that is non-contiguous, is it guaranteed that the memory addresses of the elements inside the container never changes if no element is removed, (but new ones can be added)?
e.g.
class ABC { };
//
//...
//
std... | std::list, std::set, and std::map guarantee that the iterators (including simple pointers) will not be invalidated when a new element is added or even removed.
|
5,183,026 | 5,183,956 | Can I use my own message loop in windows? | I am building a C++ program, on windows, using Visual Studio. It relies on a COM base API, that sends windows message for notification.
To process those messages, I see two possibilities:
Create a windows form and call doModal on it which should process the messages, but since I don't want to use any UI, it's not what... | It is not just for your own benefit, COM requires you to create a message loop. COM needs it to handle apartment threaded COM servers, an expensive word for "components that don't support multi-threading". The vast majority of them don't.
It is best to create a window, it doesn't have to be visible. That gives you a... |
5,183,307 | 5,183,469 | c++ compile-time assertion | I'm using a macro that might be dangerous:
#define REMAINDER(v, size) ((v) & (size -1))
obviously it assumes that size is a power of 2.
I would like to make sure size is indeed a power of 2, but at compile time. (testing at run time is easy, but is NOT what I want).
A sufficient test for me would be that size is alway... | First things first: that micro optimization is not needed. Any decent compiler with optimizations enabled will convert a % b into that construct when b is a compile time constant that is actually a power of 2.
Then on the particular assert, you can use the same construct to assert it [*]:
BOOST_STATIC_ASSERT( !(size & ... |
5,183,703 | 5,184,306 | Why does declaring a "static const" member in a header file cause linker errors? | I have a class declaration(.h file) like so:
struct MyClass {
static const uint32_t SIZE = sizeof(MyType);
};
When linking my program together, I get linker errors for MyClass::SIZE. nm confirms that the symbol is undefined. http://forums.devshed.com/c-programming-42/linker-errors-undefined-reference-to-static-mem... | Your problem may have nothing to do with someone taking the address of your variable. It could simply be the compiler opting not to use the variable as a constant expression even though it could. For example:
f(int const&);
struct X { enum { enum_val = 42 }; static int const static_mem = 42; };
f(5);
f(X::enum_val);... |
5,184,209 | 5,184,275 | addition of 2x2 matrices with operator overloading | I have the following code.
The code works fine without the operator + part.
It gives me
error: no match for ‘operator=’ in ‘final[i][j] = (((matrix*)this)->matrix::mat[i][j] + matr->matrix::mat[i][j])’
and
error: no match for ‘operator<<’ in ‘std::cout << final[i][j]
#include <iostream>
#include <cstdio>
#include... | That's because matrix final[2][2]; declares a 2-d array of matrices, so final[i][j] is of type matrix & and the relevant operators aren't defined. You must have meant double final[2][2];
|
5,184,430 | 5,184,447 | Good books for Interpreter and Compiler using C++? | I'm planning to write a simple interpreter ( like TI-BASIC language for TI-89 ) or compiler ( C compiler ) using C++. I'm currently taking a course about programming languages, and learning the basic of BNF, EBNF. I wonder is it good enough to start on this project? In addition, could anyone know some good books about ... | The Dragon Book is a must read if you want to write a compiler.
|
5,184,459 | 5,184,634 | MSVC/Linux code for count_sprintf | I need function count_sprintf() that should return
number of characters (not inc nul byte) needed for the formatted buffer, on Win32 and on Linux.
int count_sprintf(const char *format, va_list ap);
There are subtle diffs beteen Win32 vs Linux in return value of vsnprintf when formatted value is longer than buffer size... | The VS runtime has the _vscprintf which counts characters needed.
int count_sprintf(const char *format, va_list ap) {
#ifdef WIN32
return _vscprintf(format, ap);
#else
char c;
return vsnprintf(&c, 1, format, ap);
#endif
}
|
5,184,538 | 5,184,673 | quick question about static function in c++ | static function in c++
SO, there can be only one instance of static function for this class. Right?
| In C++, a static member function is just like a normal, global function, except with respect to visibility of names:
The name of the function is qualified with the class name.
Like a friend function, a static member function has access to private and protected class members. Also like a friend function, however, it do... |
5,184,625 | 5,184,695 | in-memory cache design using OO concept | What is in-memory cache? I could not find much information on it from the Web.
In fact, I was asked to design a in-memory cache based on OO concept using C++, but just do not know how to start. Any suggestions would be appreciated.
| This depends on the context but generally, an in-memory cache stores some value so that it can be retrieved later, instead of creating a new object. This is most often used in conjunction with databases – or really any application where the construction / retrieval of an object is expensive.
For a simple memory cache, ... |
5,184,889 | 5,185,203 | How does the C++ linker know which .lib contains which functions? | For example in Boost. I set an include directory in MSVC++2010 to the Boost root directory and have an #include <boost/regex.hpp> in my source code. I set a library directory to boost\stage\lib but there are hundreds of files in there – several for each Boost library and these for boost::regex:
libboost_regex-vc100-s-... | The boost libraries use some dark magic to select the libraries to link from the headers and compiler options. I don't really know all the gory details, but you can take a look at the boost/config/auto_link.hpp header for extra information.
In particular, this seems to be an important piece of the puzzle:
# pragma com... |
5,184,927 | 5,184,938 | Double Pointer Question | I am trying to make a tree template that can have any number of children on each node. This is my code for an addChild function in the node class -
template<typename T>
void Tree<T>::Node::addChild(T& value) {
Node* temp = new Node(value, this); //second parameter is for parent
numOfChildren++;
children*[n... | Just use children[numOfChildren]. Or do it the right way with std::vector<Node *> children;
|
5,184,988 | 5,185,008 | Should I use URLDownloadToFile? | I am looking for the most simple way to download a file in C++ (on Windows).
URLDownloadToFile sounds great and does not require me to use curl or other fat libraries that I don't need - what are the requirements for this function? Which Windows's will it run on?
Thanks!
| http://msdn.microsoft.com/en-us/library/ms775123%28VS.85%29.aspx
The documentation is there for a reason.
E: Just glancing at the documentation, it requires a minimum of Internet Explorer 3.0 and Windows 95. Vanishingly few computers do not meet those requirements.
E: Here's a sample of how to use this function. You al... |
5,185,121 | 5,185,336 | gluUnproject on GL_Points or finding the depth coordinates from mouse coordinates | I have a scene consisting of a lot of points which I drew using
glBegin(GL_POINTS);
glVertex3f(x[i],y[i],z[i]); // the points are displayed properly ..
glEnd();
What I wish to do is to be able to click on one of the points on the scene using the mouse and get its 3-D coordinate.
I have seen other threads to use :
gl... | Unfortunately, it can't be done. Any point x,y point on the screen can refer to any point along a given ray in the scene.
Given that you're drawing points, you probably want to use select mode to select a specific point, and then determine the coordinates of that point.
|
5,185,330 | 5,185,414 | C++ standard template library vector question | Can someone explain in English what is going on here?
std::vector<Cat*> cats; //I get that cats is a vector of Cat objects
if (std::find(cats.begin(), cats.end(), morris) == cats.end()) {
cats.push_back(morris);
}
| @mlimber has already given one explanation.
I'd explain it a bit differently. In plain English, it's a way of taking something really simple:
std::set<Cat> cats;
cats.insert(morris);
and making it slower (linear instead of logarithmic) and considerably harder to read or understand.
Edit: In fairness, I suppose I sh... |
5,185,500 | 5,203,482 | Cross-compiling libraries for ARM device | I am experiencing some difficulties in deploying a sample application which uses Qt libraries to an ARM device. I compiled the libraries using the cross-compiler provided for my system, I copied the binaries to the device and I compiled with the same compiler a sample appliction. When I try to start it this is what I g... | As far as I can see, the first comment to my question was exactly the solution. The version of the library was the same but was not compatible. I moved that library to the device and everything worked.
|
5,185,502 | 5,185,544 | Template Factory Pattern in C++ | I am trying to make a factory that will have the type passed in, rather then having it hard coded for types. However, when I attempt to add the type to the factory inside of the types .cpp file, I will get a linker error. For example, he is a linker error I am currently getting.
1>RandomClass.obj : error LNK2019: unres... | Templated functions cannot have their definition and declaration separated from each other without export, which your compiler probably doesn't support. You need to move the TemplateFactory::AddType definition to the header.
|
5,185,608 | 5,202,032 | Recommended approaches for making my code swiggable? | I'm currently refactoring a Tcl plugin library written in C++. Originally the code was hand-written. A second library exists that does the same thing for Java.
The refactored library will be a single C++ library that can be used to create bindings to different languages.
My first tests with SWIG are promising. However,... | Any approach that means that the C++ library becomes less useful to the C++ user is not the ideal solution.
#ifdef SWIG in the middle of .hpp files: Muddies up your C++ with unnecessary cruft, so it's not ideal
SWIG Specific Interface: This is a viable option, but only makes sense if the code you want to expose to SWI... |
5,185,747 | 5,185,838 | Solving Memory Leaks Allocated via NEW Statement | Is there a way to keep track of unreleased memory blocks allocated via new statement? The unreleased memory information should be listed on application exit, containig filename and fileline. This way, it should be possible to quickly identify new statements causing memory leaks.
If I am correct, MFC has DEBUG_NEW defi... | The Visual Studio CRT has some functions that can help you find memory leaks in debug builds, read http://msdn.microsoft.com/en-us/library/e5ewb1h3%28v=vs.80%29.aspx for more information; there's a lot to take in.
It's also generally considered best practice to try to always use the shared_ptr class to manage your memo... |
5,185,773 | 5,185,978 | why its not safe to return value on function stack | I came across the following paragraph while reading bruce eckel..where he was trying to explain why its not safe for function to return value on stack
Now imagine what would happen if an ordinary function tried to return values on the stack
.you can,t touch any part of the stack that's above the return address,so th... | Suppose that you have the following call stack somewhere in your application:
Main routine
Function1's local variables
Function2's local variables <-- STACK POINTER
In this case main calls function1, and function1 calls function2.
Now suppose that function2 calls function3, and the return value of function3 is return... |
5,185,829 | 5,185,916 | c++ std::list sort preserve order |
Possible Duplicate:
Is std::list<>::sort stable?
Does C++ std::list sort function is guaranteed to preserve the order of equal elements in the list? E.g. if we have objects A, B and C in the list and the comparison operators are overloaded so that A == C and B < A, will we necessarily get B-A-C or is it possible to ... | Yes, in C++ list::sort() is stable, per ISO 14882:2003 23.2.2.4[lib.list.ops]/31
Effects: Sorts the list according to the operator< or a Compare function object.
Notes: Stable: the relative order of the equivalent elements is preserved.
If an exception is thrown the order of the elements in the list is indeterminate.
... |
5,185,833 | 5,185,870 | C++ multiple declarations in a local scope | As far as I know, in C++ one can declare the same name multiple times, as far as it has the same type in all these declarations. To declare an object of type int, but NOT define it, the extern keyword is used. So the following should be correct and compile without errors:
extern int x;
extern int x; // OK, still declar... | An extern declaration declares something to have external linkage (meaning the definition is expected to appear at file scope in some compilation unit, possibly the current one). Local variables cannot have external linkage, so the compiler complains that you're trying to do something contradictory.
|
5,186,063 | 5,186,276 | C++ iterating through a set | I recently changed some code to use a set instead of a vector:
std::set<b2Body *>toDestroy;
//std::vector<b2Body *>toDestroy;
But now I'm not sure how to iterate the set to find objects. This is what I had:
std::vector<b2Body *>::iterator pos2;
for(pos2 = toDestroy.begin(); pos2 != toDestroy.end(); ++pos2) {
... | You need to declare your iterator to be a set iterator:
Change
std::vector<b2Body *>::iterator pos2;
to
std::set<b2Body *>::iterator pos2;
|
5,186,068 | 5,186,352 | Looking for an ActiveX Component capable of rendering PNG’s transparency and translucency | I need a component or some way to render PNGs on my application in order to improve its design. I believe somewhere some control should exist, but I did not find it.
I am developing on Visual Dataflex, and all I can use is Windows' API and COM-based components.I do not have GDI+, which makes use of C++ classes.
If no f... | The libpng site has a full list of implementation:
Programming Libraries and Toolkits with PNG Support
This one looks interesting (open source, win32 support): http://www.paintlib.de/paintlib/ (untested). It's not maitained anymore but source is included, and there are not many reason to face big issues today if it use... |
5,186,227 | 5,186,771 | C++ CLR loading .net 4.0 dll when .net 4.0 is not installed | I have an application, written on c++ and compiled with VS 2010.
I need to load .net dll written on C# and compiled for .net 4.0 platform from c++ code and call some functions. I have already done this through C++ CLR and its calling .net functions fine until .net 4.0 is not installed in the system.
When .net 4.0 is no... | 0xE0434F4D is the exception code for a managed exception. By the time you get that code it is already too late. The exception was unhandled, there's no live code left to interpret the exception. Improving error handling at such an early stage of the CLR booting up requires hosting the CLR yourself. Google CorBindTo... |
5,186,740 | 5,186,819 | Is there a difference between i++ and ++i |
Possible Duplicate:
What is more efficient i++ or ++i?
No difference between these:i++;
++i;
But when using them like this:anArray[ i++ ] = 0;
anArray[ ++i ] = 0;
Is there a difference?
TO BE EDITED:
Thanks
| Yes! Big difference!
i++ increments i after the line of code is executed expression is evaluated. ++i increments it before. For example:
int i = 2;
printf("%i\n", i++); //prints "2"
printf("%i\n", i); //prints "3"
Compare with:
int i = 2;
printf("%i\n", ++i); //prints "3"
printf("%i\n", i); //prints "3"
And I'... |
5,186,787 | 5,188,088 | Switch every pair of words in a string (“ab cd ef gh ijk” becomes “cd ab gh ef ijk”) in c/c++ | Switch every pair of words in a string (“ab cd ef gh ijk” becomes “cd ab gh ef ijk”) in c++ without any library function.
int main(){
char s[]="h1 h2 h3 h4";//sample input
switch_pair(s);
std::cout<<s;
return 0;
}
char * switch_pair(char *s){
char * pos = s;
char * ptr = s;
int sp = 0;//counts number of space
whil... | int Groups = 1; // Count 1 for the first group of letters
for ( int Loop1 = 0; Loop1 < strlen(String); Loop1++)
if (String[Loop1] == ' ') // Any extra groups are delimited by space
Groups += 1;
int* GroupPositions = new int[Groups]; // Stores the positions
for ( int Loop2 = 0, Position = 0; Loop2 < strlen(String... |
5,186,815 | 5,186,905 | memory leak when deleting derived class with base-class pointer | I have an issue with a memory leak. I have a base-class pointer. From it, I use new to allocate different derived classes. Then, when I try to delete those classes with the reference (not typecasted), I get a memory leak. I researched the problem and found that I should add a virtual destructor to the base-class, but I... | use virtual ~A();
I'd be surprised if virtual ~A()=0 is allowed.
With this code:
A* base = new B();
delete base;
the destructor for B then A will be called.
If you're really still leaking memory, then you have another leak elsewhere.
|
5,186,846 | 5,186,894 | How can I do clipboard-like operations without using the real clipboard? | I am looking to write a program (in Delphi or C++) to protect my passwords, and I would like to be able to copy and paste them. Is it possible to copy and paste, per se, without the data going to the clipboard, sort of my own custom clipboard?
I want to be able pull the password from an encrypted database and post it t... | You can inject keyboard keystrokes into other applications without using the clipboard. But then you would not be using Ctrl+C/Ctrl+V or Ctrl+Insert/Shift+Insert as your hotkey.
Maybe you want another global hotkey (yes you can do that) that will find the currently focused window, and send keystrokes to it. You can d... |
5,186,935 | 5,187,017 | C++ typedef in a class | I use this C++ code for storing x to the variable val.
class Hello
{
int val;
public:
Hello(int x) : val(x) {}
};
However, when I saw this code, I cannot see how Super can store value t or o.
template<typename T>
class K : public std::auto_ptr<T>
{
typedef std::auto_ptr<T> Super;
public:
K() : Super() { }... | Could've been written as
template<typename T>
class K : public std::auto_ptr<T>
{
public:
K() : std::auto_ptr<T>() { }
K(T* t) : std::auto_ptr<T>(t) { }
K(K<T>& o) : std::auto_ptr<T>(o) { }
};
Which is just more verbose to initialize the base class. A typedef is cleaner most of the time if you have to deal... |
5,186,961 | 5,188,168 | c++ ActiveMQ sending binary messages | Is it possible to send a stringstream containing binary over activemq? If so, how is this done?
I know the Java version of activemq has a feature called BlobMessage or StreamMessage to do so, however, this isn't implemented in the c++ version yet. I've already read about the BytesMessage class however I can't find any... | If you've downloaded the source for ActiveMQ-CPP then look for the Unit Tests in the the src/test folder that deal with BytesMessage, that will show you how its done. Also the StreamMessage is supported, BlobMessage is not though.
Here is the API Doc for BytesMessage in CMS.
http://activemq.apache.org/cms/api_docs/act... |
5,187,156 | 5,187,467 | C++: Static variable declarations in a function | Static variables exist outside of the function, in terms of their memory at least (not scope), right? But one thing that always concerned me, is what happens when I call the function a second time. For instance:
f(){
static char buffer[256*256];
stuff(buffer);
}
When I call this function a second time, would... | Static storage duration objects in function scope.
These objects are created on first use.
Then destroyed in reverse order of creation (with other static storage duration objects).
#include <iostream>
class X
{
public:
X(int x): m(x) {std::cout << "X: " << m << " created\n"; }
~X() ... |
5,187,168 | 5,382,008 | CMFCCaptionMenuButton alternative? | I need to create a caption bar button for a CDockablePane which will call up a menu with various options. I tried to use CMFCCaptionMenuButton and the button and menu show up but the message map methods for the menu ids don't fire. The MFC documentation states that CMFCCaptionMenuButton is meant for internal infrastr... | Now that the sound of crickets chirping has dwindled in the background I guess I'll post the workaround I currently have in place:
Instead of inheriting and extending CMFCCaptionMenuButton I build my class by extending CMFCCaptionButton. I then create a menu and provide a ShowMenu method to be explicitly called when h... |
5,187,193 | 5,187,340 | Available implementations of IEEE 754-2008 (Densely Packed Decimal) | What are the platform independent options for decimal numbers in c++?
| What exactly are your portability requirements? GCC and the IBM compilers have native support in the newest versions. Intel also has a library for several platforms.
|
5,187,219 | 5,187,276 | JNI: can't convert jstring to LPCTSTR? | The C++ side looks like this:
JNIEXPORT jint JNICALL Java_Myclass_showMessage (JNIEnv* env, jobject obj, jstring title, jstring message, jint type)
{
const char* _title = env->GetStringUTFChars(title, 0);
const char* _message = env->GetStringUTFChars(message, 0);
const int result = MessageBox(NULL, (LPCTSTR... | Use MessageBoxA - MessageBox autoselects the wide or mbcs version based on your projects Unicode/MBCS setting.
If you need to cast to LPCTSTR that's an indication something's wrong.
Alternatively, use GetStringChars and MessageBoxW, in this case you may need to cast depending on what jchar is defined as.
EDIT: Sample c... |
5,187,370 | 5,187,478 | Conversion of .txt into.dat | I have a txt(ascii) file but i wish to convert this file into binary (dat) file using c++ but i am very new in c++ programming.so I juct opend my 2 files:myBinaryfile and myTxtFile but I don't know how to write those data into new dat file.so i want to write a c+ codes that takes in an input containing ascii(.txt) file... | Google the following words: iostream, fstream, boost.serialization. Also, consider reading this question.
|
5,187,430 | 5,187,465 | C++ templates and Unsigned long problems | I am intending to make a constant Vector
const madness::Vector<double,3> kvec(0.0, 0.0, 1.0);
By calling the following code
template <typename T>
Vector<T,3> vec(T x, T y, T z) {
Vector<T,3> r; r[0] = x; r[1] = y; r[2] = z;
return r;
}
Unfortunately, I get an error which seems to say
extra.cc:216: error: no m... | is your Vector class template perhaps:
template<typename T, size_t N> class Vector ...
And is your size_t perhaps an unsigned long?
Also, I suspect you really meant:
const madness::Vector<double,3> kvec = vec(0.0, 0.0, 1.0);
|
5,187,692 | 5,187,727 | is there a pragmatic reason to use "if (0 == p) " instead of "if (!p)"? | I'm inclined to write if statements by using logical negation operator:
if (!p)
some_code();
Some people around me tend to use explicit comparison, so that the code looks like:
if (FOO == p)
some_code();
where FOO is one of false, FALSE, 0, 0.0, NULL, etc.
I prefer the short form because it is:
operator!= fr... | Some claim that the pragmatic benefit is that programmers will find it easier to understand if you explicitly compare against NULL, FALSE, 0, etc., whereas the logical operator may be confusing to people who don't understand how implicit conversions and booleans work in C/C++.
(Disclaimer: I don't share this view mysel... |
5,187,891 | 5,187,935 | Accessing variables with the same name at different scopes | With
#include <iostream>
using namespace std;
int a = 1;
int main()
{
int a = 2;
if(true)
{
int a = 3;
cout << a
<< " " << ::a // Can I access a = 2 here?
<< " " << ::a << endl;
}
cout << a << "... | No you can't, a (2) is hidden.
Ref: 3.3.7/1
A name can be hidden by an explicit
declaration of that same name in a
nested declarative region or derived
class (10.2).
Ref: 3.4.3/1
The name of a class or namespace
member can be referred to after the ::
scope resolution operator (5.1)
applied to a nested-na... |
5,187,925 | 5,188,352 | c++ boost serialization with stringstream | I am new to boost and c++ and is attempting to serialize an object to binary and then unserialize it.
I'm using the classes from the example in: http://en.highscore.de/cpp/boost/serialization.html
So suppose this is the class I am trying to serialize:
class person
{
public:
person() { }
person(int age) : age_... | Using binary archives with std::stringstream is allowed, as any character can be stored in a std::stringstream/std::string.
The problem is passing around the resulting data as a null terminated C-string, as binary data is highly likely to have embedded nulls thus upon load your data will be truncated. Additionally, you... |
5,187,927 | 5,188,116 | Recursion to create - nested () | I am trying to solve one of the "classic" dynamic programming problems. The problem is - Given a number as input , generate possible nested conditions.
Edit: as pointed out by temp below , i am going to first try and sort this out using recursion and then try with dynamic programming.
ie. if n = 3
O/p
((()))
()()()
(... | Right now, your solution doesn't take advantage of dynamic programming. If you want to use DP here, you'll need to think about the problem recursively. Fortunately, there's a great recursive formulation to this problem:
There is only one way to make balanced parentheses from no parentheses, which is to have no paren... |
5,187,997 | 5,188,069 | Waiting for another application window | What is the best way (with a view to optimization and using system resources) to make waiting in my application when window of another app will be shown?
For example:
My application starts.
Waiting while, for example,
Notepad will be started so i can get handle of its window.
Using handle im doing something with
it an... | If you launched the process (with CreateProcess) use WaitForInputIdle and then start the FindWindow loop. Adding a Sleep(20) or something to the loop will ensure your resource usage is minimal.
|
5,188,004 | 5,188,032 | question on variable type "double" | i have written a program and it works with 3D coordinates (i.e. x,y,z).
input data for my program was like
50903.85 21274.97 15.03
50903.57 21274.96 15.08
50903.33 21274.95 15.17
and i got the output with some more columns. So, i got the same x,y,z for my output file.
50903.85 21274.97 15.03
50903.57 21274.96 15.0... | Numbers aren't changing, you are just seeing a different notation change there. Perhaps you are using something other than %f to format your doubles? See printf format parameters.
Better yet, check out this StackOverflow question: How to avoid scientific notation for large numbers?
|
5,188,140 | 5,188,188 | C++: const char * to stringstream | Is it possible to put a const char* into a string stream?
I think it's possible with the write() function in stringstream but I'm having trouble figuring out how to get the streamsize if i only know of the const char *.
Assuming size is my const char * variable:
stringstream s;
s.write(temp,size);
How do I get size? ... | I tested it, and it works correctly...
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
stringstream s;
const char* token = "HELLO";
s << token;
cout << s.str() << endl;
return 0;
}
[facu@arch ~]$ g++ p.cpp
[facu@arch ~]$ ./a.out
HELLO
|
5,188,285 | 5,188,456 | C++ equivalent to Python's traceback library | I need to get some debugging libraries/tools to trace back the stack information print out to the stdout.
Python's traceback library can be an example.
What can be the C++ equivalent to Python's traceback library?
| This is platform-specific, and also depends on how you're compiling code. If you compile code with gcc using -fomit-frame-pointer it's very hard to get a useful backtrace, generally requiring heuristics. If you're using any libraries that use that flag you'll also run into problems--it's often used for heavily optimi... |
5,188,554 | 5,188,614 | My enum is not a class or namespace | Hi I have files called MyCode.h and MyCode.cpp
In MyCode.h I have declared
enum MyEnum {Something = 0, SomethingElse = 1};
class MyClass {
MyEnum enumInstance;
void Foo();
};
Then in MyCode.cpp:
#include "MyCode.h"
void MyClass::Foo() {
enumInstance = MyEnum::SomethingElse;
}
but when compiling with g++ I ge... | The syntax MyEnum::SomethingElse is a Microsoft extension. It happens to be one I like, but it's not Standard C++. enum values are added to the surrounding namespace:
// header
enum MyEnum {Something = 0, SomethingElse = 1};
class MyClass {
MyEnum enumInstance;
void Foo();
}
// implementation
#include "My... |
5,188,639 | 5,188,673 | Pointers to Incomplete Types | Consider the following:
class Incomplete;
class Complete
{
Incomplete* Foo; // Will only compile if Foo is a pointer.
};
class Incomplete
{
Complete Bar; // Bar can be a pointer or an object.
};
How are pointers to incomplete types legal? How does the compiler know how big an object of type Incomplete is? ... | The reason that pointers to incomplete types are legal is precisely because the compiler doesn't need to know their size.
The reason that you cannot declare an object of incomplete type is, as you've mentioned, because the compiler doesn't know how large the object is and therefore can't allocate space for it. When de... |
5,189,006 | 5,214,322 | DES Example invalid? | The practical example provided on the following web page, does it contain mistakes or is their some unique step that needs to be followed?
http://www.eventid.net/docs/desexample.asp#Example
The results from the 56-bit key does not match values in the permuted 56-bit key.
Following positions: 51, 43, 35, 27 (do no match... | Don't have that problem in my code with my issued question. So I consider it resolved.
My Key Schedule works like a charm.
|
5,189,049 | 5,189,190 | Game Object Factory: Fixing Memory Leaks | Dear all, this is going to be tough: I have created a game object factory that generates objects of my wish. However, I get memory leaks which I can not fix.
Memory leaks are generated by return new Object(); in the bottom part of the code sample.
static BaseObject * CreateObjectFunc()
{
return new Object();
}
Ho... | You can start by using std::shared_ptr or std::tr1::shared_ptr or boost::shared_ptr depending on your compiler.
You would use it like this:
typedef std::shared_ptr<BaseObject> BaseObjectPtr;
static BaseObjectPtr CreateObjectFunc()
{
return BaseObjectPtr(new Object());
}
You won't need to release the created resour... |
5,189,068 | 5,191,333 | Boost.Thread Assertion/Crash on Windows during win32::WaitForSingleObject | I have a rarely occurring issue in my code in which an assertion is triggered, involving the Boost.Thread library. I haven't been able to reproduce this issue using a stand-alone example, and I don't really know what is causing it, so it's hard to provide a sample case. I am hoping that anybody familiar with the intern... | I guess it will be very difficult to give a precise answer to your problem but it seems that you have a heap corruption problem, have you tried to use AppVerifier with normal pageheap enabled?
If you then attach a debugger to the process and have a heap corruption it will hopefully break when a corrupted heap block is... |
5,189,257 | 5,189,312 | sha1 function in cpp (C++) | Ill start by saying I dont know anything about c++ and I googled, there is nothing that can make me understand how to use SHA1 in C++. found this one though Objective C: SHA1 but its about objective c im not sure it is the same.
I need to do the following:
I habve a lot of files, i compile them by doing ./make.sh and ... | A good library for SHA1 and other functions is cryptopp.
Here is another question where the answer is cryptopp: Fast Cross-Platform C/C++ Hashing Library
|
5,189,614 | 5,189,659 | Operator << and inheritance | I have the following classes in C++:
class Event {
//...
friend ofstream& operator<<(ofstream& ofs, Event& e);
};
class SSHDFailureEvent: public Event {
//...
friend ofstream& operator<<(ofstream& ofs, SSHDFailureEvent& e);
};
The code I want to execute is:
main() {
Event *e = new SSHDFailu... | That would not work, as that would call operator<< for the base class.
You can define a virtual function print in base class and re-define it all derived class, and define operator<< only once as,
class Event {
virtual ofstream& print(ofstream & ofs) = 0 ; //pure virtual
friend ofstream& operator<<(ofst... |
5,189,952 | 5,199,974 | Killing Queued Notification Balloons (Pre-Vista) | I have a non-MFC, non-ATL C++ app that routinely creates notification balloons on a system tray icon. If, on pre-Vista boxes, the user locks the screen - these newly created "balloons are queued", which creates a mess when the user finally logs back in. There could be dozens or hundreds of balloons waiting. The timeo... | Regarding option (2) you need to register interest in 'SessionNotifications', using the function WTSRegisterSessionNotification:
WTSRegisterSessionNotification(HWND hWnd, DWORD dwFlags);
You pass in the handle to the window to receive the message WM_WTSSESSION_CHANGE, and use the flag NOTIFY_FOR_THIS_SESSION, which in... |
5,190,007 | 5,191,035 | Regarding mark-sweep ( lazy approach ) for garbage collection in C++? | I know reference counter technique but never heard of mark-sweep technique until today, when reading the book named "Concepts of programming language".
According to the book:
The original mark-sweep process of garbage collection operates as follow: The runtime system allocates storage cells as requested and disconnect... | There is one difficulty to using garbage collection in C++, it's to identify what is pointer and what is not.
If you can tweak a compiler to provide this information for each and every object type, then you're done, but if you cannot, then you need to use conservative approach: that is scanning the memory searching for... |
5,190,140 | 5,190,243 | assignment operator overloading skipped / not happening | I'm trying to create a library for some work and am using operator overloading for assignment operation.
Supposed X and Y are two instances of the class that has = overloaded thus:
A& A::operator=(A &rhs)
{
A::assign(*this, rhs);
return *this;
}
When I do this:
A z;
z = x + y; // x and y are other instances o... | If you declare a variable and initialize it on the same line, it will still call the copy constructor.
The are two initialization syntax:
X a;
X b(a);
X a;
X b = a;
There are slight differences as to what they mean, but in most cases they do the same. The difference is whether or not the compiler is guaranteed to avo... |
5,190,513 | 5,190,576 | PHP Style foreach loops in C++ | Is it possible to implement this using templates preferably in a way that would work with vectors and arrays, but especially vectors.
The main functionality, used in PHP as:
foreach(objects as object)
{ object=this*that; }
It would be nice to have the alternative usage as well if possible:
foreach(objects a... | C++0x supports range-based for:
for (T& object : objects)
object = this * that;
but not many compilers support this yet (only gcc 4.6 have it AFAIK). Still, you could use std::for_each with a lambda function like:
std::for_each(objects.begin(), objects.end(), [](T& object) {
object = this * that;
});
If you d... |
5,190,525 | 5,190,611 | Function Pointers vs calling cout directly | I'm working on a C++ class assignment and I'd like some input. I'm not looking for 'help' with my assignment as much as I use class assignments as an excuse to practice writing 'good' code, and I'm debating between two solutions to the current problem I'm working on.
I'm storing roughly 4000 values in an STL map. One o... | Short answer: don't worry about it. 4k indirect calls is not a big deal. If you're worried about performance, do the following:
code it up the easy way
performance good? done.
performance bad? use a profiler, like gprof, to find out why, then fix only what is is needed
Remember that 'premature optimization is the ro... |
5,190,841 | 5,190,909 | Should the include guards be unique even between namespaces? | I am using same class name in two namespaces, say A and B. Should the include guards be unique while declaring the classes with different namespaces too?
I mean can't there be two files names AFile.h (in different directories) with same include guards and declaring different namespaces?
//File 1:
#ifndef AFILE_H
... | Your guards need to be different if some code (directly or indirectly) needs to see both A::CAFile and B::CAfile.
The include guards are dealt with by the preprocessor, that has no knowledge at all of classes (let alone namespaces). If both these files are included when processing a c++ file, and they have the same hea... |
5,191,056 | 5,191,245 | PEG parser library on Windows OS | Are there any Parsing Expression Grammar (PEG) C++ libraries for Windows? I've tried in vain to compile pegc/legc, pegc with MS Visual Studio. :(
| I have had good luck with Boost.Spirit.Qi, which should work reasonably well with recent versions of the Microsoft compiler. Be forewarned, though: there is a learning curve.
If you just want a parser generator, also have a look at this related question: Is the ANTLR parser generator best for a C++ app with constraine... |
5,191,213 | 5,199,411 | Multiple lexers with flex++ | I am trying to link various Flex++ Lexers in the same executable. However, I get compile errors as a result because of symbol redefinition. I tried to set different prefixes but it was no use: These are my options:
Lexer1:
%option c++
%option noyywrap
%option yyclass="SendmailScanner"
%option prefix="zz"
Lexer2:
%opti... | Though I didn't test thoroughly, the redefinition error didn't occur when I
tested with simple files.
My flex's version is 2.5.35.
For your information, my test files are configured like the following:
Lexer1.h:
struct SendmailScanner : yyFlexLexer {
int yylex();
};
Lexer2.h:
struct SSHDFailureScanner : yyFlexLexer ... |
5,191,320 | 5,192,869 | What is the correct way to extend an existing ActiveX/COM component? | I am updating an MFC application that contains a custom ActiveX control. As a part of the update I have had cause to add new methods to the ActiveX control and so it now has a different interface to the old version. The changes had no impact on the original methods and so older clients can still use the new component.
... | Depends.
If you do have customers that are compiling their own code (C++ or C# or VB) against your controls's type library, .h file, or .idl file, you likely need to change the COM guids.
Here are the cases where you don't have to change the COM guids:
No 3rd party developers are consuming your code. No one would be ... |
5,191,436 | 5,191,461 | Creating two separate executables from a makefile (g++) | Currently, I have my makefile set up to compile and make a fairly large project. I have written a second cpp file with main function for running tests. I want these to run separately, but build together and they use the same files. How is this accomplished?
edit: As reference, here is my current makefile. I'm not s... | Normally you would just have multiple targets and do something like this:
.PHONY: all target tests
all: target tests
target: ...
...
tests: ...
...
Then you can just make (defaults to make all), or just make target or make tests as needed.
So for your makefile example above you might want to have something ... |
5,191,479 | 5,191,505 | Is there any situation where you wouldn't want include guards? | I know why include guards exist, and that #pragma once is not standard and thus not supported by all compilers etc.
My question is of a different kind:
Is there any sensible reason to ever not have them? I've yet to come across a situation where theoretically, there would be any benefit of not providing include guards ... | I've seen headers that generate code depending on macros defined before their inclusion. In this case it's sometimes wanted to define those macros to one (set of) value(s), include the header, redefine the macros, and include again.
Everybody who sees such agrees that it's ugly and best avoided, but sometimes (like if ... |
5,191,551 | 5,192,757 | Embedding MS.NET C# into c/c++ (like mono) | Is it possible to embed the MS C# compiler into an umanaged c/c++ host application and make both languages interoperate, very much like Mono does this (like here and here)?
I have a working implementation of this für my Qt based C++ Application using mono, but I'm limited (I really need the memory) by the 32bit constra... | Microsoft does support this; their term for it is hosting.
|
5,191,644 | 5,191,749 | Removing elements from a C++ map through a for-loop | My STL is a bit rusty, so forgive me for asking a possibly trivial question. Consider the following piece of code:
map<int,int> m;
...
for (auto itr = m.begin(); itr != m.end(); ++itr) {
if (itr->second == 0) {
m.erase(itr);
}
}
The question is: Is it safe to erase elements while looping over the map? ... | I think that you shouldn't use removed iterator at all - in case of lists this causes serious problems, shouldn't be different for maps.
EDIT by Matthieu M: this code is well-formed in C++0x and allowed as an extension by MSVC.
map<int,int> m;
...
auto itr = m.begin();
while (itr != m.end())
{
if (itr->second == 0)... |
5,191,785 | 5,412,798 | Substituting STL List container with class pointer | With the following implementation, I'm attempting to answer my question:
class wlist
{
private:
std::list<void*> m_list;
public:
unsigned int size () { return m_list.size(); }
bool empty () { return m_list.empty(); }
void pop_back () { m_list.pop_back(); }
void pop_front () { m_list.pop_front(); }... | Answer to my initial question:
/* Question /
/ Can the following declaration be substituted by qwertyWrap keyboard ??? */
list keyboard; or qwertyWrap keyboard;
qwertyWrap keyboard can be substituted for list keyboard and still maintain the std::list functionality. I've also implemented this solution sometime back.
|
5,191,833 | 5,191,865 | Why are all datatypes a power of 2? | Why are all data type sizes always a power of 2?
Let's take two examples:
short int 16
char 8
Why are they not the like following?
short int 12
| That's an implementation detail, and it isn't always the case. Some exotic architectures have non-power-of-two data types. For example, 36-bit words were common at one stage.
The reason powers of two are almost universal these days is that it typically simplifies internal hardware implementations. As a hypothetical exa... |
5,191,965 | 5,192,000 | int main(int argc, char** argv) |
Duplicate:
What is the proper declaration of main?
What do we mean by the arguments in this main function? What are they trying to tell us?
int main(int argc, char** argv)
UPDATE: And, is the preceding line of code similar to this int main(int argc, char* argv[])? If so, how can we say that char** argv is similar ... | The argc parameter is the number of command line options specified, including the executable name, when the executable was invoked. The individual command line options are found in the argv array, which is NULL terminated (the name and path used to invoke the executable is in argv[0]).
The difference between the two v... |
5,192,068 | 5,192,091 | C++ - char** argv vs. char* argv[] | What is the difference between char** argv and char* argv[]? in int main(int argc, char** argv) and int main(int argc, char* argv[])?
Are they the same? Especially that the first part does not have [].
| They are entirely equivalent. char *argv[] must be read as array of pointers to char and an array argument is demoted to a pointer, so pointer to pointer to char, or char **.
This is the same in C.
|
5,192,120 | 5,192,156 | change clock's precision | Env: Win Xp, Visual C++
I use clock() to measure the time cost in my program.
But the t_clock always be the multiply of 10, for example 10, 20, 30,
40,...
And I want to get the precision of 1, such as 11, 12, 13, 14...
How can I change the t_clock's precision?
thanks
| You can't; clock() uses the system's ordinary RTC. What you actually need to use are High Performance Timers. http://msdn.microsoft.com/en-us/magazine/cc163996.aspx
|
5,192,165 | 5,236,819 | matlab neural network toolbox | I used the matlab neural network to train on some data but I want to run this neural network in c++ program,how to do that?
| You can use ML to generate your feature set (input layer) and then use an open source C++ NN implementation to do training/classification. (E.g., http://takinginitiative.net/2008/04/23/basic-neural-network-tutorial-c-implementation-and-source-code/) If you want to use ML to train and C++ to classify it shouldn't be too... |
5,192,239 | 5,192,299 | Why is ostringstream faster than ofstream | To write many piece of data to file, I have 2 approaches:
Write to ofstream one by one directly
ofstream file("c:\\test.txt");
for (int i = 0; i < 10000; ++i)
{
file << data[i];
}
Write to istringstream first, and then write to ofstream at once
ostringstream strstream;
for (int i = 0; i < 10000; ++i)
{
str... | Are you using std::endl a lot instead of '\n'? std::endl does two things: it inserts a '\n' into the stream and then flushes the buffer to disk. I've seen code talking a severe performance hit by doing so. (The code ran 5-10 times faster after that was fixed.)
Flushing to a string buffer will be much faster than flushi... |
5,192,282 | 5,192,365 | Why bother with virtual functions in c++? | This is not a question about how they work and declared, this I think is pretty much clear to me. The question is about why to implement this?
I suppose the practical reason is to simplify bunch of other code to relate and declare their variables of base type, to handle objects and their specific methods from many othe... | Yes, this can be done with templates, but then the caller must know what the actual type of the object is (the concrete class) and this increases coupling.
With virtual functions the caller doesn't need to know the actual class - it operates through a pointer to a base class, so you can compile the client once and the ... |
5,192,404 | 5,192,440 | C++ - Is an array a pointer? |
Possible Duplicate:
C: differences between pointer and array
Is an array in C++ a pointer? Can you clarify this?
Thanks.
| The array name itself without any index is a pointer.
int a[10];
printf("%d\n",*a); // will print first value
printf("%d\n",*(a+1) ); // will print second value
|
5,192,501 | 5,391,712 | how to check if corba::WString is empty? | Searched for this everywhere and finally came here. I have a CORBA::WString_var as input parameter to my function. How do I know if it's empty?
| I think you need to consult your ORB vendor's documentation. If your ORB maps CORBA::WChar to std::wchar_t, then you can use the techniques in this answer.
|
5,192,599 | 5,193,676 | How to define and use boost::function with "optional arguments"? | I am using a class that needs some kind of callback method, so i'm using boost::function to store the function pointers.
i need the callback to have one optional argument, but i found out that boost::function won't let me define optional arguments kind of type, so i tried the following code and it worked..
//the second... | Arguably a type safety hole in the bind -> function conversion.
boost::bind doesn't return an std::function but a function object of a very complicated type. In the case of
boost::bind(&A::boo,a,_1);
as seen above, the returned object has type
boost::_bi::bind_t<
int,
boost::_mfi::mf1<int,A,int>,
boost::_bi::l... |
5,192,769 | 5,192,814 | Obj-C error: "expected unqualified-id before class pointer" | I am currently working on a iOS development project. For convenience I split the features in several small programs in early stage. The project consists of Obj-C, Obj-C++ and C++ programs. Right now I am putting all them together into the final product and encountered some strange behaviors in terms of (I guess) compat... | I don't know Obj-C++, just C++.
Some compilers see export as a keyword, try naming your variable differently.
|
5,192,874 | 5,192,909 | Question about vector iterator in template functions | I'm trying to learn the STL library and I'm having a weird problem. This code compiles perfectly:
void Show(vector<int> myvec)
{
vector<int>::iterator it;
cout << "Vector contains:";
for( it = myvec.begin(); it < myvec.end(); it++)
{
cout << " " << *it;
}
cout << endl;
}
while this on... | You need to say typename vector<T>::iterator it.
On another note, you're passing vectors by value. That means the entire vector gets copied in the function call. void Show(vector<T> const &myvec) and using const_iterator would be wiser.
|
5,193,007 | 5,194,962 | Composing meta-functions | Is there an established idiom for composing ("chaining") meta-functions? This is my current solution:
template
<
template <typename> class First,
template <typename> class Then,
typename T
>
struct compose : Then<typename First<T>::type> {};
And here is an example usage:
template <typename T>
struct remove... | You might check out the boost::mpl library:
http://www.boost.org/doc/libs/1_46_0/libs/mpl/doc/refmanual/composition-and-argument-binding.html
I'm not claiming that mpl is better than what you have. Just that it looks like similar territory and it might interest you.
|
5,193,113 | 5,193,328 | Increase process priority with pthread_win32 | Environment: Win XP, Visual C++
I'm using the pthread_win32 library in order to implement threads in my program, and I want to raise my process (program) priority to HIGH_PRIORITY_CLASS. Is there any function in the library that allows this kind of operation?
Otherwise, is it possible to use the SetPriorityClass funct... | You can get a native thread handle on which to call SetPriorityClass with pthread_getw32threadhandle_np.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.