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 |
|---|---|---|---|---|
2,705,141 | 2,705,165 | how to back to the first of text file | i have a txt file which have some lines ...and my code is :
string line;
ifstream myfile("c:\\main.txt");
bool passport = true;
while(passport==true){
int pos1=0;
cout<<setw(20)<<"PassPort_Number : ";
cin>>add.Id ;
if (myfile.is_open())
{
while(!myfile.eof()){
getline(myfile,l... | Call:
myfile.seekg(0, ios::beg);
to set the file read pointer back to the beginning.
|
2,705,173 | 2,705,316 | Designing a state machine in C++ | I have a little problem that involves modeling a state machine.
I have managed to do a little bit of knowledge engineering and 'reverse engineer' a set of primitive deterministic rules that determine state as well as state transitions.
I would like to know what the best practices are regarding:
How to rigorously test ... | Be sure to take a look at the Boost Statechart Library.
|
2,705,181 | 2,705,453 | Compile/use unrar C++ source for iphone app? | Writing an app that will include the ability to decompress zip and rar files. I think I'm OK on how to handle the .zips but .rars seem a little more trouble. I noticed that rarlabs has source available but it's C++. Is there a way to compile, wrap or otherwise use this code within an iPhone app?
Reference: http://www.r... | If all you need is to decompress RAR files, this library may be much easier for you to compile since it's a single C source file:
http://www.unrarlib.org/features.html
I had looked at compiling the library you mentioned, but there were a lot of errors and it was not initially apparent just how to resolve some of them (... |
2,705,183 | 2,705,209 | struct constructor + function parameter | I am a C++ beginner. I have the following code, the reult is not what I expect. The question is why, resp. what is wrong. For sure, the most of you see it at the first glance.
struct Complex {
float imag;
float real;
Complex( float i, float r) {
imag = i;
real = r;
}
Complex( float r... | You can't call one constructor in the body of another one like that:
Complex( float r) {
Complex(0, r);
}
In C++ it creates a temporary object of class Complex which immediately gets destroyed.
You could use default parameters in the constructor or some private method that would be called by constructors
|
2,705,269 | 2,705,276 | Why size_t arguments in template declaration need to be const? | I can have
std::bitset< 10 > bitsetA;
or
const size_t LengthB = 20;
std::bitset< LengthB > bitsetB;
without any problem.
But, if the length is not const
size_t LengthC = 30;
std::bitset< LengthC > bitsetC; // Line 30, say
I face the following compilation error
'LengthC' cannot appear in a constant-expression
t... | Template arguments have to be declared const at compile time so that the template can be instantiated at compile time.
In the example you give, it does indeed appear that LengthC isn't going to change from the point where it is initialized to the point where the template has to be instantiated, so it could be treated a... |
2,705,439 | 2,705,448 | Where does abort() and terminate() "live"? | Regarding the terminate handler,
As i understand it, when something bad happens in code, for example when we dont catch an exception,
terminate() is called, which in turn calls abort()
set_terminate(my_function) allows us to get terminate() to call a user specified function my_terminate.
my question is: where do these ... | If there are default handler functions for terminate and abort that you did not install yourself, they'd have to be in the runtime library provided by your compiler.
Normally, every program is linked against the runtime library (e.g. glibc under Linux). Among other reasons, this is because the runtime library contains ... |
2,705,442 | 2,705,525 | Debugging MinGW program with gdb on Windows, not terminating at assert failure | How do I set up gdb on window so that it does not allow a program with assertion failure to terminate? I intend to check the stack trace and variables in the program.
For example, running this test.cpp program compiled with MinGW 'g++ -g test.cpp -o test' in gdb:
#include <cassert>
int main(int argc, char ** argv) { a... | Just set a breakpoint on exit:
(gdb) b exit
|
2,705,459 | 2,705,572 | 1>Project : error PRJ0003 : Error spawning 'rc.exe' | 1>Project : error PRJ0003 : Error spawning 'rc.exe'.. this is the error i get when i try to run this small practice program of reading and writing files which i cant do because of the reason of me not being able to get the files to open correctly. i use microsoft visual c++ 2008 and i have used the file path to try to... | There's something wrong with your setup of Visual Studio, it should never have any trouble finding and running rc.exe. First thing to check if the file is there. It should be located in c:\program files\microsoft sdks\windows\v6.0a\bin\rc.exe.
Next thing to check is that the paths are set properly. Tools + Options, ... |
2,705,554 | 2,705,898 | runtime library and global namespace | Does the runtime library pollute the global namespace?
| The runtime library is required to use reserved identifiers. Without namespace qualification, these must begin with two underscores: __start, etc.
You are not allowed to use reserved names. The library is not allowed to use your names. If either crosses over to the other, it is "pollution" which is illegal.
Essentially... |
2,705,701 | 2,705,710 | My First Go With Function Templates | Thought it was pretty straight forward.
But I get a "iterator not dereferencable" errro when running the below code.
What's wrong?
template<typename T>
struct SumsTo : public std::binary_function<T, T, bool>
{
int myInt;
SumsTo(int a)
{
myInt = a;
}
bool operator()(const T& l, const T& r)
... | Your functor is fine. The problem is in the call to transform.
Transform has the prototype
transform(_InputIterator1 __first1, _InputIterator1 __last1,
_InputIterator2 __first2, _OutputIterator __result,
_BinaryOperation __binary_op)
your call is
transform(l1.begin(), l1.end(), l2.begin(), l2.end()... |
2,705,780 | 2,705,830 | How to use length indicator in a C++ program | I want to make a program in C++ that reads a file where each field will have a number before it that indicates how long it is.
The problem is I read every record in object of a class; how do I make the attributes of the class dynamic?
For example if the field is "john" it will read it in a 4 char array.
I don't want to... | In order to do this, you need to use dynamic allocation (either directly or indirectly).
If directly, you need new[] and delete[]:
char *buffer = new char[length + 1]; // +1 if you want a terminating NUL byte
// and later
delete[] buffer;
If you are allowed to use boost, you can simplify that a bit by using boost::... |
2,705,927 | 2,706,223 | Get specific process memory space | I have a pointer (void *) to a function and I want to know which process this function belongs to. I have no idea which way to go about it, but I think it's possible by using some form of VirtualQuery trickery. Any help would be appreciated.
Thanks in advance,
CLARIFICATION: By "belong to process" I mean what process t... | The hijacked function pointer in the VTable can only be inside your process, as the other folks have already answered. The memory address only makes sense for your process. If someone is going to overwrite one of your VTable spots, then they would first have to hook something your process, which means running code in... |
2,706,009 | 2,706,013 | C++: namespace conflict between extern "C" and class member | I stumbled upon a rather exotic c++ namespace problem:
condensed example:
extern "C" {
void solve(lprec * lp);
}
class A {
public:
lprec * lp;
void solve(int foo);
}
void A::solve(int foo)
{
solve(lp);
}
I want to call the c function solve in my C++ member function A::solve. The compiler is not... | To call a function in the global namespace, use:
::solve(lp);
This is needed whether the function is extern "C" or not.
|
2,706,040 | 2,706,053 | 'Scanner' does not name a type error in g++ | I'm trying to compile code in g++ and I get the following errors:
In file included from scanner.hpp:8,
from scanner.cpp:5:
parser.hpp:14: error: ‘Scanner’ does not name a type
parser.hpp:15: error: ‘Token’ does not name a type
Here's my g++ command:
g++ parser.cpp scanner.cpp -Wall
Here's parser.hpp:
#... | parser.hpp incluser scanner.hpp and vice versa.
So one file evalated before the other.
You can use a forward declaration like
class Scanner;
or reorginaze your headers
|
2,706,076 | 2,706,145 | new >> how would i read a file that has 3 columns and each column contains 100 numbers into an array? | int exam1[100];// array that can hold 100 numbers for 1st column
int exam2[100];// array that can hold 100 numbers for 2nd column
int exam3[100];// array that can hold 100 numbers for 3rd column
int main()
{
ifstream infile;
int num;
infile.open("example.txt");// file containing numbers in 3 columns
... | int exam1[100];// array that can hold 100 numbers for 1st column
int exam2[100];// array that can hold 100 numbers for 2nd column
int exam3[100];// array that can hold 100 numbers for 3rd column
int main() // int main NOT void main
{
ifstream infile;
int num = 0; // num must start at 0
infile.open("exam... |
2,706,112 | 2,706,121 | C++ Exact difference between having myMethod(Thing& a) or myMethod(Thing a)? | What is the exact difference between having myMethod(Thing& a) or myMethod(Thing a)? Because later you still ned to use &a if you want the address of the object.. I'm not sure when to use what..
| Three differences:
With a reference, you have a "shared" instance. So if you modify a you change the original and vice versa.
Performance. With Thing a you invoke the copy constructor. If the copy constructor has to do a lot of things, that could affect how fast the code runs.
A reference is guaranteed to work. If... |
2,706,129 | 2,706,136 | Can a c++ class include itself as an member? | I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython.
I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free.
I plan to implement an expression tree, and a method to evaluate it in postfix order.
The problem I run into right away is:
class Node {
char... | No, because the object would be infinitely large (because every Node has as members two other Node objects, which each have as members two other Node objects, which each... well, you get the point).
You can, however, have a pointer to the class type as a member variable:
class Node {
char *cargo;
Node* left; ... |
2,706,132 | 2,706,189 | Handling Messages in Console Apps/DLLs in C++ Win32 | I would like to have the ability to process Win32 messages in a console app and/or inside a standalone DLL.
I have been able to do it in .NET with the following article and it works great in C# inside a console app and standalone DLL
http://msdn.microsoft.com/en-us/magazine/cc163417.aspx
Is there a way to do the equiva... | You need a message pump yes. The window also has thread affinity so it needs to be created on the same thread that you're running the message pump on. The basic approach is sound, if you include more code it may become clear what the problem is.
|
2,706,198 | 2,706,230 | how to pass an array into an function and in the function count how many numbers are in a range? | #include <iostream>
#include <fstream>
using namespace std;
int calculate_total(int exam1[], int exam2[], int exam3[]); // function that calcualates grades to see how many 90,80,70,60
int exam1[100];// array that can hold 100 numbers for 1st column
int exam2[100];// array that can hold 100 numb... | use a vector.
you can initialize a vector like an array.
the vector has a method to give you the number of elements
|
2,706,245 | 2,706,312 | read pair of characters separated by \t c++ | Friends,
I want to read a pair of characters separated by \t. I want to continue reading the input until user enters z for any of the characters.
Here are the options I thought:
while (cin>>ch1>>ch2)
{
// process ch1 & ch2
}
std::string str;
while (getline(cin, str) ){
//split string
}
Also, I want to validate t... | Despite its name, you can use std::getline() to read other things than lines. It takes an optional third parameter denoting the delimiter. The default one is '\n', but there's no reason you cannot use '\t' instead.
std::string line;
while( std::getline(is,line) ) { // read lines
std::istringstream iss(line);
std:... |
2,706,277 | 2,706,298 | error C2146: syntax error : missing ';' before identifier 'vertices' | I would usually search for this error. But in VS C++ Express, this error comes up for just about every mistake you do. Any how I recieve this error below
error C2146: syntax error : missing ';' before identifier 'vertices'
everytime I add the following code at the top of my document
// Create vertex buffer
SimpleVert... |
error C2146: syntax error : missing ';' before identifier 'vertices'
Usually this error occurs when what's before the identifier isn't known to the compiler. In your case that means the compiler hasn't seen SimpleVertex yet.
|
2,706,296 | 2,706,305 | Use boost library in cocoa project | It is theoretically possible to use a boost library (e.g. boost threads) inside a cocoa project?
| Yes, there is nothing stopping you from doing that:
you can mix Objective-C and C++ - the result is called Objective-C++
you can of course also link to C and C++ libraries
|
2,706,357 | 2,706,383 | pop3 multiline problem | i'm making a client for pop3 and somehow i can't figure out how to handle multiline responses. There is no difference in the response from server whether it is single or multiline, it always ends with CRLF (considering the usual case) so how do I know if I should call recv() once more?
| Responses that can span more than one line (such as the contents of an email) are identified as such in the POP3 RFC.
The last line of a multi-line response just contains a dot "."
So look for "\r\n.\r\n"
That last line is a termination mark. It's not part of the actual message.
|
2,706,444 | 2,706,458 | error C2440: 'initializing' : cannot convert from 'const wchar_t [9]' to 'LPCSTR' | When I add the following to my code.
// Define the input layout
D3D10_INPUT_ELEMENT_DESC layout[] =
{
{ L"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = sizeof(layout)/sizeof(layout[0]);
I get the following error
1>c:\users\numerical25\desktop\intro tod... | The problem is that first element of D3D10_INPUT_ELEMENT_DESC needs a const char *, not a const wchar_t *. Just remove the L before the string.
|
2,706,495 | 2,706,504 | Use older version of MSVCR? | I have VS 2008 and I want my application to work with Windows 98 without needing to include MSVCR90.dll .. Win98 comes with MSVCR60 so how could I tell MSVC to do this? Is my only option to hunt down Visual studio 6?
Thanks
*also I want to avoid static linking msvcr
| You can't tell Visual Studio to use an earlier version of the runtime library. Even if you can get it to compile with the old library, the application itself is not going to run correctly because the compiler is going to insert calls to functions it expects to be in the library, which might not be the case.
also I want... |
2,706,512 | 2,706,548 | STL container to pop() by priority? | I'm writing a thread-pool for Qt as QRunnable doesn't handle event loops in new threads.
Not too familiar with STL, what would be the best way to pop() something by priority? Priority should probably be a property of MyRunnable imo, but I can always give that info to an STL container when adding the runnable to the qu... | Not familiar with QT, but as other suggest, use a priority_queue.
You'll also need a functor to allow the structure to access the priority information and specify the sorting order.
struct is_higher_priority {
bool operator()( MyRunnable const &l, MyRunnable const &b )
{ return l.priority > r.priority; }
};... |
2,706,538 | 2,706,609 | Event to handle Open With (WinApi) | I cannot find how I'm supposed to handle file opening in my program. For example if the user does Open With ... myprogram.exe then how do I handle that and do something with it. which WM_Message is sent?
Thanks
*no I mean if you have sometext.txt and openwith Notepad.exe, it magically displays the text, so how can I kn... | There is no message sent, you will probably get it on the commandline, use argc/argv or GetCommandLine()
The shell first checks for a NoOpenWith value in KCR\Applications\myprogram.exe if it is not there, your app is listed in the open with dialog.
If the user chooses your app, the shell will use the command listed und... |
2,706,539 | 2,706,549 | Writing a custom iterator -- what to do if you're at the end of the array? | I'm writing a custom iterator for a Matrix class, and I want to implement the increment method, which gets called when the iterator is incremented:
void MatrixIterator::increment()
{
// go to the next element
}
Suppose the iterator has been incremented too many times and now points to past the end of the matrix (i... | You can assert, but in general you are not required to do anything. C++ iterators are not supposed to catch errors. E.g. STL iterators don't do that.
|
2,706,575 | 2,706,587 | PInvoke Unbalances the stack | Good afternoon,
I have been working on a dll that can use CORBA to communicate to an application that is network aware. The code works fine if I run it as a C++ console application. However, I have gotten stuck on exporting the methods as a dll. The methods seems to export fine, and if I call a method with no parame... | The calling conventions don't match. In C++, declare the function with the stdcall calling convention:
extern "C" bool __declspec(dllexport) __stdcall SpiceStart(char* installPath)
|
2,706,787 | 2,706,953 | nested function call faster or not? | I have this silly argument with a friend and need an authoritative word on it.
I have these two snippet and want to know which one is faster ? [A or B]
(assuming that compiler does not optimize anything)
[A]
if ( foo () );
[B]
int t = foo ();
if ( t )
EDIT : Guys, this might look a silly question to you but I have... | For the record, gcc, when compiling with optimization specifically disabled (-O0), produces different code for the two inputs (in my case, the body of foo was return rand(); so that the result would not be determined at compile time).
Without temporary variable t:
movl $0, %eax
call foo
te... |
2,707,010 | 2,707,039 | Why doesn't ifstream read to the end? | I'm making a notepad-like program. To get the text from a file I read each character into the buffer by doing
while (!file.EOF())
{
mystr += file.get();
}
however if I load in an exe it stops after MZ but Notepad reads the whole exe.
I set my ifstream to binary mode but still no luck. What am I doing wrong?
Thanks
c... |
however if I load in an exe it stops
after MZ
a file of type .exe can contain all kinds of bytes even 0's, you would need to check the byte value before appending to the string.
regarding MZ
|
2,707,048 | 2,707,073 | Check my anagram code from a job interview in the past | Had the following as an interview question a while ago and choked so bad on basic syntax that I failed to advance (once the adrenalin kicks in, coding goes out the window.)
Given a list of string, return a list of sets of strings that are anagrams of the input set. i.e. "dog","god", "foo" should return {"dog","god"}. ... | The best way to group anagrams is to map the strings to some sort of histogram representation.
FUNCTION histogram
[input] -> [output]
"dog" -> (1xd, 1xg, 1xo)
"god" -> (1xd, 1xg, 1xo)
"foo" -> (1xf, 2xo)
Basically, with a linear scan of a string, you can produce the histogram representation of how many of ... |
2,707,106 | 2,707,674 | Chipmunk Physics or Box2D for C++ 2D GameEngine? | I'm developing what it's turning into a "cross-platform" 2D Game Engine, my initial platform target is iPhone OS, but could move on to Android or even some console like the PSP, or Nintendo DS, I want to keep my options open.
My engine is developed in C++, and have been reading a lot about Box2D and Chipmunk but still ... | You are right, chipmunk has been developed improving a lot of the places where Box2D falls down.
However, Box2D is definitely the more established platform and from my personal experience when making the decision of which engine to use, I found that Box2D had a much larger community following, so was easier to learn by... |
2,707,133 | 2,707,149 | Returning references while using shared_ptrs | Suppose I have a rather large class Matrix, and I've overloaded operator== to check for equality like so:
bool operator==(Matrix &a, Matrix &b);
Of course I'm passing the Matrix objects by reference because they are so large.
Now i have a method Matrix::inverse() that returns a new Matrix object. Now I want to use the... | You do not need to return a reference from the inverse() method. Return the object itself. The compiler will create a temporary reference for passing to the equality operator, and that reference will go out of scope immediately after the operator returns.
To answer your question whether or not it's a memory leak.
Depe... |
2,707,159 | 2,707,184 | Class type while deserialization in c++ | I am developing game editor in c++.I have implemented reflection mechanism using DiaSDK.Now I want to store state of the objects(Like Camera,Lights,Static mesh) in some level file via serialization.
And later on able to retrieve their state via deserialization.Serializing objects is not a problem for me.During deserial... | When you serialize the class, you will need to emit its runtime type so that you can instantiate the correct type when deserializing. Otherwise, it is not possible to determine which runtime type to use.
A good technique for constructing classes based on a type string is to build a hash map from class names to factory ... |
2,707,318 | 2,707,335 | what is the wrong with this code"length indicator implementation"? | this is an implementation of length indicator field
but it hang and i think stuck at a loop and don't show any thing.
// readx22.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
#include "fstream"
#include "stdio.h"
using namespace std;
class Student
{
public:
s... | You probably should have used cnt-- instead of -- cnt everywhere. The first zero-byte string will trigger an extremely large loop that eventually consumes all memory (except maybe on a 64-bit OS). Actually, don't even bother with this fix. Loop over get() is extremely inefficient, just call read().
|
2,707,640 | 2,707,650 | Static Member Variables of the Same Class in C++ | I'm trying to create a class which contains a static pointer to an instance of itself. Here's an example:
A.h:
#include <iostream>
#ifndef _A_H
#define _A_H
class A {
static A * a;
};
A * a = NULL;
#endif
However, when I include A.h in another file, such as:
#include "A.h"
class B {
};
I get the following err... | This line:
A * a = NULL;
needs to look like this:
A *A::a = NULL;
And you need to move it out of the header file, and put it in a source (.cpp) file.
The definition of a static member must exist only once in your program. If you put this line in the header file, it would be included in every source file which include... |
2,707,740 | 2,707,839 | Writing an ostream filter? | I'd like to write a simple ostream which wraps an argument ostream and changes the stream in some way before passing it on to the argument stream. The transformation is something simple like changing a letter or erasing a word
What would a simple class inheriting from ostream look like? What methods should I override?
| std::ostream is not the best place to implement filtering. It doesn't have the appropriate virtual functions to let you do this.
You probably want to write a class derived from std::streambuf containing a wrapped std::ostream (or a wrapped std::streambuf) and then create a std::ostream using this std::streambuf.
std::s... |
2,707,909 | 2,714,396 | How do I use Loki's small object allocator? | I need to use Loki's small object allocator but I am very confused as to how it works. I've read the documentation and lots of forums but it doesnt make sense: some of them say to use the stl, others use custom allocators. I just need to be able to test its performance with allocating and deallocating objects of differ... | Ok, best I got was to make Loki's Small Object Allocator compliant with the STL. To do this I just created a wrapper class for the SmallObjAllocator class in Loki according to http://www.codeproject.com/kb/cpp/allocator.aspx?fid=16541&df=90&mpp=25&sort=Position&tid=1677312
|
2,707,923 | 2,708,155 | Inlining an array of non-default constructible objects in a C++ class | C++ doesn't allow a class containing an array of items that are not default constructible:
class Gordian {
public:
int member;
Gordian(int must_have_variable) : member(must_have_variable) {}
};
class Knot {
Gordian* pointer_array[8]; // Sure, this works.
Gordian inlined_array[8]; // Won't compile. Can't ... | For one thing, you can use an array wrapper (such as boost::array) to initialize the array with fixed values:
#include <boost/array.hpp>
class Gordian {
public:
int member;
Gordian(int must_have_variable) : member(must_have_variable) {}
};
namespace detail
{
boost::array<Gordian, 8> chop()
{
b... |
2,707,980 | 2,707,985 | How to convert a char* pointer into a C++ string? | I have a C++ string. I need to pass this string to a function accepting a char* parameter (for example - strchr()).
a) How do I get that pointer?
b) Is there some function equivalent to strschr() that works for C++ strings?
|
To get the C string equivalent of
the C++ string object use c_str
function.
To locate the first occurence of a
char in a string object use
find_first_of function.
Example:
string s = "abc";
// call to strlen expects char *
cout<<strlen(s.c_str()); // prints 3
// on failure find_first_of return string::npos
if(s.fi... |
2,708,078 | 2,708,087 | What Should be the Structure of a C++ Project? | I have recently started learning C++ and coming from a Ruby environment I have found it very hard to structure a project in a way that it still compiles correctly, I have been using Code::Blocks which is brilliant but a downside is that when I add a new header file or c++ source file, it will generate some code and eve... | To answer your questions:
The lines are include guards. They prevent the header file being included more than once in any given translation unit. If it was included multiple times, you would probably get multiple definition errors.
Header files are #included in .cpp files and in other headers. .cpp files are not norma... |
2,708,127 | 2,708,257 | aligning extern constants (gcc) | I want to make some static constants globally visible. I'm pretty familiar how to do that in C++. The problem is that these constants need to be aligned to some exotic boundary. Do I have to specify the alignment in extern declaration? I'm using GCC4.5
in *.cpp file
static const constant_t constant __attribute__((align... | First, it looks like you're trying to declare it static in the C file, which is the old C way of saying internal (file) linkage. This is inconsistent with your goal of making it global.
Given that the static is removed, you should only need the attribute in the C file: The extern declaration says effectively "I want to... |
2,708,176 | 2,708,193 | executable parameter c++ | if i got a c++ executable file like this: executable.exe and i want to add some parameters like:
executable.exe +username = pino
how do i get in c++ that i filled in pino as my username?
| Arguments to main. Your main is
int main(int argc, char **argv) {
...
}
All the command-line params are in argv. There are also Windows-specific APIs.
|
2,708,265 | 2,708,289 | Force to reimplement a static function in inherit classes | I have a program in C++ with plugins (dynamic libs). In the main program, I want to execute a static function to check if i can create a object of this type.
An example without dynamic libs (aren't neccesary to understand the problem):
#include "libs/parent.h"
#include "libs/one.h"
#include "libs/two.h"
int main(int a... | What you have here is classic factory pattern. You want to create an interface named IPluginFactory which would have two methods - match and create (or, optionally, combine them both in a single method). Then each of your plugin DLLs would have a class that implements this interface.
Parent obj;
IPluginFactory ... |
2,708,291 | 2,708,307 | Stack Overflow Accessing Large Vector | I'm getting a stack overflow on the first iteration of this for loop
for (int q = 0; q < SIZEN; q++)
{
cout<<nList[q]<<" ";
}
nList is a vector of type int with 376 items. The size of nList depends on a constant defined in the program. The program works for every value up to 376, then after 376 it stops working.... | If by "stops working", you mean crashes, then you're probably reading past the end of the buffer. vector::operator[] is not range checked, so it will let you shoot yourself in the foot.
If you want to traverse a vector, use an iterator, or at the very least nList.size().
So with least modifications to your code:
for (i... |
2,708,338 | 2,708,375 | std::cin >> *aa results in a bus error | I have this a class called PPString:
PPString.h
#ifndef __CPP_PPString
#define __CPP_PPString
#include "PPObject.h"
class PPString : public PPObject {
char *stringValue[];
public:
char *pointerToCharString();
void setCharString(char *charString[]);
void setCharString(const char charString[]);
};
#end... | The setCharString with the char *s[] signature is dereferencing the first element of an array of pointers to char*. It has not been allocated. If you change the declaration of aa to char aa[1000];, it will probably run.
There are some other issues too (also pointed out by others). The assignment to the variable str... |
2,708,340 | 2,708,546 | limit stl's vector max_size | How can I limit STL vector's max_size? Eventually by specialization. An example would be welcome.
| The way to do this is to replace the allocator. Note that vector and string are the only containers that actually check their allocators max_size right now. The idea is that since these containers guarantee that the elements are stored in contiguous memory, the container asks the allocator just how many elements the al... |
2,708,423 | 2,708,451 | C++ design related question | Here is the question's plot: suppose I have some abstract classes for objects, let's call it Object. It's definition would include 2D position and dimensions. Let it also have some virtual void Render(Backend& backend) const = 0 method used for rendering.
Now I specialize my inheritance tree and add Rectangle and Ellip... | Your actual problem seems to be managing the objects' lifetimes. Four possibilities that come to mind are:
Your container (i.e. Plane) assumes ownership of all contained objects and therefore deletes them once it's itself destroyed.
Your container (Plane) does not assume ownership and whoever added objects to your con... |
2,708,460 | 2,708,473 | How do Hex editors display data so quickly? | I'v created a Notepad-like application and if I load a 1MB file into the textbox, it takes about 1 minute. The Visual Studio Binary editor displays lines, Hex, and ascii versions in a fraction of a second. How do they get the data into the textbox so quickly?
Thanks
| They only read enough of the file to display what is viewable on screen. In other words, if your UI can only display 100 bytes at a time, you only need to read 100 bytes to fill the screen. If the user scrolls the window, you have to read additional bytes to fill in the missing pieces.
|
2,708,501 | 3,246,426 | Intel AVX intrinsics: any compatibility library out? | Are there any Intel AVX intrinsics library out? I'm looking for something similar as 'sse2mmx.h' header which fall-backs to MMX intrinsics if SSE2 integer intrinsics are not available on compile time. Thus if I had similar library for AVX I could write optimized code for new hardware which would have almost optimal spe... | Intel provides a AVX emulation header. I haven't tried it, but quoting the linked article "The AVX emulation header file uses intrinsics for the prior Intel instruction set extensions up to Intel SSE4.2. SSE4.2 support in your development environment as well as hardware is required in order to use the AVX emulation h... |
2,708,519 | 2,708,587 | Stopping Backtracking | Is there any way in C/C++ to stop a backtracking algorithm after finding the first solution without exiting the program.
I want my function to immediately exit the function,not to quit every level of recurrsion one by one stating return.
| You could use setjmp()/longjmp() in both C and C++ for a crude but effective way of bypassing the need to pass a flag all the way back.
|
2,708,735 | 2,708,745 | How to install MinGW correctly on Windows | I have recently started learning C++, but I require a compiler. I have tried the one packaged with Code::Blocks, but I have been told it is out of date.
I have tried reading the instructions on the website, but I simply don't know which files to download and un-zip. Is there a list of files to download? (latest versio... | I was the person that pointed you at the more up-to-date version at Twilight Dragon. The file you want there is http://sourceforge.net/projects/tdm-gcc/files/TDM-MinGW%20Installer/1.908.0/tdm-mingw-1.908.0-4.4.1-2.exe/download which is a Windows binary installer - you just run it. Note that you don't actually need to d... |
2,708,948 | 2,709,039 | How does the compile choose which template function to call? | Regarding the below code, how does the compiler choose which template function to call?
If the const T& function is omitted, the T& function is always called.
If the T& function is omitted, the const T& function is always called.
If both are included, the results are as below.
#include <iostream>
#include <typeinfo>
t... | Here is a brief summary of the process the compiler goes through. It doesn't cover everything, but it gets you started.
In this case, the decision is made the same as a non-templated function. Given void f(int&) and void f(const int&), the first will be chosen for regular ints, and the second for const ints. The par... |
2,708,985 | 2,709,047 | Access violation reading location 0x00184000 | having troubles with the following line
HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mVB));
it appears the CreateBuffer method is having troubles reading &mVB. mVB is defined in box.h and looks like this
ID3D10Buffer* mVB;
Below is the code it its entirety. this is all files that mVB is in.
//Box.cpp
#include "Box.... | If you want a pointer to the data array of a vector, you should use &vec[0]. If you use &vec it will give you a pointer to the vector object, which might contain all kinds management structures/... that have nothing to do with the data you inserted into the vector.
The data itself is stored at continuous memory startin... |
2,709,037 | 2,709,093 | WM_KEYDOWN confusion | I'm trying to get my application to do something when CTRL+S is pressed. I'm just not sure how the W and L params work for WM_KEYDOWN. MSDN has something about bit fields which i'm not sure about. How can I detect CTRL and S?
Thanks
What do I do if another control aside from hWnd has focus?
| Well, this is the big list of virtual key codes.
CTRL-S is going to be sent through as 2 WM_KEYDOWN messages - a message when the ctrl key is pressed (VK_LCONTROL or VK_RCONTROL) followed by a 0x53 for the "S" key.
Rather than processing both messages, wait for the key down message for the 'S' press then call GetKeySta... |
2,709,083 | 2,709,127 | Boost's "cstdint" Usage | Boost's C99 stdint implementation is awfully handy. One thing bugs me, though. They dump all of their typedefs into the boost namespace. This leaves me with three choices when using this facility:
Use "using namespace boost"
Use "using boost::[u]<type><width>_t"
Explicitly refer to the target type with the boost:: pre... | I just use C99's stdint.h (it's actually now in VS 2010). For the versions of Visual C/C++ that don't include it, I use a public domain version from MinGW that I modified to work with VC6 (from when I had to work in VC6):
http://snipplr.com/view/18199/stdinth/
There are a couple other options you might consider in th... |
2,709,092 | 2,709,100 | Creating a 3d plane using Frank Luna's technique: what are sinf and cosf? | I am creating a 3d plane that lies on the x and z axis, and has hills that extend on the y axis. The bulk of the code looks like this:
float PeaksAndValleys::getHeight(float x, float z)const
{
return 0.3f*( z*sinf(0.1f*x) + x*cosf(0.1f*z) );
}
void PeaksAndValleys::init(ID3D10Device* device, DWORD m, DWORD n, flo... | cosf and sinf are simply the float versions of cos and sin. The normal cos and sin functions return double values instead of floats. Note that all these functions work in radians, not degrees.
Combined in the way above, they give a landscape that looks somewhat like a mountain range, as in this plot.
|
2,709,124 | 2,709,688 | WxWidgets custom events | I'm trying to use a custom event in my WxWidgets C++ application, like described here.
In the constructor of my wxApp:
Connect(wxID_ANY, wxCommandEventHandler(APP::OnMyEvent));
Then the function that should catch the event:
void APP::OnMyEvent(wxCommandEvent& event)
{
exit(0); //testing
}
Finally, to test it:
wxC... | You appear to be using the following overload of Connect:
void Connect(wxEventType eventType, wxObjectEventFunction function,
wxObject* userData = NULL, wxEvtHandler* eventSink = NULL)
If so, then should an event of type wxID_ANY happen (never?), then the connected function will be called.
Perhaps you need:
Conn... |
2,709,199 | 2,709,246 | C++ String manipulation isn't making sense to me | This particular assignment has to do with removing substrings from strings; I am trying some of the Stanford SEE courses online to learn some new languages.
What I've got so far is below, but if text = "hello hello" and remove ="el", it gets stuck in a loop, but if i change text to text = "hello hllo", it works, makin... | found = (text.substr(lastfound,text.size())).find(remove); is incorrect. It returns the index of the searched string in text.substr(lastfound,text.size()), but not in text.
You should perhaps change this to found = text.find(text, lastfound);.
Besides of being incorrect, taking a substring (this means, allocating a new... |
2,709,210 | 2,709,413 | How do I define an Icon in QT with a compile time predefined image? | I have a png file on disk at compile time. I'd like to have it included into the compiled executable.
How do I define such an icon in Qt?
| You basically need to use the Qt resource system.
Check out Compiled-In Resources here.
Lets say this this your resource file
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file>images/copy.png</file>
<file>images/cut.png</file>
<file>images/paste.png</file>
</qresource>
</RCC>
In your source you can ... |
2,709,238 | 2,731,222 | WinApi equivalent of .NET KeyPreview | In .Net there is a feature called KeyPreview. How can I do this in WinApi. Maybe I don't necessarily need this but my hWnd has WM_KEYDOWN, but it does not receive it when my Text Box has focus. How can I achieve this?
Thanks
*Using pure Win32API...
is there an alternative, how could I handle the Text Box's WM_KEYDOWN?
| You can try subclassing the edit control. Either "instance subclassing", to trap messages for only one window, or "global subclassing" to trap messages for all windows of that class (in your application, not system-wide).
The example here (http://msdn.microsoft.com/en-us/library/ms997565.aspx) shows how to subclass an ... |
2,709,257 | 2,709,290 | trying to sort a simple string in c++ | #include "stdio.h"
#include "conio.h"
#include <iostream>
using namespace std;
int main (void)
{
char my_char[] = "happy birthday";
int i;
bool j=false;
char my_char_temp[1];
do
{
for (i=0;i<sizeof(my_char)-2;i++)
{
j=false;
if (my_char[i+1] < my_cha... | You are resetting j to false each and every time you compare two characters.
This means that, if you swap two characters, and you are NOT at the end of your array, you will forget that you have swapped them.
Move the j=false; from inside the for-loop to just inside the do-loop.
And you owe me a bottle of Jack for savin... |
2,709,283 | 2,709,295 | C++ delete static_cast<void*> (pointer) behavior | suppose the code does the following:
T *pointer = new T();
delete static_cast<void*>(pointer);
what is result? Undefined, memory leak, memory is deleted?
| The behavior is undefined. Concerning the delete expression, the C++ standard says:
In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or... |
2,709,315 | 2,709,502 | Is Boost.Tuple compatible with C++0x variadic templates? | I was playing around with variadic templates (gcc 4.5) and hit this problem :
template <typename... Args>
boost::tuple<Args...>
my_make_tuple(Args... args)
{
return boost::tuple<Args...>(args...);
}
int main (void)
{
boost::tuple<int, char> t = my_make_tuple(8, 'c');
}
GCC error message :
sorry, unimplemented:... | It doesn't seem to like expanding Args... to T1, T2, T3, ..., T9 as Boost has it.
As a workaround, use constructs that don't require this expansion:
#include <boost/tuple/tuple.hpp>
template <typename... Args>
auto my_make_tuple(Args... args) -> decltype(boost::make_tuple(args...))
{
return {args...};
}
int main (... |
2,709,339 | 2,709,368 | C++ R - tree implementation wanted | Does anyone know a good and simple to use in production code R-tree implementation? (actually, any implementations - R*, R+ or PR-tree would be great)
It doesn't matter if it is a template or library implementation, but some implementations that Google found look very disappointing...
| Check R-Trees code on http://www.superliminal.com/sources/sources.htm
also check
http://www.virtualroadside.com/blog/index.php/2008/10/04/r-tree-implementation-for-cpp/
|
2,709,434 | 2,709,510 | Assign RegEx submatches to variables or map (C++/C) | I need to extract the same type of information (e.g. First name, Last Name, Telephone, ...), from numerous different text sources, each with a different format & different order of the variables of interest.
I want a function that does the extraction based on a regular expression and returns the result as descriptive ... | Can you use "named capture groups"? It seems like returning a map is exactly what you want.
For example, in RE2
Check wikipedia see if your favorite regex library supports named captures.
|
2,709,435 | 2,709,490 | C++ union data-structure, easy access of bits within a DWORD | I'm running through a set of DirectX tutorials online and I have the following structure:
struct CUSTOMVERTEX
{
FLOAT x, y, z, rhw; // from the D3DFVF_XYZRHW flag
DWORD color; // from the D3DFVF_DIFFUSE flag
}
My basic understanding of directX leads me to thing tha color is made up of 8-bit alpha, red, green an... | Yes, this is an endianness issue. If you are supporting just one platform, you can lay out the struct members according to the architecture's endianness. If you are dealing with multiple architectures, you will need #define multiple struct member layouts, dependent on endianness.
Structs and unions always look more e... |
2,709,487 | 2,709,532 | Displaying (rendering) HTML from a string in QT | I have html in a QString, what widget can I use to display it?
(QWebView is not necessary as I dont access Internet)
| QWebViews setHtml():
The QWebView class provides a widget that is used to view and edit web documents.
In Qt QWebView is the widget that renders pages for you - if you don't need the networking features it provides, simply don't use them.
|
2,709,524 | 2,709,935 | Which graphical environment? | Which graphical environment (MFC, ATL, QT etc.) should I concentrate on, in order to be more employable? I don't want to spend months learning something only to discover that "no one" really use this or this really sucks, and "all" pros are using only such and such.
| Compare the number of jobs on various employment web sites for each technology you are asking. I believe MFC is still in most demand, but may be wrong.
|
2,709,669 | 2,709,687 | RTTI and Portability in C++ | If a compiler doesn't "support" RTTI, does that mean that the compiler can not handle class hierarchies that have virtual functions in them? Or have I been misunderstanding the literature about how RTTI isn't portable, and the issues lie elsewhere?
Thank you all for your comments!
| RTTI is not needed for virtual functions.
It is mainly used for dynamic_cast and typeid.
|
2,709,699 | 2,709,751 | Using a variable in a mysql query, in a C++ MFC program | After extensive trawling of the internet, I still haven't found any solution for this problem.
I'm writing a small C++ app that connects to an online database and outputs the data in a listbox.
I need to enable a search function using an edit box, but I can't get the query to work while using a variable.
My code is:
re... | The problem here is that you are probably building for Unicode, which means that CString consists of wide characters. You can't directly concatenate an ASCII string with a wide character string (and you can't concatenate string literals with the + operator either).
I think the clearest way to build the query string he... |
2,709,719 | 2,709,733 | Throwing out of range exception in C++ | This code works;
int at(int index) {
if(index < 1 || index >= size)
throw 0;
return x[index];
}
Yet this doesn't
int at(int index) {
if(index < 1 || index >= size)
throw std::out_of_range;
return x[index];
}
I get the error "expected primary expression before ';'". Now... it surprises me because I ... | Replace throw std::out_of_range; with throw std::out_of_range ("blah");. I.e. you need to create an object, you cannot throw a type.
|
2,710,010 | 2,710,030 | How to speed up calculation of length of longest common substring? | I have two very large strings and I am trying to find out their Longest Common Substring.
One way is using suffix trees (supposed to have a very good complexity, though a complex implementation), and the another is the dynamic programming method (both are mentioned on the Wikipedia page linked above).
Using dynamic pro... | Will it be faster in practice? Yes. Will it be faster regarding Big-Oh? No. The dynamic programming solution is always O(n*m).
The problem that you might run into with suffix trees is that you trade the suffix tree's linear time scan for a huge penalty in space. Suffix trees are generally much larger than the table you... |
2,710,098 | 2,710,183 | C++, generic programming and virtual functions. How do I get what I want? | This is what I would like to do using templates:
struct op1
{
virtual void Method1() = 0;
}
...
struct opN
{
virtual void MethodN() = 0;
}
struct test : op1, op2, op3, op4
{
virtual void Method1(){/*do work1*/};
virtual void Method2(){/*do work2*/};
virtual void Method3(){/*do work3*/};
virtual... | Tested with GCC 4.3. Don't even know why I spent time on this :-/
#include <iostream>
template <std::size_t N>
struct mark
{ };
template <std::size_t N>
struct op : op <N - 1>
{
virtual void do_method (const mark <N>&) = 0;
};
template <>
struct op <1>
{
virtual void do_method (const mark <1>&) = 0;
};
str... |
2,710,194 | 2,710,313 | Register C function in Lua table | How to register a C function in Lua, but not in a global context, but as a table field?
| void register_c_function(char const * const tableName, char const * const funcName, CFunctionSignature funcPointer)
{
lua_getfield(lstate, LUA_GLOBALSINDEX, tableName); // push table onto stack
if (!lua_istable(lstate, -1)) // not a table, create it
{
lua_createtable(lstate, 0... |
2,710,224 | 2,710,352 | Trying to make a plugin system in C++/Qt | I'm making a task-based program that needs to have plugins. Tasks need to have properties which can be easily edited, I think this can be done with Qt's Meta-Object Compiler reflection capabilities (I could be wrong, but I should be able to stick this in a QtPropertyBrowser?)
So here's the base:
class Task : public QO... | Sounds like you've been giving this a thorough thought, which is great and needed. I cannot comment on the Qt specifics, but be sure to not miss out on these pieces of plugin advice, particularly versioning: Plugin Architecture
EDIT: The original link above is borked (was added 8 years ago...). The Wayback Machine has ... |
2,710,423 | 2,720,661 | Setting Position of source and listener has no effect | First time i've worked with OpenAL, and for the life of my i can't figure out why setting the position of the source doesn't have any effect on the sound. The sounds are in stero format, i've made sure i set the listener position, the sound is not realtive to the listener and OpenAL isn't giving out any error.
Can anyo... | Arrrr, Stero isn't localised. It all makes sense now because steros channels are already computed where mono isn't so panning is calculated by openAL.
|
2,710,507 | 2,710,520 | Mixing Objective-C and C++ | I'm trying to mix Objective-C with C++. When I compile the code, I get several errors.
A.h
#import <Cocoa/Cocoa.h>
#include "B.h"
@interface A : NSView {
B *b;
}
-(void) setB: (B *) theB;
@end
A.m
#import "A.h"
@implementation A
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
i... | You need to name your .m files .mm. And you will be able to compile C++ code with Objective-C.
So, following your example, your AView.m file should be named AView.mm. It's simple as that. It works very well. I use a lot of std containers (std::vector, std::queue, etc) and legacy C++ code in iPhone projects without any ... |
2,710,719 | 2,710,868 | bitset to dynamic bitset | I have a function where i use bitset.Now i need to convert it to a dynamic bitset..
but i don't know how.
Can somebody help me ?
set<string> generateCandidates(set<string> ck,unsigned int k){
set<string> nk ;
for (set<string>::const_iterator p = ck.begin( );p != ck.end( ); ++p){
for (set<string>::const_iterator ... | The difference isn't that big:
boost::dynamic_bitset<> bs1(*p);
boost::dynamic_bitset<> bs2(*q);
bs1 |= bs2;
if(bs1.count() == k){
std::string str;
boost::to_string(bs1, str);
nk.insert(str);
}
|
2,710,721 | 2,710,746 | Using a type parameter and a pointer to the same type parameter in a function template | I've written a template function to determine the median of any vector or array of any type that can be sorted with sort. The function and a small test program are below:
#include <algorithm>
#include <vector>
#include <iostream>
using namespace::std;
template <class T, class X>
void median(T vec, size_t size, X& ret... | The idiomatic approach is to use iterators. To enable this, you can derive the return type from the iterator:
template <class I>
typename iterator_traits<I>::value_type median(I start, I finish)
{
...
}
|
2,710,750 | 2,710,775 | What is the correct less operator for simple class with two int members? | What is the correct operator< for the following class?
struct Person {
int height;
int width;
friend bool operator<(const Person&, const Person&);
};
Thanks!
| That's entirely up to you and how you would want people to naturally sort. If you want short people first, but skinny to come before tall if they are the same height:
friend bool operator<(const Person& a, const Person& b) {
return a.height != b.height ? a.height < b.height : a.width < b.width;
}
If you want some ... |
2,710,765 | 5,233,034 | No-op deallocator for boost::shared_ptr | Is there a stock no-op deallocator in Boost to use with boost::shared_ptr for static objects, etc.
I know it's ultra-trivial to write, but I don't want to sprinkle my code with extra tiny functions if there is already one available.
| Yes there is one here:
#include <boost/serialization/shared_ptr.hpp> // for null_deleter
class Foo
{
int x;
};
Foo foo;
boost::shared_ptr< Foo > sharedfoo( &foo, boost::serialization::null_deleter() );
There is, of course, a danger with the fact that you need to know the function you call doesn't store the shared_... |
2,710,844 | 2,710,874 | Why is 'unbounded_array' more efficient than 'vector'? | It says here that
The unbounded array is similar to a
std::vector in that in can grow in
size beyond any fixed bound. However
unbounded_array is aimed at optimal
performance. Therefore unbounded_array
does not model a Sequence like
std::vector does.
What does this mean?
| It appears to lack insert and erase methods. As these may be "slow," ie their performance depends on size() in the vector implementation, they were omitted to prevent the programmer from shooting himself in the foot.
insert and erase are required by the standard for a container to be called a Sequence, so unlike vector... |
2,711,005 | 2,711,023 | 2D collision detection and stuff with OpenGL | I am working on a simple 2D openGL project. It contains a main actor you can control with the keyboard arrows. I got that to work okay. What I am wanting is something that can help explain how to make another actor object follow the main actor. Maybe a tutorial on openGL. The three main things I need to learn are the a... | You could use a physics library like Chipmunk Physics, which lets you attach springs and things between the two objects and detect when they hit each other and other things.
|
2,711,170 | 2,711,191 | returning a pointed to an object within a std::vector | I have a very basic question on returning a reference to an element of a vector .
There is a vector vec that stores instances of class Foo. I want to access an element from this vector . ( don't want to use the vector index) . How should I code the method getFoo here?
#include<vector>
#include<stdio.h>
#include<iost... | Why use pointers at all when you can return a reference?
Foo& B::getFoo() {
vec.push_back(Foo());
return vec.back();
}
Note that references, pointers and iterators to a vectors contents get invalidated if reallocation occurs.
Also having member data public (like your vec here) isn't good practice - it is bette... |
2,711,272 | 2,711,282 | Declaring an uninitialized variable without a null constructor | Consider the DUPoint class, whose declaration appears below. Assume this code appears in a file named DUPoint.h:
#include <string>
class DUPoint {
public:
DUPoint (int x, int y);
int getX () const;
int getY () const;
void setX (int x);
void setY (int y);
void print();
private:
int... | Yes, if there is a user-declared constructor, no default constructor will be generated implicitly by the compiler.
|
2,711,343 | 2,711,376 | Some exam questions about C++ vectors and arrays | Hey guys, I have a CS exam tomorrow. Just want to get a few questions cleared up. Thanks a lot, and I really appreciate the help.
Que 1.
What are parallel vectors?
Vectors of the same length that contain data that is meant to be processed together
Vectors that are all of the same data type
Vectors that are of the same... | Question 1
The term "parallel vector" is non-standard... (to me, it means that the dot product of their directions is 1!), so you will need to look at your notes and see what the teacher's own meaning of "parallel" is.
Question 2
This is a tricky question. Array construction (of primitives w/o initialization) is faster... |
2,711,430 | 2,711,460 | How do I prevent race condition WITHOUT using locks in C++? | How do I prevent a race condition WITHOUT locking or using mutexes/semaphors in C++? I'm dealing with a nested for loop in which I will be setting a value in an array:
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
for (int k = 0; k < o; ++k)
array[k] += foo(...);
More or less, I want to deal with... | Assuming windows and that array contains elements of type LONG you could do something like:
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
for (int k = 0; k < o; ++k) {
LONG val = foo(...);
InterlockedAdd( &array[k], val);
}
If you're not working in Windows your platform ... |
2,711,432 | 2,771,613 | boost::python string-convertible properties | I have a C++ class, which has the following methods:
class Bar {
...
const Foo& getFoo() const;
void setFoo(const Foo&);
};
where class Foo is convertible to std::string (it has an implicit constructor from std::string and an std::string cast operator).
I define a Boost.Python wrapper class, which, among other... | I ended up giving up and implementing something similar to custom string class conversion example in Boost.Python FAQ, which is a bit verbose, but works as advertised.
|
2,711,522 | 2,711,560 | What happens if I assign a negative value to an unsigned variable? | I was curious to know what would happen if I assign a negative value to an unsigned variable.
The code will look somewhat like this.
unsigned int nVal = 0;
nVal = -5;
It didn't give me any compiler error. When I ran the program the nVal was assigned a strange value! Could it be that some 2's complement value gets assi... | For the official answer - Section 4.7 conv.integral
"If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is con... |
2,711,613 | 2,711,635 | How can free() immediately followed by assignment of NULL lead to a dangling pointer? | How can the below code result in a dangling pointer.
{
char *cPointer = malloc ( some constant number );
/* some code */
free ( cPointer );
cPointer = NULL;
/* some code */
}
| It can't.
This would:
char * a = malloc(556);
char * b = a;
free(a);
a = NULL;
b is now dangling pointer, because the object it pointed to it's gone but b still stores address to memory where the object used to be, you get funny results when you try to access it - it depends if the memory has been reused or is untouch... |
2,711,672 | 2,711,930 | Building Boost with LSB C++ Compiler | I want to build my program with LSB C++ Compiler from the Linux Standard Base http://www.linuxfoundation.org/collaborate/workgroups/lsb. Program depends on the Boost library, built with gcc 4.4 version. Compilation fails. Is it possible to build the Boost library with LSB C++ Compiler? Alternatively, is it possible to ... | LSB C++ compiler is not actually a compiler. The lsbc++ executable is a wrapper around GCC compiler that is installed on your system (the actual compiler can be controlled via --lsb-cxx option). You will most likely hack into boost build system for it to call LSB wrapper instead of native gcc compiler.
So the issues ... |
2,711,704 | 2,722,699 | Is factory method proper design for my problem? | here is my problem and I'm considering to use factory method in C++, what are your opinions ?
There are a Base Class and a lot of Subclasses.
I need to transfer objects on network via TCP.
I will create objects in first side, and using this object I will create a byte array TCP message, and send it to other side.
On th... | Short answer: Yes.
Long Answer: The factory method pattern is what you want.
Your network messages need to include the type and size of the object to deserialize in the message header and then on the recipient side your factory method can consume and deserialize the rest of the message body to construct the objects.
... |
2,711,705 | 2,711,740 | Is there any way to limit the size of an STL Map? | I want to implement some sort of lookup table in C++ that will act as a cache. It is meant to emulate a piece of hardware I'm simulating.
The keys are non-integer, so I'm guessing a hash is in order. I have no intention of inventing the wheel so I intend to use std::map for this (though suggestions for alternatives ar... | First thing is that a map structure is not a hash table, but rather a balanced binary tree. This has an impact in the lookup times O(log N) instead of O(1) for an optimal hash implementation. This may or not affect your problem (if the number of actual keys and operations is small it can suffice, but the emulation of t... |
2,711,732 | 2,711,845 | Should boost library be dependent on structure member alignments? | I found, the hard way, that at least boost::program_options is dependent of the compiler configured structure member alignment.
If you build boost using default settings and link it with a project using 4 bytes alignment (/Zp4) it will fail at runtime (made a minimal test with program_options). Boost will generate an a... | You need to ensure that your program and the libraries you link with have the same ABI.
The number of compiler switches that can alter the ABI of C++ classes and functions could be too large so it is clearly a problem to name more than 3000 combinations.
You could take a look here for a more detailed rationale.
|
2,711,780 | 2,711,804 | Question about char input | This is what I'm trying to do...
char input[4];
cin >> input;
cout << "Input[0]: " << input[0] << "Input[1]: " << input[1] << "Input[2]: " << input[2] << "Input[3] " << input[3]<< "Input[4] " << input[4] <<endl;
However, when I enter "P F" I get an output of this: Input[0]:P Input[1]: Input[2]:(A weird looking square... | cin >> separates inputs by a space, hence when you enter P<space>F, only the P is accepted into input, and F is queued for the next cin >>.
Thus after that cin >> input line, your input will look like
input[0] = 'P';
input[1] = '\0';
// input[2] = garbage;
// input[3] = garbage;
// input[4] = buffer-overflow;
Pe... |
2,711,848 | 2,711,926 | Finding latest release links on website for C++ Application | Basically I have written a game plugin that will allow server admins to update their administration tools from within game rather than having to go download it and install it. The releases are updated regularly, and the beta versions are nightly builds.
I am trying to find a way to grab the links from the website, but ... | The solution is simple and can be broken down into a few steps:
Fetching the links & files: Use cURL/cURLpp or Poco C++. They are easy but you may spend a few hours to learn :)
Processing/Extracting the links: Use TidyHTML to make sure the HTML is converted to valid XHTML and use XPath to extract the links. Can use li... |
2,711,959 | 2,711,971 | C++ array of classes | I working on a game but I have a problem with the initialization of the level. (feld is just field in german)
class level{
private:
feld spielfeld[10][10];
public:
/*
other stuff
*/
void init_feld();
};
void level::init_feld()
{
for(int i=0;i!=10;i++){
for(int n=0;n!=10;n++){
spielfeld[... | spielfeld[i][n] is a feld object, new feld(land, i, n) dynamically allocates a new feld object and returns a pointer to that object. If you want to assign to a feld value to spielfeld[i][n] you could use:
spielfeld[i][n] = feld(land, i, n);
Alternatively you may be able to set the appropriate members of spielfeld[i][n... |
2,712,070 | 2,771,958 | Producing Mini Dumps for _caught_ SEH exceptions in mixed code DLL | I'm trying to use code similar to clrdump to create mini dumps in my managed process.
This managed process invokes C++/CLI code which invokes some native C++ static lib code, wherein SEH exceptions may be thrown (e.g. the occasional access violation).
C# WinForms
->
C++/CLI DLL
->
Static C++ Lib
... | I found that with Vectored Exception Handling I can get a first-chance notification of any SEH exception and use this occasion to produce a mini dump.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.