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 |
|---|---|---|---|---|
1,236,827 | 1,236,907 | Compiling C++ Code With Boost's Numeric Binding Library to Solve Ax=b Linear System | I am using Numeric Library Bindings for Boost UBlas to solve a simple
linear system:
#include<boost/numeric/ublas/matrix.hpp>
#include<boost/numeric/ublas/io.hpp>
#include<boost/numeric/bindings/traits/ublas_matrix.hpp>
#include<boost/numeric/bindings/lapack/gesv.hpp>
#include <boost/numeric/bindings/traits/ublas_vecto... | sgesv_ is a symbol from LAPACK library, you'll have to link to that. uBLAS just binds to it I guess.
I too don't know the name of the library though :)
|
1,237,042 | 1,237,077 | Retrieving paths of FileSystemInfo instances | How does one retrieve ( or resolve, for that matter ) the absolute and relative ( FullPath and OriginalPath fields ) paths of FileSystemInfo/DirectoyInfo/FileInfo instances ? I'm trying to get the paths of the files/directories returned by a FileSystemInfos call on a DirectoryInfo class object.
| the FullName property gets you the full path of the directory or file.
|
1,237,188 | 1,237,199 | compiling c++ into "real" programs | I know how to use g++ and all that to compile c++ programs.
My question is, if I have some code which depends on various libraries, how can I compile it into a simple executable that I can send anyone. For this I would be happy with just keeping it on os x.
I would like to know how to compile a "real" program not just ... | You a looking for "static linking". That will import all the needed code from the libraries into your executable. Note the executable will get larger. If you are using standard libraries, they should be present on standard OS installation.
You should try "-static" flag of g++.
Running "ldd your_executable_name" should ... |
1,237,259 | 1,827,599 | About write buffer in general network programming | I'm writing server using boost.asio. I have read and write buffer for each connection and use asynchronized read/write function (async_write_some / async_read_some).
With read buffer and async_read_some, there's no problem. Just invoking async_read_some function is okay because read buffer is read only in read handler ... | Answer #1:
You are correct that locking is a viable approach, but there is a much simpler way to do all of this. Boost has a nice little construct in ASIO called a strand. Any callback that has been wrapped using the strand will be serialized, guaranteed, no matter which thread executes the callback. Basically, it h... |
1,237,361 | 1,237,545 | How sets, multisets, maps and multimaps work internally | How do multisets work? If a set can't have a value mapped to a key, does it only hold keys?
Also, how do associative containers work? I mean vector and deque in the memory is located sequentially it means that deleting/removing (except beginning [deque] and end [vector, deque]) are slow if they are large.
And list is a... | These 4 containers are typically all implemented using "nodes". A node is an object that stores one element. In the [multi]set case, the element is just the value; in the [multi]map case each node stores one key and its associated value. A node also stores multiple pointers to other nodes. Unlike a list, the nodes in s... |
1,237,536 | 1,237,583 | Controlling Firefox from C/C++ | I'm thinking of creating an application that can use Firefox as a download manager. Is there any way to control Firefox (add downloads, start/stop downloads, etc) from an external program in C/C++?
If that is not possible, then perhaps an extension that can do that? If an extension is the only way, then how do I commun... | You're starting with a solution, not a problem. The easier idea is to use XulRunner, the platform on which FireFox is built. You'd effectively implement your own application as a XulRunner plugin and use Necko (the network layer of XulRunner and FireFox) from there.
|
1,237,555 | 1,238,201 | Design advice for a personal project - "Files Renamer"? | i've just started learning winapis and c++ programming ..
i was thinking about starting a personal project (to enhance my coding, and to help me understand the winapis better)..
and i've decided to program a "cmd" files renamer, that basically takes :
1)a path
2)a keyword
3)the desiered formate
4)versioned or not (or n... | Regular expressions should do the trick. Also you could use the Boost library, it has some really neat functions including the regexp, which is probably faster than the functions you'll find around (:
|
1,237,571 | 1,237,619 | Problems deleting a 2D dynamic array in C++ (which is eventually store in a vector) | So I have this 2d dynamic array which content I want to free when I am done with it. However I keep running into a heap corruption after the destructor. The code works fine (of course with memory leaks) if I comment out the destructor. (Visual Studio 2005)
FrameData::FrameData(int width, int height)
{
width_ = widt... | Your problem is as you guessed in here:
FrameData myFrame;
std::vector<FrameData> frames;
...snipped...
frames.push_back(myFrame);
The vector makes copies of the elements that you push in. What do you have for your copy constructor and/or operator= for your class? If you have none defined, the default version that the... |
1,237,723 | 1,237,927 | How to assign / copy a Boost::multi_array | I want to assign a copy of a boost::multi_array. How can I do this. The object where I want to assign it to has been initialized with the default constructors.
This code does not work, because the dimensions and size are not the same
class Field {
boost::multi_array<char, 2> m_f;
void set_f(boost::multi_array<shor... | You should resize m_f before assigning. It could look like in the following sample:
void set_f(boost::multi_array<short, 2> &f) {
std::vector<size_t> ex;
const size_t* shape = f.shape();
ex.assign( shape, shape+f.num_dimensions() );
m_f.resize( ex );
m_f = f;
}
May be there is a better way. Convers... |
1,237,756 | 1,237,777 | How to Sum Column of a Matrix and Store it in a Vector in C++ | Is there a straight forward way to do it?
I'm stuck here:
#include <iostream>
#include <vector>
#include <cstdlib>
using std::size_t;
using std::vector;
int main()
{
vector<vector<int> > Matrix;
//Create the 2x2 matrix.
size_t rows = 2;
size_t cols = 2;
// 1: set the number of rows.
Matrix.resize(row... | for( size_t row = 0; row < Matrix.size(); row++ )
{
ColSum[row] = 0;
for( size_t column = 0; column < Matrix[row].size(); column++ )
{
ColSum[row] += Matrix[row][column];
}
}
|
1,237,768 | 1,237,803 | Where is the memory leak in this C++? | I have been told be a couple of tools that the following code is leaking memory, but we can't for the life of us see where:
HRESULT CDatabaseValues::GetCStringField(ADODB::_RecordsetPtr& aRecordset, CString& strFieldValue,
const char* strFieldName, const bool& bNullAllowed)
{
... | You have to release memory allocated for BSTR.
See article
Oh, and you have to do a detach before assigning bstr value of VARIANT to CString
strFieldValue = olevar.detach().bstrVal;
and then ensure your CString object gets properly destroyed in time.
|
1,237,948 | 1,297,928 | Problem with directories and file selector (VC++ 2008) | I have implemented a file selector with a combobox. I want to write the selected filename to a log. The problem is that when I select a file from the original directory it goes well but when I choose a file from another directory it won't work. Can anybody help with this? Here is the code for the file selector, it is i... | From the documentation for DlgDirListComboBox:
If lpPathSpec specifies a directory,
DlgDirListComboBox changes the current
directory to the specified directory
before filling the combo box. The text
of the static control identified by
the nIDStaticPath parameter is set to
the name of the new current direct... |
1,237,963 | 1,238,014 | Alignment along 4-byte boundaries | I recently got thinking about alignment... It's something that we don't ordinarily have to consider, but I've realized that some processors require objects to be aligned along 4-byte boundaries. What exactly does this mean, and which specific systems have alignment requirements?
Suppose I have an arbitrary pointer:
u... | It can definitely cause problems on some systems.
For example, on ARM-based systems you cannot address a 32-bit word that is not aligned to a 4-byte boundary. Doing so will result in an access violation exception. On x86 you can access such non-aligned data, though the performance suffers a little since two words have ... |
1,238,319 | 1,238,326 | Check whether a shutdown is initiated or not | What is the win32 function to check whether a shutdown is initiated or not?
EDIT: I need to check that inside a windows service (COM). How to do that?
| There's no actual Win32 function to check for that.
Instead Windows sends the WM_QUERYENDSESSION message to every application when a shutdown is initiated.
You can respond to that message and for example cancel the shutdown. (Although you shouldn't do that unless it is absolutely necessary)
Before the actual shutdown ... |
1,238,376 | 1,281,662 | VC++: KB971090 and selecting Visual C Runtime DLL dependencies | As you might know, Microsoft recently deployed a security update for Visual Studio: KB971090.
Among other things, this updated the Visual C Runtime DLL from version 8.0.50727.762 to 8.0.50727.4053.
So after this update, everything I compile that uses the runtime dynamically linked, gets their dependencies updated to th... | You can specify the version by using the workaround found here
|
1,238,379 | 1,238,410 | Detecting if a process is still running | I need to check if a process with a given HANDLE is still running, I tried to do it using the following code however it always returns at the second return false, even if the process is running.
bool isProcessRunning(HANDLE process)
{
if(process == INVALID_HANDLE_VALUE)return false;
DWORD exitCode;
if(GetE... | You can test the process life by using
bool isProcessRunning(HANDLE process)
{
return WaitForSingleObject( process, 0 ) == WAIT_TIMEOUT;
}
|
1,238,609 | 1,238,719 | static_cast wchar_t* to int* or short* - why is it illegal? | In both Microsoft VC2005 and g++ compilers, the following results in an error:
On win32 VC2005: sizeof(wchar_t) is 2
wchar_t *foo = 0;
static_cast<unsigned short *>(foo);
Results in
error C2440: 'static_cast' : cannot convert from 'wchar_t *' to 'unsigned short *' ...
On Mac OS X or Linux g++: sizeof(wchar_t) is 4
wc... | You cannot cast between unrelated pointer types. The size of the type pointed to is irrelevant. Consider the case where the types have different alignment requirements, allowing a cast like this could generate illegal code on some processesors. It is also possible for pointers to different types to have differrent size... |
1,238,741 | 1,365,903 | Does the latest Visual Studio 2005 Security Update cause C runtime library issues when hot fixing customer sites | As you might be aware an update to visual studio 2005 was auto updated on most machines last week. This update included a new version of the visual c runtime library. As a result any binaries built after the update also require a new redistributable installed on client systems.
See http://support.microsoft.com/kb/971... | The version number specified in the application’s manifest file/resource only specifies the minimum version required to run the application. The default behavior of the loader is to first check the WINDOWS\WinSxS folder for the identical version or a superseding version of a dependency identified in an application mani... |
1,239,235 | 1,239,457 | How lazy can C++ global initialization be? | I'm used to thinking of all initialization of globals/static-class-members as happening before the first line of main(). But I recently read somewhere that the standard allows initialization to happen later to "assist with dynamic loading of modules." I could see this being true when dynamic linking: I wouldn't expect ... | The standard has the following in 3.6.2/3:
It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of
namespace scope is done before the first statement of main. If the initialization is deferred to some point
in time after the first statement of main, it shall ... |
1,239,297 | 1,239,305 | What environment should I use for 3d programming on Linux? | One thing I always shy away from is 3d graphics programming, so I've decided to take on a project working with 3d graphics for a learning experience. I would like to do this project in Linux.
I want to write a simple 3d CAD type program. Something that will allow the user to manipulate objects in 3d space. What is the... | OpenGL/SDL, and the IDE is kind-of irrelevant.
My personal IDE preference is gedit/VIM + Command windows. There are tons of IDE's, all of which will allow you to program with OpenGL/SDL and other utility libraries.
I am presuming you are programming in C, but the bindings exist for Python, Perl, PHP or whatever else, s... |
1,239,364 | 1,239,468 | When are two elements of an STL set considered identical? | From cplusplus.com:
template < class Key, class Compare = less<Key>,
class Allocator = allocator<Key> > class set;
"Compare: Comparison class: A class that takes two arguments of the same type as the container elements and returns a bool. The expression comp(a,b), where comp is an object of this comparison clas... | Not an exact duplicate, but the first answer here answers your question
Your second guess as to the behaviour is correct
|
1,239,380 | 1,239,792 | pass a callable object to a member function | class Action {
public:
void operator() () const;
}
class Data {
public:
Data();
~Data();
Register(Action action) { _a = action; }
private:
Action _a;
}
class Display {
public:
Display(Data d) { d.Register( bind(Display::SomeTask, this, _1) ); }
~Di... | What you're trying to do is not completely clear, but I'll assume that "bind" is boost::bind (or tr1::bind).
A couple of problems with bind(Display::SomeTask, this, _1):
It should be &Display::SomeTask
The _1 placeholder makes no sense because that creates an unary function object and:
Display::SomeTask takes no arg... |
1,239,613 | 1,241,852 | Use Objective-C game engine in C++ iPhone game? | You often hear that C++ is preferable to Objective-C for games, especially in a resource-constrained environment like the iPhone. (I know you still need some Objective-C to initially talk to iPhone services.) Yet, the 2D game engine of choice these days seems to be Cocos2d, which is Objective-C.
I understand that what... | I'm currently prototyping a game with Cocos2. I'm writing the game logic in C++ with Chipmunk and then using Cocos to implement the view layer. You can indeed mix C++ and Objective-C freely in the same class, function and line of code. I'm sure there are limits, like you probably can't mix Objective-C and C++ method de... |
1,239,845 | 1,239,947 | CMake build mode RelWithDebInfo | I think that I understand the difference between Release and Debug build modes. The main differences being that in Debug mode, the executable produced isn't optimized (as this could make debugging harder) and the debug symbols are included.
While building PCRE, one of the external dependencies for WinMerge, I noticed ... |
Am I missing something, or does it not
make sense to compile all release code
as RelWithDebInfo?
It depends on how much you trust your customer with the debugging information.
Additional Info:
gcc encodes the debugging information into the object code.
Here is the pdb equivalent for gcc:
How to generate gcc debug... |
1,239,855 | 1,240,032 | Pad a C++ structure to a power of two | I'm working on some C++ code for an embedded system. The I/O interface the code uses requires that the size of each message (in bytes) is a power of two. Right now, the code does something like this (in several places):
#pragma pack(1)
struct Message
{
struct internal_
{
unsigned long member1;
unsig... | Use a template metaprogram. (Edited in response to comment).
#include <iostream>
#include <ostream>
using namespace std;
template <int N>
struct P
{
enum { val = P<N/2>::val * 2 };
};
template <>
struct P<0>
{
enum { val = 1 };
};
template <class T>
struct PadSize
{
enum { val = P<sizeof (T) - 1>::val - ... |
1,239,908 | 1,239,940 | Why doesn't a derived template class have access to a base template class' identifiers? | Consider:
template <typename T>
class Base
{
public:
static const bool ZEROFILL = true;
static const bool NO_ZEROFILL = false;
}
template <typename T>
class Derived : public Base<T>
{
public:
Derived( bool initZero = NO_ZEROFILL ); // NO_ZEROFILL is not visible
~Derived();
}... | That's two-phase lookup for you.
Base<T>::NO_ZEROFILL (all caps identifiers are boo, except for macros, BTW) is an identifier that depends on T.
Since, when the compiler first parses the template, there's no actual type substituted for T yet, the compiler doesn't "know" what Base<T> is. So it cannot know any identifie... |
1,239,938 | 1,239,977 | Accessing an array out of bounds gives no error, why? | I am assigning values in a C++ program out of the bounds like this:
#include <iostream>
using namespace std;
int main()
{
int array[2];
array[0] = 1;
array[1] = 2;
array[3] = 3;
array[4] = 4;
cout << array[3] << endl;
cout << array[4] << endl;
return 0;
}
The program prints 3 and 4. It... | Welcome to every C/C++ programmer's bestest friend: Undefined Behavior.
There is a lot that is not specified by the language standard, for a variety of reasons. This is one of them.
In general, whenever you encounter undefined behavior, anything might happen. The application may crash, it may freeze, it may eject your... |
1,240,218 | 1,927,684 | Does a Qt application work in Google Native Client? | I'm not familiar with Qt or with Google Native Client. Is it possible for a TRIVIAL Qt console application to be ported to Google Native Client? I understand that some work would be involved. But the question is, how much if it's even possible?
| A Qt developer has managed to get some Qt examples running under Native Client:
http://blog.qt.io/blog/2009/12/17/take-it-with-a-grain-of-salt/
|
1,240,242 | 1,240,279 | Should destructors be exported in Windows DLL Libraries? | In generating Windows DLL dynamic libraries, you are asked to declare which functions should be exported so that some functions maybe left private to the DLL and not accessible by other applications.
I haven't seen anything mentioned regarding whether destructors need to be exported or are they automatically handled by... | In general, any class with a constructor should export the destructor as well.
That being said, there are a couple of things to be wary of here...
If you're building on Windows, you need to be careful about mixing VS versions with libraries. If you're only going to be distributing your library as a DLL, exporting cons... |
1,240,634 | 1,241,325 | How to get rid of warning LNK4006 when not using templates? | I know the question is not very descriptive but I couldn't phrase it better.
I'm trying to compile a static linked library that has several objects, all the objects contain the following:
#include foo.h
foo.h is something along these lines:
#pragma once
template<class T>
class DataT{
private:
T m_v;
pu... | I'm not sure what you're trying to do in the example for edit #2, but I think it might help if you have the following in foo.inl:
inline
Data::Data(double v): m_v(v) {}
If the contents of foo.inl is also being included in something where the inline keyword won't work or shouldn't be, you can probably use the preproces... |
1,240,703 | 1,240,717 | storage of user, error, exception messages (c++) | Rather simple question.
Where should I store error,exception, user messages?
By far, I always declared local strings inside the function where it is going to be invoked and did not bother.
e.g.
SomeClass::function1(...)
{
std::string str1("message1");
std::string str2("message2");
std::string str3("message3");
...
// s... | Why not just use a string constant when you need it?
SomeClass::function1(...)
{
/* ... */
throw std::runtime_error("The foo blortched the baz!");
/* ... */
}
Alternately, you can use static const std::strings. This is appropriate if you expect to copy them to a lot of other std::strings, and your C++ implementati... |
1,240,876 | 1,240,898 | Stylistic question concerning returning void | Consider the following contrived example:
void HandleThat() { ... }
void HandleThis()
{
if (That) return HandleThat();
...
}
This code works just fine, and I'm fairly sure it's spec-valid, but I (perhaps on my own) consider this unusual style, since the call appears to return the result of the function, despi... | I agree with you, the first style is confusing because there's the implication that some sort of value is getting returned. In fact I had to read it over a couple times because of that.
When returning from a function prototyped void, it should just be return;
|
1,241,000 | 1,241,031 | Unmanaged C++ Get the current process id? (Console Application) | How can I get the current process id from an unmanaged C++ console application? I see that
GetWindowThreadProcessId
Works when you have an HWND, but what can I do for a console application?
| Have you tried GetCurrentProcessId?
http://msdn.microsoft.com/en-us/library/ms683180(VS.85).aspx
|
1,241,099 | 1,241,592 | C++: access const member vars through class or an instance? | In C++, is there any reason to not access static member variables through a class instance? I know Java frowns on this and was wondering if it matters in C++. Example:
class Foo {
static const int ZERO = 0;
static const int ONE = 1;
...
};
void bar(const Foo& inst) {
// is this ok?
int val1 = inst.ZERO;
... | For the first question, aside from the matter of style (it makes it obvious it's a class variable and has no associated object), Fred Larsen, in comments to the question, makes reference to previous question. Read Adam Rosenthal's answer for very good reason why you want to be careful with this. (I'd up-vote Fred if ... |
1,241,144 | 1,241,199 | Socket remains open after program has closed (C++) | I'm currently writing a small server application, and my problem is, that when I close my app (or better, press the terminate button in eclipse), the socket sometimes stays open, so when I execute my app the next time, bind() will fail with "Address already in use". How can I properly close my sockets when the program ... | http://hea-www.harvard.edu/~fine/Tech/addrinuse.html should answer a lot of your questions. I tend to use SO_REUSEADDR to work around that problem.
|
1,241,399 | 1,241,548 | What is a .h.gch file? | I recently had a class project where I had to make a program with G++.
I used a makefile and for some reason it occasionally left a .h.gch file behind.
Sometimes, this didn't affect the compilation, but every so often it would result in the compiler issuing an error for an issue which had been fixed or which did no... | A .gch file is a precompiled header.
If a .gch is not found then the normal header files will be used.
However, if your project is set to generate pre-compiled headers it will make them if they don’t exist and use them in the next build.
Sometimes the *.h.gch will get corrupted or contain outdated information, so dele... |
1,241,848 | 1,241,892 | Why doesn’t WPF support C++.NET - the way WinForms does? | As a C++ stickler, this has really been bugging me. I've always liked the idea of the "language-independant framework" that Microsoft came up with roughly a decade ago. Why have they dropped the ball on this idea? Does anyone know the reasoning behind it?
| Part of the reason will be that C++ support is actually two languages in one -- the native and the CLI variants; that extra development load has been acknowledged by the Visual C++ team as the reason that proper MSBuild integration lagged (lags? I haven't checked in 2008 or later) behind other languages.
Another part ... |
1,241,973 | 1,241,998 | push_back(this) pushes wrong pointer onto vector | I have a vector of UnderlyingClass pointers stored in another object, and inside a method in UnderlyingClass I want to add the "this" pointer to the end of that vector. When I look at the contents of the vector immediately after the push_back call, the wrong pointer is in there. What could be going wrong?
cout << "th... | This can happen with multiple inheritance, if your layout looks like this:
class UnderlyingBase {
char d[56];
};
class UnderlyingClass
:public UnderlyingBase,
public WebCallback {
};
Then the layout can be like this, for each object involved. The last one is the complete object containing the first two o... |
1,242,005 | 2,671,834 | What is the most efficient way to display decoded video frames in Qt? | What is the fastest way to display images to a Qt widget? I have decoded the video using libavformat and libavcodec, so I already have raw RGB or YCbCr 4:2:0 frames. I am currently using a QGraphicsView with a QGraphicsScene object containing a QGraphicsPixmapItem. I am currently getting the frame data into a QPixma... | Thanks for the answers, but I finally revisited this problem and came up with a rather simple solution that gives good performance. It involves deriving from QGLWidget and overriding the paintEvent() function. Inside the paintEvent() function, you can call QPainter::drawImage(...) and it will perform the scaling to a... |
1,242,185 | 1,242,214 | loop condition evaluation | Just a quick question.
I have a loop that looks like this:
for (int i = 0; i < dim * dim; i++)
Is the condition in a for loop re-evaluated on every loop?
If so, would it be more efficient to do something like this?:
int dimSquare = dim * dim;
for (int i = 0; i < dimSquare; i++)
Thanks
-Faken
| In general, if you would for example change the value of "dim" inside your loop, it would be re-evaluated every time. But since that is not the case in your example, a decent compiler would optimize your code and you wouldn't see any difference in performance.
|
1,242,190 | 1,279,744 | C++ Memory Efficient Solution for Ax=b Linear Algebra System | I am using Numeric Library Bindings for Boost UBlas to solve a simple linear system.
The following works fine, except it is limited to handling matrices A(m x m) for relatively
small 'm'.
In practice I have a much larger matrix with dimension m= 10^6 (up to 10^7).
Is there existing C++ approach for solving Ax=b that us... | Short answer: Don't use Boost's LAPACK bindings, these were designed for dense matrices,
not sparse matrices, use UMFPACK instead.
Long answer: UMFPACK is one of the best libraries for solving Ax=b when A is large and sparse.
http://www.cise.ufl.edu/research/sparse/umfpack/
http://www.cise.ufl.edu/research/sparse/umf... |
1,242,357 | 1,242,442 | How to release memory from std::deque? | I'm using a std::deque to store a fairly large number of objects. If I remove a bunch of those objects, it appears to me that its memory usage does not decrease, in a similar fashion to std::vector.
Is there a way to reduce it? I know that in a vector you have to use the 'swap trick', which I assume would work here too... | There is no way to do this directly in a std::deque. However, it's easy to do by using a temporary (which is basically what happens in a std::vector when you shrink it's capacity).
Here is a good article on std::deque, comparing it to std::vector. The very bottom shows a clean way to swap out and shrink a vector, whi... |
1,242,742 | 1,242,748 | Compiling PARDISO linear solver test case with GCC | I am trying to compile a linear system solver using PARDISO.
The test case (pardiso_sym.c) also downloaded from the same website above.
I have the following files inside the directory:
[gv@emerald my-pardiso]$ ls -lh
total 1.3M
-rw-r--r-- 1 gv hgc0746 1.3M Aug 7 11:59 libpardiso_GNU_IA64.so
-rw-r--r-- 1 gv hgc0746 7.... | EDIT: I read the pardiso manual. Here's the fix:
gcc pardiso_sym.c -o pardiso_sym -L . -lpardiso_GNU_IA64 -L/home/gv/.boost/include/boost-1_38 -llapack
Here I've removed the "lib" from the start and the ".so" from the end of -lpardiso_GNU_IA64
|
1,242,820 | 1,243,108 | Can a C++ Static Library link to shared library? | Say I have a static C++ lib, static.lib and I want to call some functions from a C++ shared lib, say shared.lib. Is it possible?
Now assume that I have another shared lib, say shared2.lib which links to static.lib but does not link to shared.lib. Does the linker automatically link shared2.lib to shared.lib in this case... | Static libraries are not linked. They are just a collection of object files (*.obj or *.o) that are archived together into a library file (kind of like a tar/zip file) to make it easier for the linker to find the symbols it needs.
A static lib can call functions that are not defined (but are only declared in a header ... |
1,242,830 | 1,242,835 | Constructor initialization-list evaluation order | I have a constructor that takes some arguments. I had assumed that they were constructed in the order listed, but in one case it appears they were being constructed in reverse resulting in an abort. When I reversed the arguments the program stopped aborting. This is an example of the syntax I'm using. The thing is, ... | It depends on the order of member variable declaration in the class. So a_ will be the first one, then b_ will be the second one in your example.
|
1,242,947 | 1,242,960 | Quickest way to find substrings in text files | What's the fastest way to find strings in text files ? Case scenario : Looking for a particular path in a text file with around 50000 file paths listed (each path has it's own line).
| A file of that size should easily fit in memory and you can make it into a std::set (or even better a hashset, if you have a library of that at hand) with the paths as its items. Checking if an exact path is there will then be very fast.
If you need to look for sub-paths as well, a sorted std::vector (if you're looking... |
1,243,241 | 1,243,317 | Given an Array, is there an algorithm that can allocate memory out of it? | I'm doing some graphics programming and I'm using Vertex pools. I'd like to be able to allocate a range out of the pool and use this for drawing.
Whats different from the solution I need than from a C allocator is that I never call malloc. Instead I preallocate the array and then need an object that wraps that up and k... | in general: you're looking for a memory mangager, which uses a (see wikipedia) memory pool (like the boost::pool as answered by TokenMacGuy). They come in many flavours. Important considerations:
block size (fixed or variable; number of different block sizes; can the block size usage be predicted (statistically)?
effi... |
1,243,331 | 1,243,344 | Disjoint set as linked list | Can anyone point me to some info on Disjoint sets as linked list? I cant find any code on this.
Language C++
| Well I think you can find information in this page of Wikipedia. Of course, that information is written in pseudo-code, but is not difficult to translate it.
|
1,243,428 | 1,243,435 | Convert string to int with bool/fail in C++ | I have a std::string which could be a string or could be a value (such as 0).
What is the best or easiest way to convert the std::string to int with the ability to fail? I want a C++ version of C#'s Int32.TryParse.
| Use boost::lexical_cast. If the cast cannot be done, it will throw an exception.
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
int main(void)
{
std::string s;
std::cin >> s;
try
{
int i = boost::lexical_cast<int>(s);
/* ... */
}
catch(...)
{
... |
1,243,962 | 1,243,998 | C++ Operator overloading - casting from class | While porting Windows code to Linux, I encountered the following error message with GCC 4.2.3. (Yes, I'm aware that it's a slight old version, but I can't easily upgrade.)
main.cpp:16: error: call of overloaded ‘list(MyClass&)’ is ambiguous
/usr/include/c++/4.2/bits/stl_list.h:495: note: candidates are: std::list<_Tp, ... | It compiles properly if you remove the cast, and I've checked that the operator std::list is being executed.
int main()
{
MyClass a;
std::list<unsigned char> b = a;
return 0;
}
Or if you cast it to a const reference.
int main()
{
MyClass a;
std::list<unsigned char> b = (const std::... |
1,244,001 | 1,244,036 | Deleting from vector in for loop crashes? | I'm having a problem with my looping over a vector, and deleting values from another vector sometimes crashes my program. I have this vector of int's to keep track of which elements should be removed.
std::vector<int> trEn;
Then I loop through this vector:
struct enemyStruct {
float x, y, health, mhealth, speed, t... | The only seemingly obvious thing would be:
if(atmp<=enemies.size() ...
Are you sure you do not mean (atmp < enemies.size()) here? Otherwise your code
enemies.erase(enemies.begin()+atmp, ...
will for sure produce some serious issues.
|
1,244,085 | 1,244,138 | Replacing Value of Diagonals in (m x m) Matrix With its Column Sum with Memory Efficient Way in C++ | I have the following matrix of size m=4
0.00000 0.09130 0.09130 0.00000
0.04565 0.00000 0.00000 0.00000
0.04565 0.00000 0.00000 0.00000
0.00000 0.00000 0.00000 0.00000
And I want to replace the diagonal of that matrix
with (1 - sum of its column). Resulting matrix:
0.90870 0.0... | Create a vector of size m to store the diagonal. Then go through the file and add the ith column of each line to diag[i]. Now go through the file again and output each line, but replace the value of the ith element on the ith line with diag[i]. This way you only need to store a vector of size m in memory.
|
1,244,231 | 1,400,713 | TrayIcon balloon does not show up | I compiled my trayicon utility c++ code in visual studio 2005 express edition and tray icon balloons showed up successfully but later I deleted my firewall, switched on to windows firewall and now I am on another firewall software. Now i ran my same project and balloons showed up successfully but when i rebuilt it, i c... | Ok I figured it out myself. nid.cbSize = sizeof( NOTIFYICONDATA_V2_SIZE ); should be nid.cbSize = NOTIFYICONDATA_V2_SIZE;
|
1,244,269 | 1,244,296 | Placement of a method in a Class | I have a C++ class in which many of its the member functions have a common set of operations. Putting these common operations in a separate function is important for avoiding redundancy, but where should i place this function ideally? Making it a member function of the class is not a good idea since it makes no sense ... | If the "set of operations" can be encapsulated in a function that is not inherently tied to the class in question then it probably should be a free function (perhaps in an appropriate namespace).
If it's somehow tied to the class but doesn't require a class instance it should probably be a static member function, proba... |
1,244,468 | 1,244,601 | QPixmap of a QGraphicsTextItem | How do you convert/paint a QGraphicsTextItem into a QPixmap?
| You can add it to a QGraphicsScene (if it's not already inside one) and then render() the scene to a QPixmap using a QPainter
QPixmap pix(100, 100);
QPainter paint(&pix);
scene.render(&paint);
Or, you can save yourself the trouble and just use QPainter::drawText() after changing the current font of the painter. it sho... |
1,244,694 | 1,244,726 | makefile/script for small program | I have to frequently compile small program and run it. Since, it was tedious to write compile command g++ -W -Wall file.cpp -o out everytime for each cpp file, I wrote one small scripts, which does the compiling.
Here is the script that I wrote
#!/bin/bash
g++ -W -Wall $1 -o $1.out
So, if I have to compile file.cpp, ... | export CXXFLAGS="-W -Wall"
rm Makefile
make file1
Make has sane defaults. You don't have to write a makefile to use make.
Make has a set of generic rules, which get apply automatically when there is no specific rule. One of them is to make 'file' out of 'file.cpp' using a C++ compiler with flags from environment varia... |
1,244,847 | 1,244,908 | Error converting a pipe (Handler) to fd on vs 2003 | I am trying to use notify a main gtk thread ( from a separate thread) that some even occurred using pipes. I get the following warning when I am trying to setup pipes. What is a good workaround?
when I can this g_io_channel_win32_new_fd, I see this warning, and thus pipe isn't created at all :(
GLib-WARNING **: giowin3... | Like the error says, handles created by CreatePipe are not file descriptors. The Windows programming model does not use file descriptors, so you cannot normally mix and match Windows and non-Windows I/O functions. I suspect if you removed some of the casts in your code, your compiler would pinpoint the problem - C-styl... |
1,245,075 | 1,245,123 | XML vs Hardcoded interface? | I'm working on a flexible GUI application that can have ~12 varied layouts. These layouts are all well-defined and won't change. Each layout consists of multiple widgets that interface with a DLL using bit patterns. While the majority of the widgets are the same, the bit patterns used vary depending on the interface ty... | YAGNI: Design your screens for the current requirements, which you specifically state aren't going to change. If a year down the line more customization is needed, make it more customizable then, not now.
KISS: If using XML results in less overall code and is simpler than subclassing, use XML. If subclassing results in... |
1,245,191 | 1,245,211 | where can I find a prime forum for gtk+ (c++) type questions? | I am sorry if it defeats the purpose of this forum, but I see very limited GTK activity here and would like get heavily involved in it. What is the prime forum(s) where GTK is discussed. I use it primarily with c/c++.
| http://www.gtkforums.com? :-)
Or, better, use mailing lists:
http://www.gtk.org/development.html#MailingLists
|
1,245,430 | 1,245,443 | Over the last 7-8 years what are the biggest influences on C++ programming? | I started programming in C++. It was my first language, but I have not used it in many years.
What are the new developments in the C++ world? What are the BIG things - technologies, books, frameworks, libraries, etc?
Over the last 7-8 years what are the biggest influences on C++ programming?
Perhaps we could do one i... | Boost:
free peer-reviewed portable C++ source libraries.
We emphasize libraries that work well with the C++ Standard Library...
We aim to establish "existing practice" and provide reference implementations so that Boost libraries are suitable for eventual standardization. Ten Boost libraries are included in the C++ St... |
1,245,445 | 1,245,562 | Asymmetric virtual Inheritance diamond in C++ | So I have this idea and I think it's basically impossible to implement in C++... but I want to ask. I read through chapter 15 of Stroustrup and didn't get my answer, and I don't think the billion other questions about inheritance diamonds answer this one, so I'm asking here.
The question is, what happens when you inher... | To simplify answer let's think about virtual/non-virtual as duplicated or non-duplicated content.
class LibDerived : LibBase
declares: I allow LibBase be twice (or more ) entered into descending of LibDerived
class MyBase : virtual LibBase {};
declares: I allow compiler to optimize two entries of LibBase in MyBase de... |
1,245,840 | 1,245,844 | Can you guarantee destructor order when objects are declared on a stack? | I have code that controls a mutex lock/unlock based on scope:
void PerformLogin()
{
ScopeLock < Lock > LoginLock( &m_LoginLock );
doLoginCommand();
ScopeLock < SharedMemoryBase > MemoryLock( &m_SharedMemory );
doStoreLogin();
...
}
Can I guarantee that MemoryLock will be destructed before Login... | Yes, it is. In any particular scope local objects are destroyed in the reverse order that they were constructed.
|
1,245,905 | 1,245,921 | Question about include directory order in g++ | Somehow this is the first time I've ever encountered this problem in many years of programming, and I'm not sure what the options are for handling it.
I am in the process of porting an application to Linux, and there is a header file in one of the directories that apparently has the same name as a header file in the st... | There is an important difference between:
#include "endian.h" // Look in current directory first.
And
#include <endian.h> // Look in the standard search paths.
If you want the one in the current directory, use the quotes. If you want the system one, then use the angle brackets. Note that if you have put the current... |
1,245,979 | 1,246,097 | C/C++ call-graph utility for Windows platform | I have a large 95% C, 5% C++ Win32 code base that I am trying to grok.
What modern tools are available for generating call-graph diagrams for C or C++ projects?
| Have you tried SourceInsight's call graph feature?
http://www.sourceinsight.com/docs35/ae1144092.htm
|
1,246,119 | 1,246,276 | why this conversion doesn't work? | Below is my func. I call it with
if(try_strtol(v, rhs))
and RHS = "15\t// comment"
bool try_strtol(int64_t &v, const string& s)
{
try
{
std::stringstream ss(s);
if ((ss >> v).fail() || !(ss >> std::ws).eof())
throw std::bad_cast();
return true;
}
catch(...)
{
... | If you want it to return a boolean, just do this:
bool try_strtol(int64_t &v, const string& s)
{
std::stringstream ss(s);
return (ss >> v).fail() || !(ss >> std::ws).eof();
}
And it's failing because it's a bad cast. Were you hoping the comment would be ignored?
|
1,246,260 | 1,246,366 | Why don't C header files increase the binary's size? | I wrote the following C++ program
class MyClass {
public:
int i;
int j;
MyClass() {};
};
int main(void)
{
MyClass inst;
inst.i = 1;
inst.j = 2;
}
and I compiled.
# g++ program.cpp
# ls -l a.out
-rwxr-xr-x 1 root wheel 4837 Aug 7 20:50 a.out
Then, I #included the ... | By including iostream in your source file, the compiler needs to generate code to setup and tear down the C++ standard I/O library. You can see this by looking at the output from nm, which shows the symbols (generally functions) on your object file:
$ nm --demangle test_with_iostream
08049914 d _DYNAMIC
08049a00 d _GLO... |
1,246,301 | 1,246,312 | C/C++, can you #include a file into a string literal? | I have a C++ source file and a Python source file. I'd like the C++ source file to be able to use the contents of the Python source file as a big string literal. I could do something like this:
char* python_code = "
#include "script.py"
"
But that won't work because there need to be \'s at the end of each line. I coul... | The C/C++ preprocessor acts in units of tokens, and a string literal is a single token. As such, you can't intervene in the middle of a string literal like that.
You could preprocess script.py into something like:
"some code\n"
"some more code that will be appended\n"
and #include that, however. Or you can use xxd -i... |
1,246,449 | 1,246,473 | How can an application write text to the screen? | How can an application write text to the screen without using any DrawText type methods, and how can I catch it?
I've hooked the following:
DrawText
DrawTextA
DrawTextW
DrawTextEx
DrawTextExA
DrawTextExW
TextOut
TextOutA
TextOutW
ExtTextOut
ExtTextOutA
ExtTextOutW
PolyTextOut
PolyTextOutA
PolyTextOutW
None of them yie... | Many applications will write their own proprietary Text Drawing API, for the exact reason that they don't want you to hook it... easily. Take a look at James Devlin's Poker Botting series, he talks about this and how certain poker sites have their own API. He also talks about methods to get around this, OCR, memory scr... |
1,246,813 | 1,247,224 | (simple) boost thread_group question | I'm trying to write a fairly simple threaded application, but am new to boost's thread library. A simple test program I'm working on is:
#include <iostream>
#include <boost/thread.hpp>
int result = 0;
boost::mutex result_mutex;
boost::thread_group g;
void threaded_function(int i)
{
for(; i < 100000; ++i) {}
... | I think you problem is caused by the thread_group destructor which is called when your program exits. Thread group wants to take responsibility of destructing your thread objects. See also in the boost::thread_group documentation.
You are creating your thread objects on the stack as local variables in the scope of your... |
1,247,119 | 12,319,593 | Is there a way to forbid subclassing of my class? | Say I've got a class called "Base", and a class called "Derived" which is a subclass of Base and accesses protected methods and members of Base.
What I want to do now is make it so that no other classes can subclass Derived. In Java I can accomplish that by declaring the Derived class "final". Is there some C++ trick... | As of C++11, you can add the final keyword (technically a special identifier since it is not actually a keyword) to your class, eg
class Derived final
{
...
You can read more about the final keyword at http://en.wikipedia.org/wiki/C++11#Explicit_overrides_and_final
|
1,247,129 | 1,247,190 | Fast generation of random set, Monte Carlo Simulation | I have a set of numbers ~100, I wish to perform MC simulation on this set, the basic idea is I fully randomize the set, do some comparison/checks on the first ~20 values, store the result and repeat.
Now the actual comparison/check algorithm is extremely fast it actually completes in about 50 CPU cycles. With this in ... | If you only use the first 20 values in the randomised array, then you only need to do 20 steps of the Fisher-Yates algorithm (Knuth's version). Then 20 values have been randomised (actually at the end of the array rather than at the beginning, in the usual formulation), in the sense that the remaining 80 steps of the a... |
1,247,493 | 1,247,530 | char[] (c lang) to string (c++ lang) conversion | I can see that almost all modern APIs are developed in the C language. There are reasons for that: processing speed, low level language, cross platform and so on.
Nowadays, I program in C++ because of its Object Orientation, the use of string, the STL but, mainly because it is a better C.
However when my C++ programs n... | The C++ string class has a lot of problems, and yes, what you're describing is one of them.
More specifically, there is no way to do string processing without creating a copy of the string, which may be expensive.
And because virtually all string processing algorithms are implemented as class members, they can only be ... |
1,247,555 | 1,247,571 | Why do you sometimes need to write `typename T` instead of just `T`? | I was reading the Wikipedia article on SFINAE and encountered following code sample:
struct Test
{
typedef int Type;
};
template < typename T >
void f( typename T::Type ) {} // definition #1
template < typename T >
void f( T ) {} // definition #2
void foo()
{
f< Test > ( 10 ); //call #1
... | In general, C++'s syntax (inherited from C) has a technical defect: the parser MUST know whether something names a type, or not, otherwise it just can't solve certain ambiguities (e.g., is X * Y a multiplication, or the declaration of a pointer Y to objects of type X? it all depends on whether X names a type...!-). Th... |
1,247,745 | 1,247,753 | default visibility of C++ class/struct members | In C++, why is private the default visibility for members of classes, but public for structs?
| C++ was introduced as a superset of C. Structs were carried over from C, where the semantics of their members was that of public. A whole lot of C code exists, including libraries that were desired to work with C++ as well, that use structs. Classes were introduced in C++, and to conform with the OO philosophy of encap... |
1,247,778 | 1,248,484 | Is D's scope failure/success/exit necessary? | When using a language that has try/catch/finally, are D's failure/success/exit scope statements still useful? D doesn't seem to have finally which may explain why those statements are used in D. But with a language like C# is it useful? I am designing a language so if I see many pros I'll add it in.
| scope(X) isn't necessary in the same way that for isn't necessary provided you have if and goto.
Here's a paraphrased example from some code I've been writing today:
sqlite3* db;
sqlite3_open("some.db", &db);
scope(exit) sqlite3_close(db);
sqlite3_stmt* stmt;
sqlite3_prepare_v2(db, "SELECT * FROM foo;", &stmt);
scope(... |
1,247,857 | 1,247,867 | Way to increase memory allocated on free store | Is it possible to incrementally increase the amount of allocated memory on a free store that a pointer points to? For example, I know that this is possible.
char* p = new char; // allocates one char to free store
char* p = new char[10]; // allocates 10 chars to free store
but what if I wanted to do something like incr... | You can do this using the function realloc(), though that may only work for memory allocated with malloc() rather than "new"
having said that, you probably don't want to allocate more memory a byte at a time. For efficiency's sake you should allocate in blocks substantially larger than a single byte and keep track of h... |
1,247,968 | 1,247,970 | Fast C++ program, C# GUI, possible? | I'm looking into developing an application that will process data from a line-scan camera at around 2000 lines (frames) per second. For this real-time application, I feel that C/C++ are the way to go. (It is my feeling, and others will agree that Managed code just isn't right for this task.)
However, I've done very l... | There is no reason that you can't write high performance code entirely in C#.
Performance (C# Programming Guide)
Rico Mariani's Performance Blog (an excellent resource)
Tuning .NET Application Performance
SO questions on the same/similiar topic:
C++ performance vs. Java/C#
How much faster is c++ than c#?
Other arti... |
1,248,079 | 1,248,533 | Ways to Determine the Version of Firebird SQL? | Exist any Way to Determine the Version of Firebird SQL is running? using SQL or code (delphi, C++).
Bye
| If you want to find it via SQL you can use get_context to find the engine version it with the following:
SELECT rdb$get_context('SYSTEM', 'ENGINE_VERSION')
as version from rdb$database;
you can read more about it here firebird faq, but it requires Firebird 2.1 I believe.
|
1,248,140 | 1,248,193 | MinGW linking problem | I have a linking problem with MinGW. These are the calls:
g++ -enable-stdcall-fixup -Wl,-enable-auto-import
-Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -Wl,-subsystem,windows
-o debug/Simulation.exe debug/LTNetSender.o debug/main.o debug/simulation.o
debug/moc_simulation.o -L'c:/Programmieren/Qt/4.5.2/l... | I think the linker command should be -lws2_32. The "lib" and ".a" is filled in automatically.
|
1,248,255 | 1,248,261 | Are C++ zero (null) pointers supposed to return false? | I'm not sure if my understanding of C++ is wrong.. I've read that 1) all non-zero values are equivalent to TRUE, and zero is equivalent to FALSE; 2) null pointers are stored as zero.
Yet code like this:
void ViewCell::swapTiles (ViewCell *vc) {
ViewTile *tmp = vc->tile();
[stuff ...]
if (tmp) addTile(tmp);
... | For a pointer, p and (p != 0) are exactly equivalent. If it gives you a segfault, then either it's not a plain pointer, or the problem is elsewhere
|
1,248,506 | 1,248,522 | How to put std::dec/hex/oct into a look-up array | I have this generic string to number conversion :
enum STRING_BASE : signed int {
BINARY = -1,
OCTAL = 0,
DECIMAL = 1,
HEX = 2,
};
template <class Class>
static bool fromString(Class& t, const std::string& str, STRING_BASE base = DECIMAL) {
if (base == BINA... | Try:
std::ios_base& (*arr[])( std::ios_base& ) = { std::oct, std::dec, std::hex };
Or with typedef for the function pointer:
typedef std::ios_base& (*ios_base_setter)( std::ios_base& );
ios_base_setter arr[] = { std::oct, std::dec, std::hex };
You can omit the array size, it will be deteremined from the number of in... |
1,248,706 | 1,249,143 | Accurate evaluation of 1/1 + 1/2 + ... 1/n row | I need to evaluate the sum of the row: 1/1+1/2+1/3+...+1/n. Considering that in C++ evaluations are not complete accurate, the order of summation plays important role. 1/n+1/(n-1)+...+1/2+1/1 expression gives the more accurate result.
So I need to find out the order of summation, which provides the maximum accuracy.
I... | Actually, if you're doing the summation for large N, adding in order from smallest to largest is not the best way -- you can still get into a situation where the numbers you're adding are too small relative to the sum to produce an accurate result.
Look at the problem this way: You have N summations, regardless of orde... |
1,248,774 | 1,248,835 | External sorting of ints with O(N log N) reads and O(N) writes | I'm interested in algorithm which I should use to meet the requirements of external sorting of ints with O(N log N) reads and O(N) writes
| If you're after an algorithm for that type of sorting (where the data can't all fit into core at once), my solution comes from the very earliest days of the "revolution" when top-end machines had less memory than most modern-day calculators.
I haven't worked out the big-O properties but I think it would be O(n) reads, ... |
1,248,941 | 1,248,965 | Visual-C++ Linker Error | I have a class called MODEL in which public static int theMaxFrames resides. The class is defined in its own header file. theMaxFrames is accessed by a class within the MODEL class and by one function, void set_up(), which is also in the MODEL class. The Render.cpp source file contains a function which calls a function... | It sounds very much like you have declared theMaxFrames in the class, but you haven't provided a definition for it.
If this is the case you need to provide a definition for it in a .cpp somewhere.
e.g.
int MODEL::theMaxFrames;
There's a FAQ entry for this question: static data members.
|
1,249,264 | 1,249,279 | Visual Studio and Boost::Test | I'm getting started with Boost::Test driven development (in C++), and I'm retrofitting one of my older projects with Unit Tests. My question is -- where do I add the unit test code? The syntax for the tests themselves seems really simple according to Boost::Test's documentation, but I'm confused as to how I tell the co... | They way I've added Boost unit tests to existing solutions was to create new projects and put the test code in those projects. You don't need to worry about creating a main() function or setting up the tests. Boost takes care of all that for you.
Here is a project I put on Google Code that uses Boost for its unit tests... |
1,249,402 | 1,249,418 | Everything inside < > lost, not seen in html? | I have many source/text file, say file.cpp or file.txt . Now, I want to see all my code/text in browser, so that it will be easy for me to navigate many files.
My main motive for doing all this is, I am learning C++ myself, so whenever I learn something new, I create some sample code and then compile and run it. Also,... | You might want to take a look at online tools such as CodeHtmler, which allows you to copy into the browser, select the appropriate language, and it'll convert to HTML for you, together with keyword colourisation etc.
|
1,249,646 | 39,934,452 | When using boost::program_options, how does one set the name of the argument? | When using boost::program_options, how do I set the name of an argument for boost::program_options::value<>()?
#include <iostream>
#include <boost/program_options.hpp>
int main()
{
boost::program_options::options_description desc;
desc.add_options()
("width", boost::program_options::value<int>(),
"Give w... | In recent versions of Boost (only tested for >= 1.61) this is fully supported. Below a slight modification of the first example in the tutorial, where "LEVEL" is printed instead of "arg":
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("compression", po::val... |
1,249,673 | 1,250,768 | UCS-2LE text file parsing | I have a text file which was created using some Microsoft reporting tool. The text file includes the BOM 0xFFFE in the beginning and then ASCII character output with nulls between characters (i.e "F.i.e.l.d.1."). I can use iconv to convert this to UTF-8 using UCS-2LE as an input format and UTF-8 as an output format...... | substr works fine for me on Linux with g++ 4.3.3. The program
#include <string>
#include <iostream>
using namespace std;
int main()
{
wstring s1 = L"Hello, world";
wstring s2 = s1.substr(3,5);
wcout << s2 << endl;
}
prints "lo, w" as it should.
However, the file reading probably does something different from w... |
1,249,750 | 1,251,000 | Is there an elegant way to bridge two devices/streams in Asio? | Given two stream-oriented I/O objects in Asio, what is the simplest way to forward data from one device to the other in both directions? Could this be done with boost::iostreams::combination or boost::iostreams:copy perhaps? Or is a manual approach better--waiting for data on each end and then writing it out to the oth... | With standard C++ streams you can do the following, can't you do something similar with Asio?
// Read all data from in and write to out.
void forward_data( std::istream& in, std::ostream& out )
{
out << in.rdbuf();
}
|
1,249,814 | 1,249,848 | Templated copy-constructor fails with specific templated type | As some of my code required implicit conversion between matrices of different types (e.g. Matrix<int> to Matrix<double>), I defined a templated copy constructor Matrix<T>::Matrix(Matrix<U> const&) instead of the standard Matrix<T>::Matrix(Matrix<T> const&):
template <typename T> class Matrix {
public:
// ...
te... | It fails because a template doesn't suppress the implicit declaration of a copy constructor. It will serve as a simple converting constructor, which can be used to copy an object when overload resolution selects it.
Now, you probably copied your matrix somewhere, which would use the implicitly defined copy constructor... |
1,249,904 | 1,249,918 | convert batch files to exes | I'm wondering if it's possible to convert batch files to executables using C++? I have plenty of batch files here and I would like to convert them to executables (mainly to obfuscate the code). I understand that there are 3rd party tools that can do this but I was thinking that this would be a good opportunity for a pr... | You don't just need a parser, you need to write a compiler that accepts .BAT or .CMD files as it's input and outputs C++ as its "machine code". I would class this as a "hard to very hard" project (mainly because of the weirdo syntax and semantics of the input language) but if you want to go for it, the definitive SO qu... |
1,250,219 | 1,250,314 | Using Visual Studio 2008 with C/C++ | I've decided to dive into some code written in C, and I'd like to use Visual Studio. I have Visual Studio 2008 Professional which I'm using now primarily for C#, but I've noticed that there are no options for C in Visual Studio.
Also I've noticed that although Visual Studio has projects, and whatnot for C++ that the bu... | Visual Studio doesn't distinguish much between C++ and C. Instead, you create a C++ project, and then simply add .c files to it. It will by default compile .c files as C code, and .cpp files as C++.
|
1,250,253 | 1,250,761 | Optimizing bit array accesses | I'm using Dipperstein's bitarray.cpp class to work on bi-level (black and white) images where the image data is natively stored as simply as one pixel one bit.
I need to iterate through each and every bit, on the order of 4--9 megapixels per image, over hundreds of images, using a for loop, something like:
for( int i =... | a quick peak into the code for bitarray.cpp shows:
bool bit_array_c::operator[](const unsigned int bit) const
{
return((m_Array[BIT_CHAR(bit)] & BIT_IN_CHAR(bit)) != 0);
}
m_Array is of type std::vector
the [] operator on STL vectors is of constant complexity but its likely implemented as a call to vector::begin t... |
1,250,432 | 1,250,440 | Limiting Singleton instance to thread | What is a good way to implement a singleton that will be restricted only to the thread that seeks its instance? Is there a thread id or something that I can use to do that? I'm using Carbon threading API but will have to implement this on windows and pure POSIX later too, so any technique is appreciated.
| In the past, I have leveraged a hashmap or index to store data structures that are per-thread inside of a single global thread-safe data structure. For instance, if you provide the id for each thread as an incrementing integer, you can store your data structure in a pre-allocated array at the index of the thread it. If... |
1,250,459 | 1,250,476 | Return value for a << operator function of a custom string class in C++ | I am trying to create my own std::string wrapper to extend its functionality.
But I got a problem when declaring the << operator.
Here's my code so far:
my custom string class:
class MyCustomString : private std::string
{
public:
std::string data;
MyCustomString() { data.assign(""); }
MyCustomString(char *value) ... | Firstly, you seem to have an issue with the definition of MyCustomString. It inherits privately from std::string as well as containing an instance of std::string itself. I'd remove one or the other.
Assuming you are implementing a new string class and you want to be able to output it using std::cout, you'll need a cast... |
1,250,522 | 1,250,589 | Does Qt work well with STL & Boost? | I am interested in learning Qt. I am fairly good with C++, STL and Boost. I like STL/Boost style very much, and I use them with C++ whenever I can in uni projects. However, I always miss the GUI. It seems that Qt is the best solution in my case. Qt does have a good collection of containers, but I am greatly familiar wi... | Yes, Qt works just fine with both Boost and the STL. Most of the STL functionality is duplicated in Qt to ensure that such features are supported on all of the platforms that support Qt. However, nothing prohibits you from using STL/boost counterparts of the Qt constructs or functionality therein that Qt lacks.
Althoug... |
1,250,599 | 1,250,624 | How to unordered_set<tuple<int,int>>? | I had encountered strange problem while construct a unordeed_set<tuple<int,int>>. I had tried VC++8, gcc3.2, gcc4.3, all have the same result. I have no idea what's wrong with the code, following is my code:
#include <boost/unordered_set.hpp>
#include <boost/tuple/tuple.hpp>
// For unordered container, the declaration ... | Put the hash function in namespace boost.
#include <boost/unordered_set.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
using namespace std;
using namespace boost;
namespace boost {
size_t hash_value(tuple<int, int> const & t) {
return get<0>(t) * 10 + get<1>(t) ;
}
}... |
1,250,991 | 1,407,600 | Visual Studio 2008 folder browser dialog | In Visual Studio 2008 there is a folder browser dialog that looks like this (very similar to file open dialog):
Does anyone know how to invoke it from code?
| At the end I just used the VistaBridge library to open it.
|
1,251,147 | 1,251,505 | Boost::Test -- generation of Main()? | I'm a bit confused on setting up the boost test library. Here is my code:
#include "stdafx.h"
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE pevUnitTest
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE( TesterTest )
{
BOOST_CHECK(true);
}
My compiler generates the wonderfully useful error message:
... | I think the problem is that you're using the VC10 beta.
It has a fun little bug where, when Unicode is enabled, it requires the entry point to be wmain, not main. (Older versions allowed you to use both wmain and main in those cases).
Of course this will be fixed in the next beta, but until then, well, it's a problem. ... |
1,251,389 | 1,251,501 | What is the smallest embedded browser I can use in C++? | I need to build my application GUI using HTML/CSS/JavaScript
with a C++ backend all cross platform. I made simple tests
with QtWebKit, XULRunner and Mozilla.
Well from the simple testes I notice something that is very
batters me and it is the deployment size of the browsers
libs/framework. It's big: 8 MB and above.
Is ... | I think dillo requires c calling conventions, but it might do for your needs. No javascript or flash, or or or, but it does support CSS.
On reading the question again, I see that you need javascript, which dillo does not currently support. Sorry.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.