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,088,414 | 5,088,441 | Interesting things of ! operation in bool value | Following are one code snippet
#define T 0xFF
using namespace std;
int main(void) {
char c = T;
bool *pc = (bool *)(&c);
bool nc = !(*pc);
cout << "print: " << hex << nc << endl;
nc = T;
cout << "print: " << hex << nc << endl;
nc = c;
cout << "print: " << hex << nc << endl;
}
The resu... | A bool can only take the values true and false.
When you perform !(*pc) you are getting undefined behavior because you telling the compiler to perform ! on a bool object when in actual fact pc is pointing at a char object. (It is the C style cast from char* to bool* that is dangerous, even though the undefined behavior... |
5,088,429 | 5,088,748 | Composition using reference or pointer? | Please let me know which one is good
Consider I have a class like this
class Shape
{
public:
virtual void Display()
{
cout << "Shape::Display()" << endl;
}
};
class Line : public Shape
{
public:
void Display()
{
cout << "Line::Display()" << endl;
}
};
class Circle : public Shap... | The decision has to be taken in terms of what you want to do with your object. Since you are not including the option of storing a value, I will assume that you need the container to refer to an external object. If this is not a requirement, consider using what standard containers do: store a copy of the object.
By usi... |
5,088,460 | 5,088,602 | Flags to enable thorough and verbose g++ warnings | Often in C under gcc, I will start with the following set of warning flags (painfully assembled from multiple sources):
-Wall -Wextra -Wformat-nonliteral -Wcast-align -Wpointer-arith -Wbad-function-cast \
-Wmissing-prototypes -Wstrict-prototypes -Wmissing-declarations -Winline -Wundef \
-Wnested-externs -Wcast-qual -Ws... | D'oh, all of my original searches turned up 99% of posts on how to suppress warnings (scarily enough), but I just ran across this comment, which has this lovely set of flags (some less relevant):
Cross checked with:
http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
-g -O -Wall -Weffc++ -pedantic \
-pedantic-error... |
5,088,727 | 5,088,776 | Remove un-/signedness of char type | I want to specialize a class template for char, short, long and long long. This specializations should also holds good for the signed and unsigned variants of the integral types.
I know boost library and std::tr1 / C++0x implements is_signed/is_unsigned and make_signed/make_unsigned type_traits. But how can I remove an... | The "sign-ness" of char is implementation defined. It doesn't have to be able to store negative numbers. In strict standardese, char even is never a signed integer type, even if it can store negative numbers on an implementation. Still, the class template is_signed will report true for char if it can store negative num... |
5,089,147 | 5,089,205 | Does C++ have a Garbage Collector (GC)? | I'm currently reading an unreleased master thesis report, that I'm going to give feedback on.
In the report they mention Garbage Collector under native C++ and managed C++. I thought C++ didn't have any standard GC, am I wrong or right? (They do not mention Boehm-Demers-Weiser.)
They have some problem getting it to wor... | Native C++ by default has no such thing (the closest thing to this are the smart pointers, but that's still something entirely different), but that doesn't prevent you from writing your own garbage collection solution (or using third party solution).
Managed C++ (and its successor C++/CLI) of course use .NET garbage co... |
5,089,171 | 5,089,218 | Managing member function execution in C++ | I have a class Managed that contains a function f, which executes other functions of that class.
class Managed {
public:
Managed(){}
~Managed(){}
int f( some arguments ); //managed function
private:
int A();
int B();
int C();
};
I want to manage the actions performed by f depending on the way ... | Your question misses several crucial details (like what some arguments are supposed to do). However, it sounds like maybe you need Managed to contain a std:list of function pointers. Then the f function can simply walk the list, and call the function specified by each element in turn.
I can't comment on how you might... |
5,089,245 | 5,089,464 | Boost.Asio as header-only | I want to use ASIO library from Boost in my project. Its doc say it can be header-only if regex is not used and SSL not used. However, running bcp for asio pulls a very many libraies some of which are with sources so need compiling, bjam etc.
Can I somehow use ASIO in project as only headers, without libs/source? I onl... | AFAIK you can get the non-boost version of asio from http://think-async.com/Asio/AsioAndBoostAsio
"— Boost.Asio uses the Boost.System library to provide support for error codes ( boost::system::error_code and boost::system::system_error). Asio includes these under its own namespace ( asio::error_code and asio::system_e... |
5,089,723 | 5,090,029 | (iphone) is it ok to define @property for a c++ class/struct? | I am mixing c++ and objectc.
In particular, I'm adding a c++ class/struct variable to object-c header, and if this is legit?
For example,
@interface MyView : UIView
{
MyCppClass cppVariable;
}
@property (nonatomic, assign) MyCppClass cppVariable;
@end
and at implementation file, @synthesize cppVariable; as wel... | As is described in this official document on Objective-C++, you can have non-pointer C++ objects inside Objective-C classes. They are correctly constructed and destructed, if you use the option -fobjc-call-cxx-cdtors in GCC / clang.
The situation for @sythesizing non-pointer C++ @property is not as clear, because the d... |
5,089,897 | 5,090,433 | Transferring file using sockets from C++ application to Java application | I'm trying to transfer a file using sockets from a C++ application to a Java application. I wrote this simple code in C++ to send the file:
int main() {
int sock;
struct sockaddr_in sa;
char* memblock;
/* Create socket on which to send. */
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (so... |
UDP doesn't guarantee that all datagrams will arrive.
UDP doesn't guarantee that all datagrams will arrive only once.
UDP doesn't guarantee that the datagrams that do arrive will be in the sequence that you sent them.
See here.
You are wrong to assume that these rules do not apply just because your sender and receive... |
5,089,935 | 5,090,074 | Which questions should one read on stackoverflow? (regarding C++) | Since I'm still learning c++ (and with still I mean since 5 years :-) ) I thought, what better way to learn the hidden details than asking for it.
So, I'm not looking for the question with the most votes, but I would like to know, if you have ever read an article here, you think every intermediate c++ programmer shoul... | I cant suggest you an article but I can advice you two amazing books by Scott Meyers ( I hope they help you). I never seen anything better.
More Effective C++: 35 New Ways to Improve Your Programs and Designs
Effective C++: 55 Specific Ways to Improve Your Programs and Designs
|
5,090,124 | 5,090,404 | C++: Replacing Long Switch() Statement with Indexed Array? | To create a game object dynamically, I take the ObjectTypeID, which is unsigned int, and let it compare within very long switch() statement. If the appropriate swith case is found, I create the object and store it. Because I already have 90 Game Objects, the Switch() is already very long and will be growing to about 30... | An easier way to create factories is to use a template to create the factory method and then store it using a function pointer or perhaps boost::function or std::function if they're available.
For example, given the objects:
#include <iostream>
struct GameObject {
virtual ~GameObject() {}
virtual void foo() co... |
5,090,867 | 5,090,904 | Are boost interprocess containers suitable for thread shared storage in the same process? | I need a vector container to be shared between two threads of the same process, providing mutex protected access for the following methods:
empty
size
erase
push_back
I would also like the collection to provide an iterator which locks the container while the iterator is in use. Essentially I am looking for a collectio... | The answer is yes - it is suitable. See here
|
5,090,988 | 5,091,024 | Which way you prefer to send arguments? | Suppose you have a function:
void fun(int *a, int *b);
Which way you would prefer to send the arguments?
(1.)
int x, y;
fun(&x, &y);
(2.)
int *x, *y;
fun(x, y);
What are the problems with other way or both are same and their behavior will also be the same?
| Usually you use the former if you want the variables on the stack, and the latter if you allocate memory for them on the heap. The stack is typically faster, whereas the heap is typically bigger. So in general, you use the first pattern quite often, and only use the latter when dealing with giant arrays or very large o... |
5,091,023 | 5,094,614 | Choosing between WPF/C# and Qt/C++ | Me and my team are developing an application, which involves a back-end written in C++ and involves use of libraries such as OpenCV, MIL, etc.
Now, we need to develop a GUI to interface with this program, such that the GUI displays the images, and the user can interact with the images and annotate / mark the images, an... | I've used both Qt with C++ and WPF. I much prefer WPF as a User Interface framework. Qt isn't bad, especially post 4.0. I wouldn't even touch earlier versions of Qt.
As others have said in comments, WPF is better documented, and the online community is larger. If you are looking at styled applications WPF is certai... |
5,091,036 | 5,091,099 | Can I create a for loop containing multiple type declarations? | For example:
Is there anything I can do, that might allow me to do this:
for(TiXmlElement * pChild = elem->First(), int i=0; // note multiple type declarations
pChild;
pChild=pChild->NextSiblingElement(), i++) // note multiple types
{
//do stuff
}
Perhaps there is a boost header?
| Nope.
If you want to limit the scope of variables to the loop just add another scope:
{
TiXmlElement * pChild = elem->First();
int i = 0;
for(; pChild; pChild=pChild->NextSiblingElement(), i++)
{
//do stuff
}
}
|
5,091,324 | 5,116,921 | Detecting basic_string instantiation | I wrote the following code to determine if a type is an instantiation of std::basic_string:
template <typename T>
struct is_string
{
enum { value = false };
};
template <typename charT, typename traits, typename Alloc>
struct is_string<std::basic_string<charT, traits, Alloc> >
{
enum { value = true };
};
Is t... | Okay, I found a slightly shorter way:
#include <type_traits>
template <typename T>
struct is_string : std::false_type {};
template <typename charT, typename traits, typename Alloc>
struct is_string<std::basic_string<charT, traits, Alloc> > : std::true_type {};
But maybe others can do even better? :)
|
5,091,346 | 5,091,764 | Pass an object of a type aggregated by a boost::variant to a function that accepts that boost::variant | Suppose I have:
class TypeA { };
class TypeB { };
typedef boost::variant<TypeA, TypeB> Type;
This is ok:
void foo(Type t) { };
int main(){
TypeA a;
foo(a);
}
This does not compile:
void foo(Type &t) { };
int main(){
TypeA a;
foo(a);
}
with the error:
invalid initialization of reference of type ‘T... | What really happens in 1:
TypeA a;
Type __temporary__(a);
foo(__temporary__);
What cannot happen in 2 or 3:
TypeA a;
Type* __temporary__(&a);
// this fails because there is no inheritance relationship
foo(__temporary__);
You have two solutions (for a non template foo):
convert to Type, then take a pointer/referenc... |
5,091,570 | 5,092,164 | Most basic working vbo example | I want to know the simplest method for using vbo's in OpenGL... I have tried running a few examples that work but are clouded with all other information thats making it really confusing me... at the moment this is what i have
GLuint vboId = 0;
const int trisize = (m_tris.size()/2)*3;//m_tris is an index array for verts... | What you are doing looks right, except sizeof(vertices) gives you the size of the address, not the size of the array. So, when you call glBufferData, you are allocating 8 bytes and when you call glBufferSubData, you fill those 8 bytes with the first four bytes of the vertices array and then the first four bytes of the ... |
5,092,333 | 5,093,009 | Boost serialization assertion fail | I use boost's binary serialization and it worked well until now. I have std::list of pointers to serialize for output (oarchive) but serialization fails inside object's serialize() function with MSVC's dialog:
R6010 -abort() has been called
and such string is printed into console window:
Assertion failed: 0 == stati... | The line in question says:
// trap usage of invalid uninitialized boolean which would
// otherwise crash on load.
It looks like at some point you are trying to serialize a bool that hasn't been initialized. Without further code we can't help you find which one.
|
5,092,641 | 5,092,724 | linking error for libs in VC++ | In my project exist two sub project.
main project is shopGUI
other ones are 'connection' and 'log'
I build at first a log.lib file from log project
then add it to connection project and build connection.lib
then I try use connection in main project(shopGUI) but I have linking error.
error said that in
connection.lib(... | Libraries don't link in dependent libraries.
You'll need to link your ShopGui with both sub project libraries.
|
5,093,090 | 5,093,133 | What's the syntax for declaring an array of function pointers without using a separate typedef? | Arrays of function pointers can be created like so:
typedef void(*FunctionPointer)();
FunctionPointer functionPointers[] = {/* Stuff here */};
What is the syntax for creating a function pointer array without using the typedef?
| arr //arr
arr [] //is an array (so index it)
* arr [] //of pointers (so dereference them)
(* arr [])() //to functions taking nothing (so call them with ())
void (* arr [])() //returning void
so your answer is
void (* arr [])() = {};
But naturally, this is a bad practice, just use typedefs :)
Extra:
Wonder how to... |
5,093,188 | 5,093,312 | Good Practice: To Modify Only Function Parameters? | Say, I develop a complex application: Within object member functions, should I modify only those objects, that are passed to the member functions as parameters, or can I access and modify any other objects I have access to(say public or static objects)?
Technically, I know that it is possible to modify anything I have ... | Global state is never a good idea (though it is sometimes simpler, for example logging), because it introduces dependencies that are not documented in the interface and increase coupling between components. Therefore, modifying a global state (static variables for example) should be avoided at all costs. Note: global c... |
5,093,285 | 5,093,647 | Using C++ DLL in D10 | I use a C++ DLL in my app.
type
Tcl_bla = function(filename: PChar): Integer; cdecl;
var
cl_bla: Tcl_bla;
function CallLibraryProc(Proc: String): Pointer;
begin
Result := GetProcAddress(Handle, PChar(Proc));
if not Assigned(Result) then
Loaded := False;
if not Loaded then
MessageBox(0, PChar('Error ... | I may as well post this this as an answer, because it seems like the answer!
The code that you say is D6 code will work fine unmodified in D2010, and have the same meaning. There are two GetProcAddress overloads in Windows.pas. One of them converts from Unicode to ANSI. So you can just call GetProcAddress(Handle, PCha... |
5,093,330 | 5,181,505 | mongoose web server helloworld program | I came across an embedded web server named mongoose and http://code.google.com/p/mongoose/ and I read the wiki it was great and i searched for some sample hello world program but i couldn't find it... i found some example but that was written in c++ for windows and can any one provide an example c program to run this w... | It is quite simple, first you need to implement the call back function:
void *event_handler(enum mg_event event,
struct mg_connection *conn) {
const struct mg_request_info *request_info = mg_get_request_info(conn);
static void* done = "done";
if (event == MG_NEW_REQUEST) {
if (strcmp(request_... |
5,093,460 | 5,093,643 | How to convert an enum type variable to a string? | How to make printf to show the values of variables which are of an enum type? For instance:
typedef enum {Linux, Apple, Windows} OS_type;
OS_type myOS = Linux;
and what I need is something like
printenum(OS_type, "My OS is %s", myOS);
which must show a string "Linux", not an integer.
I suppose, first I have to crea... | There really is no beautiful way of doing this. Just set up an array of strings indexed by the enum.
If you do a lot of output, you can define an operator<< that takes an enum parameter and does the lookup for you.
|
5,093,760 | 5,093,847 | Looking for a simple audio playback library for C++ | I'm working on a simple audio player, which is going quite well, using Qt and everything. But I'm in need of a solid but simple Audio library. I don't need anything fancy such as 3D sound and what do I know what else these things got nowadays. I'm just looking for something simple and efficient.
A list of features I'm ... | The best possible choice in my opinion is the BASS audio library, which is not open source, but free for non-commercial use.
It is used by the AIMP2 audio player, which you can use to check the sound quality, natively supports a lot of formats including MP3 and OGG, and uses plugins to support even more, including FLAC... |
5,093,925 | 5,094,017 | Simultaneous abort() in two threads | I have a backtrace with something I haven't seen before. See frame 2 in these threads:
Thread 31 (process 8752):
#0 0x00faa410 in __kernel_vsyscall ()
#1 0x00b0b139 in sigprocmask () from /lib/libc.so.6
#2 0x00b0c7a2 in abort () from /lib/libc.so.6
#3 0x00752aa0 in __gnu_cxx::__verbose_terminate_handler () from /us... | Looks like it could be heap corruption, detected by malloc in thread 1, causing or caused by the error in thread 31.
Some broken piece of code overwriting a.o. the vtable in thread 31 could easily cause this.
|
5,094,013 | 5,094,230 | C++ To Cuda Conversion/String Generation And Comparison | So I am in a basic High School coding class. We had to think up one
of our semester projects. I chose to
base mine on ideas and applications
that arn't used in traditional code.
This brought up the idea for use of
CUDA. One of the best ways I would
know to compare speed of traditional
methods versus unconventional is
s... | If you want to implement a pseudorandom number generator using CUDA, have a look over here. If you want to generate chars from a predetermined set of characters, you can just put all possible chars into that array and create a random index (just as you are doing it right now).
But I think it might be more valuable comp... |
5,094,473 | 5,094,508 | Understanding getopt() example. Comparison of int to char | Hello all I hope you can help me understand why getopt used an int and the handling of the optopt variable in getopt. Pretty new to C++.
Looking at getopt, optopt is defined as an integer.
http://www.gnu.org/software/libtool/manual/libc/Using-Getopt.html#Using-Getopt
and the example here,
http://www.gnu.org/software/li... | When an integer is compared to a character constant as in optopt == 'c', the character constant actually has type int. In fact, in C char and short are second-class citizens and are always promoted to int in expressions, so it's no use passing or returning a char; it's promoted to int anyway.
This is different from the... |
5,094,498 | 5,094,853 | How to style a submenu item in Qt? | I would like to style a menu item that has a submenu differently, just to make this submenu standout. But the style is being applied to the menu items in the submenu rather than styling the submenu item alone.
Menu1
Menu2 -> menu21
menu22
menu23
Menu3
I wanted to style only menu2, but Qt is styling... | See the documentation:
Qt Style Sheets Reference - QMenu
Qt Style Sheets Examples - Customizing QMenu
I haven't tested this, but in theory, you may be able to use QMenu::item with either a Property Selector or a ID Selector (see Qt Style Sheet Syntax - Selectors). For example:
QMenu::item[text="Menu2 text"]
or
QMenu... |
5,094,502 | 5,094,570 | how do I write to stdout from an MFC program? | MFC programs can't normally write to stdout. MFC does something weird with the stdout/stdin pipes during startup and anything you write (for example doing a printf("hello");) just goes to /dev/null.
Does anyone know how to successfully write to stdout from an MFC program?
Thanks for reading.
| Use AllocConsole function to create a console for writing into. The following article explains how to use it to print to console.
Creating a console for your MFC app's debug output
Dont forget to FreeConsole once you're done with it.
|
5,094,577 | 5,094,723 | Official Definition of sscanf() Format String? | I'm implementing my own version of sscanf() in a different language (not C or C++).
I'm mostly finished. I'm just trying to wrap up some of the finer details of the meaning of the format string. However, searching the web, I'm finding that not all documentation for sscanf() is the same.
For example, some say %i handle ... | See ISO/IEC 9899:1999 7.19.6.2 (fscanf) - this is the last C standard
|
5,094,750 | 5,095,205 | Boost c++ serializing a char * | I have a class and I am trying to serialize a shared_ptr but the normal method of serializing an object is not working:
class Object {
public:
Object();
~Object();
shared_ptr<char>objectone;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive &ar, cons... | You are missing some key concepts. You don't need a share_ptr anymore if you use a std::string.
You can do
class Object {
public:
Object();
~Object();
std::string name;
template <typename Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & name;
}
};
and you a... |
5,094,877 | 5,095,059 | How can I compile c++ app for ipod/iphone under linux(debian) | How can I do this?
I search this info, about week, and all I find is this www.emdebian.org
I try to install g++ for arm platform on my PC, compile my app, copy it to my ipod, and it write "cannot execute binary file"
| IIRC, Apple uses a slightly different ARM binary format than the stock G++ does. I think you'll want to use LLVM-GCC or Clang.
|
5,094,890 | 5,095,223 | How to enable visual styles without a manifest | I am referring to this answer How to enable visual styles without a manifest
Doing what that answers says creates a .manifest and visual styles are enabled. However I don't want the manifest to be bounded with my .exe - I am delivering only my executable and would like everything bundled in there.
Is there a way to ena... | Use mt.exe to embed the manifest into the executable as a resource. This is a standard part of the build since VS2005, use a project template if you have trouble setting it up properly.
|
5,094,922 | 5,095,342 | How do I get outputs in Ruby using SWIG over a C function taking pointers to output arguments? | How do I get outputs (declared using int pointers) from a function I wrote in C++, using SWIG, in Ruby? In the transcript below, I'm declaring an 'a' and a 'b' just to get them initialized as integers, but really they're supposed to be outputs.
irb(main):001:0> require 'vetms.rb'
=> true
irb(main):002:0> a=3
=> 3
irb(m... | Hard to comment without the SWIG / vetms.rb code. Guessing you need to do some work with a typemaps.
I'd suggest using FFI instead of SWIG to interface your C code
https://github.com/ffi/ffi
much easier, and nicer
|
5,094,960 | 5,095,060 | typedef type checking? | How do I get g++ to make type checks on typedefs? Is it possible? i.e.
typedef int T1;
typedef int T2;
T1 x = 5; //Ok with me
T2 y = x; //Any way to get an error or a warning here?
I can't use C++0x features (I don't know whether they can do this.)
EDIT: What I want is something like this:
typedef int BallID;... | Consider using a strong typedef: https://www.boost.org/doc/libs/release/boost/serialization/strong_typedef.hpp
|
5,094,980 | 5,095,302 | Win32 UI - Making a control expand as the parent expands | I'm using a resource editor to design my UI (resedit), however I cant find an option to tell it to keep the width of a control (listview) the same as its parent control (dialog) - so that when I resize the dialog also the listview resizes.
Can I do this through the resource file or do I need to call some C/C++ function... | This is not automatic, you need to write some code to do it. Respond to the WM_SIZE message for the parent, determine how much the size changed, and resize the child by the same amount.
Functions that can resize a window are MoveWindow, SetWindowPos, and DeferWindowPos. DeferWindowPos is a lot more complicated but will... |
5,095,158 | 5,235,360 | Marshal C++ float to C# float accuracy problem | I have a DBase IV database. Each row has a memo field with a ASCII encoded string that holds two serialized borland c++ structures. I am able to pull the data using OleDb, re-encode it to ascii using the ASCIIEncoding class, convert it to bytes using a BinaryReader, and cast it to my C# struct using Marshal.PtrToStruc... | I wasn't able to solve the issue directly. The problem seemed to come from the OLE data provider I was using. The data retreived from the database was slightly different then what xBaseJ provided. I ended up converting xBaseJ to CLI bytecode using IKVM.NET. This allowed me to replace the OLE data provider with the x... |
5,095,206 | 5,095,265 | Returning garbage data from a classes private array | I have a class assignment where I have to write a program that will take a number from the user that is no more than 50 digits long. I have a class called Number that has an array called Value[50] used for holding the value of the number. The number length, as well as the use of arrays, is a requirement of the assignme... | You're not actually setting your values.
Value[NewNumberSize] = NumberValue % 10
That just sets the same element (the last element) to the new value, and uses that same value to cout the result as it's calculating it. count isn't used inside the loop. Additionally, You probably want to set values Value[NewNumberSize-1... |
5,095,284 | 5,095,438 | how to write path of external file in an included c++ source | Suppose I'm writing a library or a set of tools mytool where a class MyTool that other people can use is defined. Suppose I have a directory tree like this:
project
| - program1
| - main1.cpp
...
| - mytool
| - mytool.h
| - mytool.cpp
| - data.txt
in tool1.cpp I use the external binary huge file data.d... | You need to know the absolute path of the file, or else the path of the file relative to your working directory. One approach is to have a configuration script which the user runs before compiling your program. The script then hardcodes into your program the relevant path, so the program has the path hardwired in a man... |
5,095,407 | 5,097,100 | all combinations of k elements out of n | Can somebody provide me a link or pseudocode of a function for finding all combinations of k elements out of n? possibly in STL. I don't need to compute n choose k, I need to list all vectors of numbers of size k.
Thanks
| In C++ given the following routine:
template <typename Iterator>
inline bool next_combination(const Iterator first, Iterator k, const Iterator last)
{
/* Credits: Thomas Draper */
if ((first == last) || (first == k) || (last == k))
return false;
Iterator itr1 = first;
Iterator itr2 = last;
++itr1;
... |
5,095,426 | 5,097,704 | Different sizes of lambda expressions in VS2010? | Out of curiosity, I tested the size of a lamba expression. My first thought was, that they'd be 4 bytes big, like a function pointer. Strangely, the output of my first test was 1:
auto my_lambda = [&]() -> void {};
std::cout << sizeof(my_lambda) << std::endl;
Then I tested with some calculations inside the lambda, the... | Thanks to @Hans Passant's comment under the question, the solution was found. My original approach was wrong in the fact that I thought every object would be captured by the lambda, but that isn't the case, only those in the enclosing scope are, and only if they are used.
And for everyone of those captured objects, 4 b... |
5,095,434 | 5,095,750 | Warning : overflow in implicit constant conversion | In the following program, the line 5 does give overflow warning as expected, but surprisingly the line 4 doesn't give any warning in GCC: http://www.ideone.com/U0BXn
int main()
{
int i = 256;
char c1 = i; //line 4
char c2 = 256; //line 5
return 0;
}
I was thinking both lines should give overflow w... | -Wall doesn't include many options. -Wconversion is one of them and warns about the behavior you're interested in.
See http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
|
5,095,476 | 5,102,784 | Initialize variable shared beetween dlls | I all,
I have a win32 application and several DLLs that must use a global variable. In each dll I put
extern MYTYPE* myvariable = NULL;
and in the main program I have
MYTYPE* myvariable = NULL;
mavariable = new MYTYPE();
....
now, when the DLLs are loaded myvariable is NULL and I cannot use it. How can I share the in... | You should make some changes in your program. If it is possible you can just move myvariable from the EXE to one from DLL. Then you can continue to use import libraries.
It general you can export functions or data from an EXE, but in the most cases there are less sense to do this. So you can see this very seldom. For e... |
5,095,519 | 5,103,943 | How to use transactions in Informix CSDK and OIC++ | I'd need some advice how to handle transactions with Informix CSDK and OIC++.
conn is a open connection object. Select works find. The database here is setup with logging — as I found out while update stmt on its own does nothing.
Here's what I tried:
conn.SetTransaction( ITConnection::BEGIN );
qtext = ... | okay once again I answer myself...
from Informix C++ DocNotes
Operations can now be performed on large objects within a fetched row even though the connection is still checked out (locked). A connection is checked out after the ITQuery::ExecForIteration() method returns multiple rows in the result set. It remains check... |
5,095,536 | 5,179,631 | C++ library for drawing graphics | Someone can suggest me a good, free, easy to use library for c++ that allow to draw a mathematical function in a window for microsoft windows? (e.g. the parabola x^2+5x+3=0)
| Another wxWidgets-based option is wxArt2D, It has got tons of good features for drawing mathematical functions as curves, like you could easily pass this y=140*cos(x/20) + 80*cos(x*2/20) + 40*cos(x*4/20)" to a curve object and it will get drawn, it's amazing!
Check out these screenshots there are some curves drawn by e... |
5,095,683 | 5,095,756 | Floating point operations resulting in a number that is essentially zero | I'm doing some calculations that result in a value like {-0.707107, 9.61481e-017, 0.707107} when I'm expecting {-0.707107, 0, 0.707107}. Could that second component, while essentially zero, cause problems down the road? Should I do something about it? Using C++ doubles.
| That depends very much on what you intend to do down the road. :-) However, getting results that are very close to, but not exactly equal, to what the "mathematical" result should be, is something one must live with when using floating point numbers. A common solution is to define some "epsilon" value (say, 1e-10) and ... |
5,095,799 | 5,095,845 | why type casting doesn't work in here? | The following code has type casting error
#define IMG_I (std::complex<double>(0, 1))
#define PI 3.1415926535
for (unsigned long int j = 0; j < 10; ++j)
std::cout << exp(-IMG_I * PI * j);
The type casting can be easily solved by using extra parenthesis or changing the order of multiplication. But it is not clear for ... | This operator* overload for std::complex is a function template with a declaration that looks like:
template<typename T>
complex<T> operator*(const complex<T>& lhs, const T& val);
The T in complex<T> for the lhs argument must be the same as the T for the val argument in order for template argument deduction to work.... |
5,095,839 | 5,095,863 | Redirect FROM stderr to another file descriptor | My program calls library functions which print to stderr. I want to intervene so that all write calls to file descriptor #2 will instead get sent to somewhere else.
Here is my first attempt:
bool redirect_stderr (int fd)
{
return dup2 (2, fd) > 0;
}
Here, fd was successfully obtained from open("/foo/bar",O_APPEND|... | You reversed the arguments: it's
dup2(from_fd, to_fd)
i.e.
dup2(fd, 2)
(see POSIX.2008 or your manpages.)
|
5,095,852 | 5,096,567 | sharing opengl context on different displays using ubuntu | We have an application with multiple windows on different screens using 3 graphic cards. Each window uses opengl to render fonts, images etc...
This works very well so far, except for sharing resources. we tried to implement something like this (fenster is a custom class to store information like context, etc...):
//a... | From http://www.opengl.org/sdk/docs/man/xhtml/glXCreateContext.xml :
BadMatch is generated if the context to be created would not
share the address space or the screen of the context specified by shareList.
The spec wording suggests this should work if you have direct rendering contexts and they're all created by t... |
5,095,888 | 5,098,249 | Making boost::asio::ip::tcp::acceptor non-blocking | I've been trying to make a non-blocking TCP server of sorts using tcp::acceptor. I've done this before using BSD sockets and C(++) but unable to set non blocking I/O using boost.
C(++):
#ifdef WIN32
int mode = 1;
ioctlsocket(Socket, FIONBIO, (u_long FAR *) &mode);
#else
fcntl(Socket, F_SETFL, fcntl(Socket, F_GETF... | Since I'm actually refactoring old C++ code the accept() function (if could be set nonblocking) would fit quite nicely. I tried to avoid async functions due to the entire concept being unfamiliar to me:
tcp::socket *CTCPServer :: AsyncAccept( )
{
tcp::socket *Socket = new tcp::socket( *m_Service );
m_Socket.async_a... |
5,095,990 | 5,096,027 | What C++ library can I use to check disk quotas on linux? | Is there an easy to use library that I can use for checking disk quotas? I need to modify a piece of software I have to implement this functionality.
| Can't you just use quotactl?
int quotactl(int cmd, const char *special, int id, caddr_t addr);
|
5,096,069 | 5,096,120 | gTest and multiple main() | I have an Eclipse project. All testcases are in one *.cpp file. The problem is that this way I end up with two main() functions. One for the app itself and one for the testcases. And Eclipse, of course, refuses to build... I would like to keep everything together under one project (and avoid having multiple configurati... | Are you linking with libgtest_main in addition to libgtest? If you don't link in the libgtest_main you should be good.
If you want to create two executables with Eclipse CDT the easiest way is to have each executable have a separate project. You can have one project reference another if you have common code.
|
5,096,077 | 5,096,267 | Overridding QMessageBox::paintEvent() | I am creating a custom message box for an application. My object is derived from QMessageBox, but I am overriding the paintEvent() method in order to change its appearance. Curiously, although I do not call the base paintEvent method in my derived method, my custom message box is still being painted with an OK button... | The OK button is not being painted. It's a child QWidget added to the message box. Child widget painting is not controlled in the parent's paintEvent.
|
5,096,129 | 5,096,324 | STL algorithms and iterators instead of "for" loops | I guess that there should be someway to write the below piece of code without using "for" loops and by just using STL algorithms and iterators. If I am not wrong can anyone guide me on how to do this?
std::vector<double> A(N);
std::vector<double> B(N);
std::vector<double> C(N);
std::vector<double> D(N);
for(int i = 0;... | typedef boost::counting_iterator<int> counter;
std::transform(counter(0), counter(N), A.begin(), myFunction1);
std::transform(A.begin(), A.end(), counter(0), B.begin(), myFunction2);
std::transform(A.begin(), A.end(), B.begin(), C.begin(), myFunction3);
Now write your own version of std::transform that takes a ternar... |
5,096,232 | 5,099,933 | Pascal Triangle Recursive Program optimization in C++ | I have built recursive function to compute Pascal's triangle values.
Is there a way to optimize it?
Short reminder about Pascal's triangle: C(n, k) = C(n-1, k-1) + C(n-1, k)
My code is:
int Pascal(int n, int k) {
if (k == 0) return 1;
if (n == 0) return 0;
return Pascal(n - 1, k - 1) + Pascal(n - 1, k);
}
The ineff... | The following routine will compute the n-choose-k, using the recursive definition and memoization. The routine is extremely fast and accurate:
inline unsigned long long n_choose_k(const unsigned long long& n,
const unsigned long long& k)
{
if (n < k) return 0;
if (0 == n) ret... |
5,096,443 | 5,096,484 | about "static function" in c++,what is corresponding feature in Java | about "static function" in c++,what is corresponding feature in Java
Thank you
| You can declare a class method as static
public static int test(int i) {
...
}
|
5,096,881 | 5,101,557 | Does set_target_properties in CMake override CMAKE_CXX_FLAGS? | At the beginning of my CMake project, I'm setting general compilation flags in the variable CMAKE_CXX_FLAGS, like
set(CMAKE_CXX_FLAGS "-W -Wall ${CMAKE_CXX_FLAGS}")
Later on, I need to append additional configuration-specific compilation flags (stored in BUILD_FLAGS). Can I use the following command for this:
set_targ... | Use the first one:
set_target_properties(${TARGET} PROPERTIES COMPILE_FLAGS ${BUILD_FLAGS})
The flags stored in BUILD_FLAGS are appended after CMAKE_CXX_FLAGS when compiling the sources of TARGET. The documentation hints at this, but I've just tried it to make sure.
COMPILE_FLAGS
Additional flags to use when compi... |
5,096,923 | 5,097,116 | Problem with input in c++ | I have a very basic question i want to take integer input in certain range from user. if the user gives some string or char instead of integer. then my program goes to infinite loop.
my code is some what like that
cin >> intInput;
while(intInput > 4 || intInput < 1 ){
cout << "WrongInput "<< endl;
cin >> intIn... | The solution to this answer is to always read lines from the standard input.
std::string input; int value = 0;
do
{
// read the user's input. they typed a line, read a line.
if ( !std::getline(std::cin,input) )
{
// could not read input, handle error!
}
// attemp conversion of input... |
5,097,145 | 5,098,999 | OpenGL - mask with multiple textures | I have implemented masking in OpenGL according to the following concept:
The mask is composed of black and white colors.
A foreground texture should only be visible in the white parts of the mask.
A background texture should only be visible in the black parts of the mask.
I can make the white part or the black part w... | This should work:
glEnable(GL_BLEND);
// Use a simple blendfunc for drawing the background
glBlendFunc(GL_ONE, GL_ZERO);
// Draw entire background without masking
drawQuad(backgroundTexture);
// Next, we want a blendfunc that doesn't change the color of any pixels,
// but rather replaces the framebuffer alpha values wi... |
5,097,282 | 5,099,310 | Why does this dynamic library loading code work with gcc? | Background:
I've found myself with the unenviable task of porting a C++ GNU/Linux application over to Windows. One of the things this application does is search for shared libraries on specific paths and then loads classes out of them dynamically using the posix dlopen() and dlsym() calls. We have a very good reason fo... | As aschepler says, its because you got lucky.
As it turns out, the ABI used for gcc (and most other compilers) for both x86 and x64 returns 'large' structs (too big to fit in a register) by passing an extra 'hidden' pointer arg to the function, which uses that pointer as space to store the return value, and then return... |
5,097,411 | 5,130,257 | std::string messed up when using it as storage within (boost.)async_read_some | I am using async_read_some to read data from a port that is saved in a char[] called _data. Its buffer size is big enough for every request:
void start() {
socket_.async_read_some(boost::asio::buffer(data_,BUFFERSIZE),make_custom_alloc_handler(allocator_,boost::bind(&attentionSession::handle_read, shared_from_this... | Well, the problem wasn't Boost nor Boost::Asio. It was the method how I tested my application:
I used nc (Netcat) to test the performance and functions of my application with this command
nc localhost 4450 <testfile
where testfile contained a 36 characters long test string. Netcat wasn't only slow - it was the origin ... |
5,097,488 | 5,097,532 | C++ registry handling without .NET | For a script that will check/set a Windows registry value. No GUI.
Am writing in Visual Studio, but do not want .NET - just C++.
However, I haven't figured out where and what methods exist natively in C++ [NOT Visual C++]
that interface with the registry.
I also haven't worked out how to compile C++ code in Visual Stud... | To create a native C++ console application in VS 2010: http://msdn.microsoft.com/en-us/library/46e82t5z.aspx
To check/set registry values using Win32 APIs: http://msdn.microsoft.com/en-us/library/ms724875%28v=VS.85%29.aspx
|
5,097,545 | 5,097,714 | Are empty constructors always called in C++? | I have a general question, that may be a little compiler-specific.
I'm interested in the conditions under which a constructor will be called. Specifically, in release mode/builds optimised for speed, will a compiler-generated or empty constructor always be called when you instantiate an object?
class NoConstructor
{ ... | When in optimizing mode, if your class or structure is POD (has only POD types) and constructor is not specified, any production quality C++ compiler will not only skip the call to a constructor but not even generate it.
If your class has non-POD members who's constructor(s) have to be called, compiler will generate de... |
5,097,573 | 5,184,278 | Saving as Flash in C++ | How to save an IPLImage of OpenCV as a Flash file? Maybe there is a library that does that?
| If you mean storing your output as a flash video (.flv) just use ffmpeg (libavcodec/libavformat). It is cross platform and supports the .flv format (besides a massive amout of others) and should be quite easy to do. You can embed audio too.
As a note: ffmpeg is partially included in opencv (depending on your build) as ... |
5,098,036 | 5,098,951 | How can I obfuscate/de-obfuscate integer properties? | My users will in some cases be able to view a web version of a database table that stores data they've entered. For various reasons I need to include all the stored data, including a number of integer flags for each record that encapsulate adjacencies and so forth within the data (this is for speed and convenience at ... | Why not convert each of the fields to hex, and append them as a string and save that value?
As long as you always append the strings in the same order, breaking them back apart and converting them back to numbers should be trivial.
|
5,098,069 | 5,098,145 | Why does std::forward discard constexpr-ness? | Being not declared constexpr, std::forward will discard constexpr-ness for any function it forwards arguments to. Why is std::forward not declared constexpr itself so it can preserve constexpr-ness?
Example: (tested with g++ snapshot-2011-02-19)
#include <utility>
template <typename T> constexpr int f(T x) { return -1... | The general answer is that the C++ committee's Library Working Group have not done an exhaustive trawl through the working draft looking for opportunities to use the new core facilities. These features have been used where people have had the time and inclination to look at possible uses, but there is not the time for ... |
5,098,125 | 5,098,933 | Editing listview control item | How do you add or edit listview item by double clicking on it?
| Two things. First, you have to create the List view control with the LVS_EDITLABELS style, as shown in Using List-View Controls.
Then, when you want to edit the label, you send the LVM_EDITLABEL message to the focused label.
Be sure to handle the LVN_ENDLABELEDIT message in the parent.
|
5,098,185 | 5,098,401 | How can I assign clipboard text to a variable in c++? | I've written a program that highlights numbers and copies them. I would like to be able to do some basic math with the copied text, such as multiplication or addition, but I can't figure out how to assign the clipboard data to a variable. Basically, I would like to be able to copy a number, assign it to variable "a", t... | The text content of the clipboard is a c-string pointed to by c.
if(OpenClipboard(NULL) != FALSE)
{
HANDLE clip0 = GetClipboardData(CF_TEXT);
if(clip0 != NULL)
{
char *c = reinterpret_cast<char*>(GlobalLock(clip0));
// Use c before it goes out of scope
...
GlobalUnlock(clip0);
}
CloseClipboar... |
5,098,373 | 5,098,498 | OO design, table design | Design table with wood or steel meterial. I have following designed, which is better and why? Or any better suggestion design?
design 1 :
class Meterial{
public:
void virtual info()=0;
};
class Wood:public Meterial{
public:
void info();
};
void Wood::info(){
cout<<"wood"<< " ";
}
class Steel:public Meterial{
p... | You should only use inheritance when you have a very specific reason to, or when all other options are not better nor worse. Never inherit for reuse.
Does material have any behaviour that can change dynamically? Can the table's material change at runtime? If the answer is yes to either of these then you'll likely need ... |
5,098,797 | 5,098,831 | C++ Using pointers to template objects | I have a class named ABC which has a class template:
template <class T> class ABC{}
In another class I am trying to store of objects ABC in a list:
class CDE{
private:
list<ABC *> some_list;
}
I intend to store objects of ABC which might have different class template parameters. Is it necessary to specify template... |
Is it necessary to specify template even for a pointer at compile time ?
Yes.
What if the container is supposed to store objects of different type ? Is that not possible ?
It is not (directly) possible.
There is no such thing as the class ABC. There are only instantiations of ABC, such as ABC<Foo> and ABC<Bar>. T... |
5,098,887 | 5,099,401 | Visual C++ 2010 Express: How to use with Qt? | I'm confused about getting Qt working with Visual Studio Express. Most of the searches online have turned up instructions for compiling Qt using instructions such as:
Install MSVC2005 or MSVC2008
Install the most recent Platform SDK (@ MSDN: "Platform SDK for Windows
Server 2003 R2")
From the Platform SDK, you'll ... | Using the downloadable exe from qt (http://get.qt.nokia.com/qt/source/qt-win-opensource-4.7.1-vs2008.exe) does not seem to work with Visual Studio 2010. I tried building a simple hello world program from the command line which would not run. I'll repeat my comment from a previous answer.
I tried the hello world exam... |
5,099,053 | 10,791,582 | How do I specify the .DLL search path for an MFC .EXE? | How do I specify the .DLL search path for an MFC .EXE? It would need to be a relative path, not absolute. Is this what the Manifest File is for?
| THERE IS NO ANSWER
In order for my "answer rate" to be acceptable to those out there who only look at numbers (not the actual answers), I'm answering my own long-outstanding-unanswered questions as "there is no answer" (if one shows up, I'll definitely choose their answer as THE answer).
|
5,099,206 | 5,099,324 | Info.plist value as C++ #define | In a C++ iOS project (or any other Mac OS), is there a simple way of making a value available both to the Info.pList settings, and to the code in the form of a preprocessor macro?
Ideally, I would like to have something like this
C++ code:
#define MY_VERSION_STRING "1.0"
Info.pList
CFBundleVersion: ${MY_VERSION_STRING... | Probably not the best solution, but you could use the /usr/libexec/PlistBuddy utility in a build script to generate a .h file containing a define with a value extracted from the plist.
To output a value from a plist:
/usr/libexec/PlistBuddy -c 'Print :Path:To:Key' filename.plist
|
5,099,337 | 5,099,373 | Finding all paths down stairs? | I was given the following problem in an interview:
Given a staircase with N steps, you can go up with 1 or 2 steps each time. Output all possible way you go from bottom to top.
For example:
N = 3
Output :
1 1 1
1 2
2 1
When interviewing, I just said to use dynamic programming.
S(n) = S(n-1) +1 or S(n) = S(n-1) ... | You can generalize your recursive function to also take already made moves.
void steps(n, alreadyTakenSteps) {
if (n == 0) {
print already taken steps
}
if (n >= 1) {
steps(n - 1, alreadyTakenSteps.append(1));
}
if (n >= 2) {
steps(n - 2, alreadyTakenSteps.append(2));
}
}... |
5,099,429 | 5,113,135 | How to use std::tuple types with boost::mpl algorithms? | The boost::mpl algorithms seem not to be able to work on std::tuple types out of the box, e.g., the following does not compile (boost-1.46.0, g++ snapshot 2011-02-19):
#include <tuple>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/contains.hpp>
namespace mpl=boost::mpl;
typedef mpl::vector<int,float,bool> types... | Converting from std::tuple to boost types and back seems to be the easiest way
#include <iostream>
#include <tuple>
#include <type_traits>
#include <boost/mpl/if.hpp>
#include <boost/mpl/not.hpp>
#include <boost/mpl/vector.hpp>
namespace mpl = boost::mpl;
template<typename Sequence, typename T>
struct push_front;
te... |
5,099,493 | 5,099,513 | Overloading [] operator in C++ | Im trying to overload the [] operator in c++ so that I can assign / get values from my data structure like a dictionary is used in c#:
Array["myString"] = etc.
Is this possible in c++?
I attempted to overload the operator but it doesnt seem to work,
Record& MyDictionary::operator[] (string& _Key)
{
for (int i = 0; i ... | Your code is on the right track - you've got the right function signature - but your logic is a bit flawed. In particular, suppose that you go through this loop without finding the key you're looking for:
for (int i = 0; i < used; ++i)
{
if (Records[i].Key == _Key)
{
return Records[i];
}
}
If thi... |
5,099,669 | 5,099,675 | invalid conversion from `void*' to `char*' when using malloc? | I'm having trouble with the code below with the error on line 5:
error: invalid conversion from void* to char*
I'm using g++ with codeblocks and I tried to compile this file as a cpp file. Does it matter?
#include <openssl/crypto.h>
int main()
{
char *foo = malloc(1);
if (!foo) {
printf("malloc()");
... | In C++, you need to cast the return of malloc()
char *foo = (char*)malloc(1);
|
5,099,769 | 5,101,759 | Regarding lvalue-to-rvalue conversion, when is it required? | I've been reading quite many on the Internet and it seems that many people mentioned the following rules (but i couldn't find it in the standard),
The addition operator + (and all other binary operators) requires both operands to be rvalue, and the result is rvalue.
And so on..
I checked the C++ standard, and it clearl... | So, this is generally one of those inferred and ill-specified parts of the standard; However, in 3.10
[ Note: some built-in operators expect lvalue operands. [ Example: built-in assignment operators all expect their left-hand operands to be lvalues. — end example ] Other built-in operators yield rvalues, and some exp... |
5,099,967 | 5,100,049 | How to obtain a pointer out of a C++ vtable? | Say you have a C++ class like:
class Foo {
public:
virtual ~Foo() {}
virtual DoSomething() = 0;
};
The C++ compiler translates a call into a vtable lookup:
Foo* foo;
// Translated by C++ to:
// foo->vtable->DoSomething(foo);
foo->DoSomething();
Suppose I was writing a JIT compiler and I wanted to obtain the a... | Why do you think &DerivedFoo::DoSomething is different? Isn't this exactly what you're asking for? The way I think about it, any call to DerivedFoo::DoSomething() will call the same function, passing a different this pointer. The vtable merely distinguishes between different types derived from Foo, not instances.
|
5,100,015 | 5,117,641 | C++ metafunction to determine whether a type is callable | Is it possible to write a C++(0x) metafunction that determines whether a type is callable?
By callable type I mean a function type, function pointer type, function reference type (these are detected by boost::function_types::is_callable_builtin), lambda types, and any class with an overloaded operator() (and maybe any ... | The presence of a non-templated T::operator() for a given type T can be detected by:
template<typename C> // detect regular operator()
static char test(decltype(&C::operator()));
template<typename C> // worst match
static char (&test(...))[2];
static const bool value = (sizeof( test<T>(0) )
The presence of a templa... |
5,100,283 | 5,100,290 | How do I setup visual studio to register some #defines globally? | What I mean is, in each of my source files I have to insert #define NOGDI to stop windows.h from including GDI defines (since it's BITMAP define conflicts with mine).
e.g.
#define NOGDI
#include <windows.h>
Unfortunately, I have to do this in every seperate source file which includes windows.h, which I do not want to ... | Project Settings -> C/C++ -> Preprocessor -> Preprocessor definitions
Here you can define symbols that are applied globally to all source code in your project.
|
5,100,451 | 5,100,719 | C++ using statement in member function scope | If I want to use a member of a template base class from a template derived class, I have to bring it into scope as such:
template <typename T>
struct base
{
void foo();
};
template <typename T>
struct derived : base<T>
{
using base<T>::foo;
};
Why can't I place this using statement into a local scope, like ot... | The standard (draft 3225) says in [namespace.udecl]:
A using-declaration for a class member shall be a member-declaration. [ Example:
struct X {
int i;
static int s;
};
void f() {
using X::i; // error: X::i is a class member
// and this is not a member declaration.
using X::... |
5,100,480 | 5,100,574 | member binary operator and nonmember binary operator in operator overloading | While trying to learning operator overloading, I read the following statements from C++ Primer. Frankly speaking, I do not quite understand what does the message that these statements want to deliver. The examples include defining both member binary operator and nonmember binary operator. Is there any difference when u... | Yes, there is a difference in actual use. In particular, when you overload an operator as a non-member function, conversions can be applied to either operand (or both operands). When you overload a binary operator with a member function, conversions can only be applied to the right operand.
This can lead to some odditi... |
5,100,718 | 5,100,745 | Integer to hex string in C++ | How do I convert an integer to a hex string in C++?
I can find some ways to do it, but they mostly seem targeted towards C. It doesn't seem there's a native way to do it in C++. It is a pretty simple problem though; I've got an int which I'd like to convert to a hex string for later printing.
| Use <iomanip>'s std::hex. If you print, just send it to std::cout, if not, then use std::stringstream
std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );
You can prepend the first << with << "0x" or whatever you like if you wish.
Other manips of interest are std::oct (octal) ... |
5,100,779 | 5,101,018 | Code (C++) to html converter for Forums | I have searched for quite some time and was unable to find a program that is able to convert code to html quickly for use in forums, but not web-pages, in which case it cannot use style-sheets and does not output (or has the option to turn off) all extraneous tags such as html, body etc. Does it exist? If not, then I k... | I finally found one that does exactly what I want it to do. The reason it was not showing up easily in search results is due to its name, Source to Html (instead of Code to Html).
http://www.newty.de/lsc/
Hope this helps someone in the future.
|
5,100,866 | 5,100,896 | Template << and >> operators specialization | I want to template the >> and << operators in a class, but I would also like to specialize them for strings, so I did this;
class sql_command
{
public:
sql_command() { }
explicit sql_command(std::string& cmd)
: m_raw(cmd) {
}
inline sql_command& operator<<(const char * arg)
{
m... | You don't need to specialize the operator template: just write an overload taking a std::string:
class sql_command {
/* ... */
template<typename T>
sql_command& operator>>(const T& arg) {
/* general purpose implementation */
}
sql_command& operator>>(const std::string& arg) {
/... |
5,100,958 | 5,100,982 | C++ Homework: Parallel Arrays from text file | I have to load three arrays from a text file for homework and I can't figure out why it isn't working. This is what the text file look like:
Jean Rousseau
1001 15.50
Steve Woolston
1002 1423.20
Michele Rousseau
1005 52.75
Pete McBride
1007 500.32
It's a name on one line, then an id number and a balance due on the ne... | inFile >> idsAr[indexCount];
inFile.ignore(1000, '\n');
You read the first number from the line, then you ignore all the characters until the end of the line, including the second number. You then try to read the next name as if it were a number, and since you aren't doing any error checking, everything goes wrong.
T... |
5,101,009 | 5,101,039 | Can I write a dynamic tree structure in C++? | I need a tree with n branches in C++, What is the best way to code this? Or where can I find a implementation?
| This is one option, this is another, and finally this.
|
5,101,182 | 5,101,304 | What is SAL_CALL in c++? | can any one explain me briefly.
What is SAL_CALL in c++?
| It's a #define used in OpenOffice.org. It's defined in sal/inc/sal/types.h as one of:
#define SAL_CALL
#define SAL_CALL __cdecl
depending on the platform being compiled for. It looks like it's set to the latter only when _MSC_VER (for Microsoft) is defined.
It's used when specifying functions like:
virtual void SAL_CA... |
5,101,516 | 5,101,566 | Why function template cannot be partially specialized? | I know the language specification forbids partial specialization of function template.
I would like to know the rationale why it forbids it? Are they not useful?
template<typename T, typename U> void f() {} //allowed!
template<> void f<int, char>() {} //allowed!
template<typename T> void f<char, T>() ... | AFAIK that's changed in C++0x.
I guess it was just an oversight (considering that you can always get the partial specialization effect with more verbose code, by placing the function as a static member of a class).
You might look up the relevant DR (Defect Report), if there is one.
EDIT: checking this, I find that othe... |
5,101,570 | 5,101,714 | Remove spinning ball when hidden application start | I have created a program in c++ that doesn't have any GUI. When this program stars windows shown a spinning ball for about 5 seconds.
Is there any way to remove this?
| I'm not completely sure, but I think it goes away if you create a top-level window. Most Windows applications intended to run from the GUI, should create a top-level window, even if they aren't intending to make it visible (Don't call ShowWindow ).
Also, you probably want to recieve some types of notifications which Wi... |
5,101,903 | 5,101,925 | Problem building Festival (Text to Speech) on Ubuntu | I set up a Ubuntu VM today just to build Festival on Ubuntu (I never ran it before) Then I did the following setups
On the Terminal window I wrote following to install GNU C++ Compiler
sudo apt-get install build-essential
To test the g++ I wrote a sample hello world and compiled it using g++ and run it and it worked ... | You probably need to install the development packages for libncurses. Try
sudo apt-get install libncurses5-dev
|
5,101,997 | 5,102,174 | C++ sorting numbers from smallest to biggest | If I have the user enter 10 random numbers and I want to order them from smallest to biggest what is the best method to do this using the most basic C++ language.
| #include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
vector<int> vec;
vec.push_back(1);
vec.push_back(4);
vec.push_back(3);
vec.push_back(2);
sort( vec.begin(), vec.end() );
for (vector<int>::const_iterator it=vec.begin(); it!=vec.end(); ++it) {
... |
5,102,038 | 5,103,021 | How can I pass boost::shared_ptr as a pointer to a Windows Thread function? | How can I pass boost::shared_ptr as a pointer to a Windows Thread function ?
assume following code :
test::start()
{
....
_beginthreadex( NULL, 0, &test::threadRun, &shared_from_this(), 0, &threadID );
...
...
}
/*this is a static function*/
UINT __stdcall test::threadRun( LPVOID lpParam )
{
sha... | I solved my problem by boost::weak_ptr:
test::start()
{
....
shared_ptr<test> shPtr = shared_from_this();
boost::weak_ptr<test> wPtr=shPtr;
_beginthreadex( NULL, 0, &test::threadRun, &wPtr, 0, &threadID );
...
...
}
/*this is a static function*/
UINT __stdcall test::threadRun( LPVOID lpParam )... |
5,102,222 | 5,102,314 | C instruction is being reordered when cin cout and gets is used consecutively | Does anyone knows why C instruction is being reordered when cin cout and gets is used consecutively here?
I am using Dev-C++ 4.9.9.2.
#include<iostream>
using namespace std;
int main(){
char a[10],b;
for(;;){
cout<<"\ncin>>b:";
cin>>b;
cout<<"gets(a):";
gets(a);
cout<<"c... | cin>>b read just a character, leaving the rest of the input to be read by later input operation. So gets sill has something to read and don't block.
At the first cin >> b, there is no input available. You enter '132\n' (input from terminal is usually made line by line) in a buffer and just get the 1 out of it. gets ... |
5,102,277 | 5,105,735 | Resizing an image using OpenGL | I'd like to resize an image using OpenGL. I'd prefer it in Java, but C++ is OK, too.
I am really new to the whole thing so here's the process in words as I see it:
load the image as a texture into OGL
set some stuff, regarding state & filtering
draw the texture in different size onto another texture
get the texture da... | Instead of rendering a quad into the destination FBO, you can simply use hardware blit functionality: glBlitFramebuffer. Its arguments are straight forward, but it requires a careful preparation of your source and destination FBO's:
ensure FBO's are complete (glCheckFramebufferStatus)
set read FBO target and write FBO... |
5,102,436 | 5,102,904 | How to marshal collection in c# to pass to native (C++) code | I am working on an enterprise application development. the entire application is developed in c++, except the UI, which is developed in c#, now its time to hookup the UI with c++ code. After detailed study i choose PInvoke in order to do so.
All is successful, the only case where i stuck is that how can i pass collecti... | As mzabsky mentioned, you cannot marshal these types. You can, however, marshal an array:
The theoretical C++ export:
extern "C" __declspec(dllexport) void __stdcall Foo(wchar_t const* const* values, int length)
{
// Check argument validity...
// If you really need a vector
std::vector<std::wstring> vStr(... |
5,102,645 | 5,103,665 | Outputting Three Arrays to a File Based on the Contents of Another Array | I have an array that keeps track of the results of a search of three parallel arrays. The parallel arrays are names, id#s, and balances. A name is associated with an id and balance because they all have the same index. The user searches for names and the program is supposed to output the search results to a text file w... | My pleasure. Now i see what you are doing. What you have to do is use another indirection. You want to output the result only for those indices which are stored in resultsAr.
Change your for-loop to something similar to this:
int numFound = index;
for(index = 0; index < numFound; index++) {
cout << left << " "<<i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.