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,539,077 | 2,539,181 | BOOST program_options: parsing multiple argument list | I would like to pass the multiple arguments with positive or negative values.
Is it possible to parse it?
Currently I have a following initialization:
vector<int> IDlist;
namespace po = boost::program_options;
po::options_description commands("Allowed options");
commands.add_options()
("IDlist",po::value< vector<int> >(&IDlist)->multitoken(), "Which IDs to trace: ex. --IDlist=0 1 200 -2")
("help","print help")
;
and I would like to call:
./test_ids.x --IDlist=0 1 200 -2
unknown option -2
So,the program_options assumes that I am passing -2 as an another option.
Can I configure the program_options in such a way that it can accept the negative integer values?
Thanks
Arman.
EDIT:
BTW I was parsing it by the simple parser
store(command_line_parser(argc, argv).options(commands).run(), vm);
, but solution was to use the extended one:
parse_command_line
| Have you tried "-2"?
Edit: Quoting doesn't seem to do the trick, however, changing the command line style works:
char* v[] = {"name","--IDlist=0","1","200","-2"};
int c = 5;
std::vector<int> IDlist;
namespace po = boost::program_options;
po::options_description commands("Allowed options");
commands.add_options()
("IDlist",po::value< std::vector<int> >(&IDlist)->multitoken(), "Which IDs to trace: ex. --IDlist=0 1 200 -2")
("help","print help")
;
po::variables_map vm;
po::store(parse_command_line(c, v, commands, po::command_line_style::unix_style ^ po::command_line_style::allow_short), vm);
po::notify(vm);
BOOST_FOREACH(int id, IDlist)
std::cout << id << std::endl;
|
2,539,081 | 2,539,086 | Could the assign function for containers possibly overflow? | I ran into this question today and thought I should post it for the community's reference and/or opinions.
The standard C++ containers vector, deque, list, and string provide an assign member function. There are two versions; I'm primarily interested in the one accepting an iterator range. The Josuttis book is a little ambiguous with its description. From p. 237...
Assigns all elements of the range [beg,end); this is, is replaces all existing elements with copies of the elements of [beg,end).
It doesn't say what happens if the size of the assignee container is different from the range being assigned. Does it truncate? Does it automagically expand? Is it undefined behavior?
| Here's what I found. It turns out I didn't have to worry about silently doing the wrong thing. Once again, the standard has the answer. From section 23.2.6.1:
void assign(Iter first, Iter last);
Effects:
erase(begin(), end());
insert(begin(), first, last);
So it's really just a shortcut for a clear() followed by an insert of the full range.
|
2,539,088 | 2,557,640 | 3D coordinate of 2D point given camera and view plane | I wish to generate rays from the camera through the viewing plane. In order to do this, I need my camera position ("eye"), the up, right, and towards vectors (where towards is the vector from the camera in the direction of the object that the camera is looking at) and P, the point on the viewing plane. Once I have these, the ray that's generated is:
ray = camera_eye + t*(P-camera_eye);
where t is the distance along the ray (assume t = 1 for now).
My question is, how do I obtain the 3D coordinates of point P given that it is located at position (i,j) on the viewing plane? Assume that the upper left and lower right corners of the viewing plane are given.
NOTE: The viewing plane is not actually a plane in the sense that it doesn't extend infinitely in all directions. Rather, one may think of this plane as a widthxheight image. In the x direction, the range is 0-->width and in the y direction the range is 0-->height. I wish to find the 3D coordinate of the (i,j)th element, 0
| When I directly plugged in suggested formulas into my program, I didn't obtain correct results (maybe some debugging needed to be done). My initial problem seemed to be in the misunderstanding of the (x,y,z) coordinates of the interpolating corner points. I was treating x,y,z-coordinates separately, where I should not (and this may be specific to the application, since the camera can be oriented in any direction). Instead, the solution turned out to be a simple interpolation of the corner points of the viewing plane:
interpolate the bottom corner points in the i direction to get P1
interpolate the top corner points in the i direction to get P2
interpolate P1 and P2 in the j direction to get the world coordinates of the final point
|
2,539,113 | 2,539,189 | C++ ulong to class method pointer and back | I'm using a hash table (source code by Google Inc) to store some method pointers defined as:
typedef Object *(Executor::*expression_delegate_t)( vframe_t *, Node * );
Where obviously "Executor" is the class.
The function prototype to insert some value to the hash table is:
hash_item_t *ht_insert( hash_table_t *ht, ulong key, ulong data );
So basically i'm doing the insert double casting the method pointer:
ht_insert( table, ASSIGN, reinterpret_cast<ulong>( (void *)&Executor::onAssign ) );
Where table is defined as a 'hash_table_t *' inside the declaration of the Executor class, ASSIGN is an unsigned long value, and 'onAssign' is the method I have to map.
Now, Executor::onAssign is stored as an unsigned long value, its address in memory I think, and I need to cast back the ulong to a method pointer. But this code:
hash_item_t* item = ht_find( table, ASSIGN );
expression_delegate_t delegate = reinterpret_cast < expression_delegate_t > (item->data);
Gives me the following compilation error :
src/executor.cpp:45: error: invalid cast from type ‘ulong’ to type ‘Object* (Executor::*)(vframe_t*, Node*)’
I'm using GCC v4.4.3 on a x86 GNU/Linux machine.
Any hints?
| If I remember correctly, a class method pointer may be larger than a normal function pointer due to implementation details. This would explain why the compiler does not allow this cast – the method pointer wouldn’t fit inside the storage space of a “normal” pointer.
The solution, as I’ve stated above in a comment, is to use a proper C++ hash table implementation that allows arbitrary types via C++ templates.
|
2,539,164 | 2,539,225 | How to link app with static library + why this is not working | I have a problem. I wrote example code and I want to build it without the error:
main.cpp(.text+0x5): undefined reference to `test()'
Library
test1.c
#include <stdlib.h>
void test()
{
puts("Działa");
}
test1.h
#ifndef TEST1_H
#define TEST1_H
extern void test();
#endif
makefile
all:
gcc -c ./src/test1.c -o ./lib/test1.o
ar rcs ./lib/libtest1.a ./lib/test1.o
Program
main.cpp
#include <test1.h>
int main()
{
test();
return 0;
}
makefile
all:
g++ -static -I../test1/include -L../test1/lib ./src/main.cpp -o ./build/MyApp -ltest1
What am I doing wrong?
| You are compiling a C code function, but you are expecting to link a C++ function.
Because of 'type safe linkage', the function you provide is not the function that the C++ code calls.
Either in test1.h use:
#ifdef __cplusplus
extern "C" {
#endif
extern void test1(void);
#ifdef __cplusplus
}
#endif
Or:
Compile the function with the C++ compiler.
The C++ compiler will mangle the symbol names to provide type-safe linkage (a term which you should be able to search for via your preferred search engine).
The 'compiler' - actually the linker - is looking for a function with a C++ mangled name representing the C++ function with the signature 'void test1(void);'.
For example (but remember - different compilers deliberately mangle things differently), G++ 4.2.1 on MacOS X 10.6.2 generates a symbol '__Z5test1v' for the function; GCC generates a symbol '_test1'. Clearly, when the linker is looking for '__Z5test1v', the symbol '_test1' is not going to be used - it is not spelled the same. This is a good thing.
You can use 'nm -g' on the object file for the main program to see what it is looking for, and on the object file in the library to see what it is providing. And, given that the spellings are different, that is why the loader does not pick up the library function - it is looking for something with a different name.
|
2,539,458 | 2,539,501 | C++ -- return x,y; What is the point? | I have been programming in C and C++ for a few years and now I'm just now taking a college course in it and our book had a function like this for an example:
int foo(){
int x=0;
int y=20;
return x,y; //y is always returned
}
I have never seen such syntax. In fact, I have never seen the , operator used outside of parameter lists. If y is always returned though, then what is the point? Is there a case where a return statement would need to be created like this?
(Also, I tagged C as well because it applies to both, though my book specifically is C++)
| The comma operator is primarily used in for statements like so:
for( int i=0, j=10; i<10; i++, j++ )
{
a[i] = b[j];
}
The first comma is not a comma operator, it's part of the declaration syntax. The second is a comma operator.
|
2,539,555 | 2,554,702 | Directly Jump to another C++ function | I'm porting a small academic OS from TriCore to ARM Cortex (Thumb-2 instruction set). For the scheduler to work, I sometimes need to JUMP directly to another function without modifying the stack nor the link register.
On TriCore (or, rather, on tricore-g++), this wrapper template (for any three-argument-function) works:
template< class A1, class A2, class A3 >
inline void __attribute__((always_inline))
JUMP3( void (*func)( A1, A2, A3), A1 a1, A2 a2, A3 a3 ) {
typedef void (* __attribute__((interrupt_handler)) Jump3)( A1, A2, A3);
( (Jump3)func )( a1, a2, a3 );
}
//example for using the template:
JUMP3( superDispatch, this, me, next );
This would generate the assembler instruction J (a.k.a. JUMP) instead of CALL, leaving the stack and CSAs unchanged when jumping to the (otherwise normal) C++ function superDispatch(SchedulerImplementation* obj, Task::Id from, Task::Id to).
Now I need an equivalent behaviour on ARM Cortex (or, rather, for arm-none-linux-gnueabi-g++), i.e. generate a B (a.k.a. BRANCH) instruction instead of BLX (a.k.a. BRANCH with link and exchange). But there is no interrupt_handler attribute for arm-g++ and I could not find any equivalent attribute.
So I tried to resort to asm volatile and writing the asm code directly:
template< class A1, class A2, class A3 >
inline void __attribute__((always_inline))
JUMP3( void (*func)( A1, A2, A3), A1 a1, A2 a2, A3 a3 ) {
asm volatile (
"mov.w r0, %1;"
"mov.w r1, %2;"
"mov.w r2, %3;"
"b %0;"
:
: "r"(func), "r"(a1), "r"(a2), "r"(a3)
: "r0", "r1", "r2"
);
}
So far, so good, in my theory, at least. Thumb-2 requires function arguments to be passed in the registers, i.e. r0..r2 in this case, so it should work.
But then the linker dies with
undefined reference to `r6'
on the closing bracket of the asm statement ... and I don't know what to make of it. OK, I'm not the expert in C++, and the asm syntax is not very straightforward... so has anybody got a hint for me? A hint to the correct __attribute__ for arm-g++ would be one way, a hint to fix the asm code would be another. Another way maybe would be to tell the compiler that a1..a3 should already be in the registers r0..r2 when the asm statement is entered (I looked into that a bit, but did not find any hint).
| Well, I now figured out what went wrong.
The whole concept of JUMPing directly to another function is moot on ARM Cortex, because TriCore uses a Context Save Area (CSA) to save the whole CPU context everytime you call another function. Think of it as a second, independent stack that grows with each CALL and shrinks with each RET. And each CSA block has constant size.
ARM Cortex, on the other hand, uses a simple standard stack (ok, it knows about a system stack and a thread stack, but that's unimportant here) -- and GCC just saves what it needs for each function, so each frame has a different size. Simply jumping to another function therefore is out of the question, because the stack will be corrupt as soon as the jumped-to function starts saving the non-volatile registers it uses.
And about the linker error with the undefined reference to r6 ... well, I should have read the instruction set documentation more carefully. B is an unconditional branch to an immediate address, BX is the instruction that expects the branch address in a register. I was fooled by the instruction list in the manual where BX was shortly described as "Branch with exchange". I did not want to exchange anything, I wanted a simple jump, so I did not read further.
So, after exchanging B with BX in the asm volatile code, the code compiled. But, as pointed out above, the whole concept cannot work as expected. Maybe someone else can find a use case for that code, I have to resort to classic function calling now ...
|
2,539,709 | 2,539,737 | C++ list<T>::iterator cant be used in derived class template | g++ compiler gives this error: expected `;' before 'it'
template <typename T>
class myList : public std::list<T>
{
public:
void foo ()
{
std::list<T>::iterator it; // compiler error as above mentioned, why ???
}
};
Thanks.
| In g++. whenever in a template you see the error:
error: expected ';' before 'it'
suspect you need a typename:
typename std::list<T>::iterator it;
This is needed when in a template you have a new type declared (in this case the list iterator) which is dependant on one or more of the template parameters. The need is not unique to g++ BTW, it's part of standard C++.
|
2,539,724 | 2,540,333 | WOW64: get x64 %CommonProgramFiles% from 32 bit process | Queries I tried: ExpandEnvironmentStrings("%COMMONPROGRAMFILES%"), GetSpecialPath(CSIDL_PROGRAM_FILES_COMMON).
All resolve to (typically) c:\\Program Files (x86)\\Common Files from my 32-bit app. I need to check a file version installed (typically) under c:\\Program Files\\Common Files of a 64-bit application.
| On 64-bit operating systems, the ProgramW6432 environment variable points to c:\program files. The full list for a 32-bit app on an English version of Windows:
ProgramFiles => c:\program files (x86)
ProgramFiles(x86) => c:\program files (x86)
ProgramW6432 => c:\program files
CommonProgramFiles => c:\program files (x86)\common files
CommonProgramFiles(x86) => c:\program files (x86)\common files
CommonProgramW6432 => c:\program files\common files
Just a reminder: that folder should not contain anything of interest to a 32-bit program. Technically. Beware of the file system redirector, it will redirect file requests from c:\program files to c:\program files (x86). You'd have to use Wow64DisableWow64FsRedirection() if you'd actually wanted to access files in that directory.
|
2,539,812 | 2,539,876 | Refactor the following two C++ methods to move out duplicate code | I have the following two methods that (as you can see) are similar in most of its statements except for one (see below for details)
unsigned int CSWX::getLineParameters(const SURFACE & surface, vector<double> & params)
{
VARIANT varParams;
surface->getPlaneParams(varParams); // this is the line of code that is different
SafeDoubleArray sdParams(varParams);
for( int i = 0 ; i < sdParams.getSize() ; ++i )
{
params.push_back(sdParams[i]);
}
if( params.size() > 0 ) return 0;
return 1;
}
unsigned int CSWX::getPlaneParameters(const CURVE & curve, vector<double> & params)
{
VARIANT varParams;
curve->get_LineParams(varParams); // this is the line of code that is different
SafeDoubleArray sdParams(varParams);
for( int i = 0 ; i < sdParams.getSize() ; ++i )
{
params.push_back(sdParams[i]);
}
if( params.size() > 0 ) return 0;
return 1;
}
Is there any technique that I can use to move the common lines of code of the two methods out to a separate method, that could be called from the two variations - OR - possibly combine the two methods to a single method?
The following are the restrictions:
The classes SURFACE and CURVE are from 3rd party libraries and hence unmodifiable. (If it helps they are both derived from IDispatch)
There are even more similar classes (e.g. FACE) that could fit into this "template" (not C++ template, just the flow of lines of code)
I know the following could (possibly?) be implemented as solutions but am really hoping there is a better solution:
I could add a 3rd parameter to the 2 methods - e.g. an enum - that identifies the 1st parameter (e.g. enum::input_type_surface, enum::input_type_curve)
I could pass in an IDispatch and try dynamic_cast<> and test which cast is NON_NULL and do an if-else to call the right method (e.g. getPlaneParams() vs. get_LineParams())
The following is not a restriction but would be a requirement because of my teammates resistance:
Not implement a new class that inherits from SURFACE/CURVE etc. (They would much prefer to solve it using the enum solution I stated above)
| A couple ideas come to mind, but here's what I think would be best:
namespace detail
{
void getParameters(const SURFACE& surface, VARIANT& varParams)
{
surface->getPlaneParams(varParams);
}
void getParameters(const CURVE& curve, VARIANT& varParams)
{
curve->get_LineParams(varParams);
}
}
template <typename T>
unsigned int getParameters(const T& curve, vector<double> & params)
{
VARIANT varParams;
detail::getParameters(curve, varParams);
SafeDoubleArray sdParams(varParams);
for( int i = 0 ; i < sdParams.getSize() ; ++i )
{
params.push_back(sdParams[i]);
}
return params.size() != 0;
}
What you do is delegate the task of getting parameters to some other function that is overloaded. Just add functions like that for each different type you have. (Note, I simplified your return statement.)
|
2,539,856 | 2,540,364 | Solving a difficult incomplete type error | I get an incomplete type error when trying to compile my code. I know that it is related to includes, but my project is large and it uses several templates so I can't find which type is actually incomplete. The error message doesn't help either:
Compiling: ../../../addons/ofxTableGestures/src/Graphics/objects/CursorFeedback.cpp
In file included from ../../../addons/ofxTableGestures/ext/boost/fusion/include/invoke_procedure.hpp:10,
from ../../../addons/ofxTableGestures/src/oscGestures/tuioApp.hpp:46,
from /home/thechaos/Projectes/of_preRelease_v0061_linux_FAT/addons/../apps/OF-TangibleFramework/ofxTableGestures/src/Graphics/objects/CursorFeedback.hpp:35,
from /home/thechaos/Projectes/of_preRelease_v0061_linux_FAT/addons/../apps/OF-TangibleFramework/ofxTableGestures/src/Graphics/objects/CursorFeedback.cpp:31:
../../../addons/ofxTableGestures/ext/boost/fusion/functional/invocation/invoke_procedure.hpp: In function ‘void boost::fusion::invoke_procedure(Function, const Sequence&) [with Function = void (tuio::CanBasicFingers<Graphic>::*)(long int, float, float, float, float, float), Sequence = boost::fusion::joint_view<boost::fusion::joint_view<boost::fusion::iterator_range<boost::fusion::vector_iterator<const boost::fusion::vector6<long int, float, float, float, float, float>, 0>, boost::fusion::vector_iterator<boost::fusion::vector6<long int, float, float, float, float, float>, 0> >, const boost::fusion::single_view<tuio::CanBasicFingers<Graphic>*> >, boost::fusion::iterator_range<boost::fusion::vector_iterator<boost::fusion::vector6<long int, float, float, float, float, float>, 0>, boost::fusion::vector_iterator<const boost::fusion::vector6<long int, float, float, float, float, float>, 6> > >]’:
../../../addons/ofxTableGestures/src/oscGestures/tuioApp.hpp:122: instantiated from ‘void tuio::AlternateCallback<C, M, E>::run(tuio::TEvent*) [with C = tuio::CanBasicFingers<Graphic>, M = void (tuio::CanBasicFingers<Graphic>::*)(long int, float, float, float, float, float), E = tuio::TeventBasicFingersMoveFinger]’
/home/thechaos/Projectes/of_preRelease_v0061_linux_FAT/addons/../apps/OF-TangibleFramework/ofxTableGestures/src/Graphics/objects/CursorFeedback.cpp:64: instantiated from here
../../../addons/ofxTableGestures/ext/boost/fusion/functional/invocation/invoke_procedure.hpp:88: error: incomplete type ‘boost::fusion::detail::invoke_procedure_impl<void (tuio::CanBasicFingers<Graphic>::*)(long int, float, float, float, float, float), const boost::fusion::joint_view<boost::fusion::joint_view<boost::fusion::iterator_range<boost::fusion::vector_iterator<const boost::fusion::vector6<long int, float, float, float, float, float>, 0>, boost::fusion::vector_iterator<boost::fusion::vector6<long int, float, float, float, float, float>, 0> >, const boost::fusion::single_view<tuio::CanBasicFingers<Graphic>*> >, boost::fusion::iterator_range<boost::fusion::vector_iterator<boost::fusion::vector6<long int, float, float, float, float, float>, 0>, boost::fusion::vector_iterator<const boost::fusion::vector6<long int, float, float, float, float, float>, 6> > >, 7, true, false>’ used in nested name specifier
If I copy the conflictive code to a same file I can compile it. So I know that the code itself is OK, the problem is the way I instantiate it.
How can I trace the origin of this error? Is there any way to get the trace of the c++ compiler and preprocessor to get more informative messages?
edit: I am using gcc 4.4.1
| It would be easier if you gave us the compiler.
On gcc you can see the preprocessed file using the -E option. If you try compiling the preprocessed file it should get much easier to diagnose. Furthermore you'll see exactly what are the types involved.
As for the specific error, the last line is generally the one indicative:
boost::fusion::detail::invoke_procedure_impl<
void (tuio::CanBasicFingers<Graphic>::*)
(long int, float, float, float, float, float),
const boost::fusion::joint_view<
boost::fusion::joint_view<
boost::fusion::iterator_range<
boost::fusion::vector_iterator<
const boost::fusion::vector6<long int, float, float, float, float,
float>,
0
>,
boost::fusion::vector_iterator<
boost::fusion::vector6<long int, float, float, float, float, float>,
0
>
>,
const boost::fusion::single_view< tuio::CanBasicFingers<Graphic>* >
>, // joint_view
boost::fusion::iterator_range<
boost::fusion::vector_iterator<
boost::fusion::vector6<long int, float, float, float, float, float>, 0
>,
boost::fusion::vector_iterator<
const boost::fusion::vector6<long int, float, float, float, float,
float>,
6
>
> // iterator_range
>,
7,
true,
false
>
Okay, so reformatting helps a bit here.
It seems that you have a namespace tuio which should contain a template class CanBasicFingers of which you'd like to use the Graphic instanciation and obtain a pointer to a member function.
Assuming you've got all the Boost.Fusion includes right, chances are either CanBasicFingers or Graphic are not included correctly.
Otherwise, lookup the mix in the constness of the iterators: the ranges are defined each with a const and a non-const iterator which is downright strange.
You should try and invoke them separately.
As a general technic for diagnosis, I can only recommend Divide And Conquer approaches. You should try to build up the expression little by little:
namespace fusion = boost::fusion;
// First
typedef void (tuio::CanBasicFingers<Graphic>::* function_t)
(long int, float, float, float, float, float);
// Second
typedef fusion::vector6<long int, float, float, float, float, float> vector_t;
// Third: the iterators
typedef fusion::vector_iterator< const vector_t, 0 > const_iterator_begin;
typedef fusion::vector_iterator< const vector_t, 6 > const_iterator_end;
typedef fusion::vector_iterator< vector_t, 0 > iterator_begin;
typedef fusion::vector_iterator< vector_t, 6 > iterator_end;
// Fourth: the ranges
// (which const-ness are oddly messed up)
typedef fusion::iterator_range< const_iterator_begin, iterator_end > range_1;
typedef fusion::iterator_range< iterator_begin, const_iterator_end > range_2;
// Fifth the views
typedef const fusion::single_view<tuio::CanBasicFingers<Graphic>*> single_view;
typedef fusion::joint_view< range_1, single_view > joint_view_internal;
typedef fusion::joint_view< joint_view_internal, range_2 > joint_view_external;
// and here is the final type (aaaah!)
typedef fusion::detail::invoke_procedure_impl<
function_t,
joint_view_external,
7,
true,
false
> procedure_type;
Compiling this decomposed form, should yield the error at a more precise location :)
|
2,539,980 | 2,540,022 | Building an OpenCV application with Visual Studio 2008 and running it from another computer | I've made a simple OpenCV application with Visual Studio 2008 and I've built it in both release mode and debug mode.It works fine from my computer but when I try to run it from another computer which doesn't have OpenCV installed or has another version of Visual Studio with OpenCV it doesn't work.
How can I make the app work from a computer which doesn't have either Visual Studio or OpenCV installed ?
I'm thinking to add the external dependencies ( lib's and dll's ) into the app's folder, change the path in Visual Studio and rebuild it.
Thanks in advance and sorry for the ultranoobish question :)
| You don't need to distribute the libs; those are just needed for building the executable.
Just copy the dlls somewhere where the executable can see them (either in the same dir as the exe, or in a dir that's on the system path) and you should be golden.
|
2,540,126 | 2,540,154 | Problem separating C++ code in header, inline functions and code | I have the simplest code that I want to separate in three files:
Header file: class and struct declarations. No implementations at all.
Inline functions file: implementation of inline methods in header.
Code file: normal C++ code for more complicated implementations.
When I was about to implement an operator[] method, I couldn't manage to compile it. Here is a minimal example that shows the same problem:
Header (myclass.h):
#ifndef _MYCLASS_H_
#define _MYCLASS_H_
class MyClass
{
public:
MyClass(const int n);
virtual ~MyClass();
double& operator[](const int i);
double operator[](const int i) const;
void someBigMethod();
private:
double* arr;
};
#endif /* _MYCLASS_H_ */
Inline functions (myclass-inl.h):
#include "myclass.h"
inline double& MyClass::operator[](const int i) {
return arr[i];
}
inline double MyClass::operator[](const int i) const {
return arr[i];
}
Code (myclass.cpp):
#include "myclass.h"
#include "myclass-inl.h"
#include <iostream>
inline MyClass::MyClass(const int n) {
arr = new double[n];
}
inline MyClass::~MyClass() {
delete[] arr;
}
void MyClass::someBigMethod() {
std::cout << "Hello big method that is not inlined" << std::endl;
}
And finally, a main to test it all:
#include "myclass.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
MyClass m(123);
double x = m[1];
m[1] = 1234;
cout << "m[1]=" << m[1] << endl;
x = x + 1;
return 0;
}
void nothing() {
cout << "hello world" << endl;
}
When I compile it, it says:
main.cpp:(.text+0x1b): undefined reference to 'MyClass::MyClass(int)'
main.cpp:(.text+0x2f): undefined reference to 'MyClass::operator[](int)'
main.cpp:(.text+0x49): undefined reference to 'MyClass::operator[](int)'
main.cpp:(.text+0x65): undefined reference to 'MyClass::operator[](int)'
However, when I move the main method to the MyClass.cpp file, it works. Could you guys help me spot the problem?
Thank you.
| Your main program file used to test your setup does not include the header file with the inline member functions. Since the functions are inline, they are not included in the object file produced from myclass.cpp.
The inline functions are not available to the compiler, so it thinks the calls are external; but they are also not available to the linker, since they do not generate standalone definitions anywhere else.
If you want the functions to be inline, just put them in myclass.h.
|
2,540,218 | 2,540,301 | Get pixel's color in C++, Linux | I'm looking for a possibility to get the color of a pixel with given screen coordinates (x,y) in c++ / Linux? Maybe something similarly like getPixel() in Windows. I spent the whole day to find sth but without any success.
Thanks, Stefan
| See various different techniques posted at http://ubuntuforums.org/showthread.php?t=715256
|
2,540,246 | 2,540,278 | Xerces C++ SAX Parsing Problem: expected class-name before '{' token | I'm trying to run through an example given for the C++ Xerces XML library implementation. I've copied the code exactly, but I'm having trouble compiling it.
error: expected class-name before '{' token
I've looked around for a solution, and I know that this error can be caused by circular includes or not defining a class before it is used, but as you can see from the code, I only have 2 files: MySAXHandler.hpp and MySAXHandler.cpp. However, the MySAXHandler class is derived from HandlerBase, which is included.
MyHandler.hpp
#include <xercesc/sax/HandlerBase.hpp>
class MySAXHandler : public HandlerBase {
public:
void startElement(const XMLCh* const, AttributeList&);
void fatalError(const SAXParseException&);
};
MySAXHandler.cpp
#include "MySAXHandler.hpp"
#include <iostream>
using namespace std;
MySAXHandler::MySAXHandler()
{
}
void MySAXHandler::startElement(const XMLCh* const name,
AttributeList& attributes)
{
char* message = XMLString::transcode(name);
cout << "I saw element: "<< message << endl;
XMLString::release(&message);
}
void MySAXHandler::fatalError(const SAXParseException& exception)
{
char* message = XMLString::transcode(exception.getMessage());
cout << "Fatal Error: " << message
<< " at line: " << exception.getLineNumber()
<< endl;
XMLString::release(&message);
}
I'm compiling like so:
g++ -L/usr/local/lib -lxerces-c -I/usr/local/include -c MySAXHandler.cpp
I've looked through the HandlerBase and it is defined, so I don't know why I can't derive a class from it? Do I have to override all the virtual functions in HandlerBase? I'm kinda new to C++.
Thanks in advance.
| Try adding using namespace xercesc; or explicitly specify the namespace for the Xerces classes (e.g. xercesc::HandlerBase).
Edit: There is also the XERCES_CPP_NAMESPACE_USE macro, which should be equivalent to the using statement.
|
2,540,602 | 2,540,619 | Does C# have a std::nth_element equivalent? | I'm porting some C++ code to C#.
Does C# have an equivalent to std::nth_element() or do I need to roll my own?
| I presume you are looking for an accessor that returns the Nth element of an unordered collection by performing a partial-sort on the collection. This tends to be useful when you have a very large collection and are interested in one of the first elements based on some ordering predicate.
To my knowledge, neither the .NET BCL or LINQ extensions offer an equivalent. All of the sorting methods (including Enumerable.OrderBy) perform a complete ordering of the collection.
If you need an efficient version of Nth, you will need to roll your own extension method on IEnumerable to do so. If you are going to roll you own you may want to look into the Quick Select algorithm, which has O(n) performance.
If the brute-force version is sufficient, you could use LINQ:
var someCollection = new []{ 5, 2, 8, 9, 0, 1, 3, 12, 4 };
var fifthItem = someCollection.NthItem(5);
public static class NthExtensions
{
public static T NthItem(this IEnumerable<T> coll, int n)
{
return coll.OrderBy(x => x).Skip(n - 1).First();
}
}
|
2,540,607 | 2,541,344 | Can one class generate a signal and handled by another class? | I have a buffer in class 'bufferClass' that will generate a signal to tell 'fileClass' that buffer is full and now write data to file? And when 'fileClass' is done writing to file, it will generate a signal to tell 'guiClass' that data can be read from file.
Is this possible? I have been reading http://www.gnu.org/s/libc/manual/html_node/Signal-Handling.html but not too sure how to generate such a signal? I don't need the exact code, just an idea.
Much appreciated.
i am using mac os X, x-code.
| I would use threading.
By having your main class 'fileClass' spin off a thread called 'bufferclass'. When buffer class exits succesfully you will know that your buffer is full.
Intermediate thread url below
http://www.cs.cf.ac.uk/Dave/C/node29.html
|
2,540,740 | 3,450,366 | Using SDL to replace colors using SDL Color Keys | I am working an a simple Roguelike game, and using SDL as the display. The Graphics for the game is an image of Codepage 437, with the background being black, and the font white. Instead of using many seperate image files that are already colored, I want to use one image file, and replace the colors when it is being loaded into memory.
The code to split the codepage into a sprite sheet works properly, but when attempting to print in color, everything comes out in white. I had it working the past, but somehow I broke the code when changing it from change the color at print, to change the color on load. Here is the code to load the image:
SDL_Surface *Screen,*Font[2];
SDL_Rect Character[256];
Uint8 ScreenY,ScreenX;
Uint16 PrintX,PrintY,ScreenSizeY,ScreenSizeX;
Uint32 Color[2];
void InitDisplay()
{
if(SDL_Init(SDL_INIT_VIDEO) == -1) { printf("SDL Init failed\n"); return; }
ScreenSizeY = 600;
ScreenSizeX = 800;
Screen = SDL_SetVideoMode(ScreenSizeX,ScreenSizeY,32,SDL_HWSURFACE | SDL_RESIZABLE);
SDL_WM_SetCaption("Alpha",NULL);
SDL_Surface *Load;
Load = IMG_Load("resource/font.png");
Font[0] = SDL_DisplayFormat(Load);
SDL_FreeSurface(Load);
Color[0] = SDL_MapRGB(Font[0]->format,255,255,255);
Color[1] = SDL_MapRGB(Font[0]->format,255,0,0);
Uint8 i,j,k = 0;
PrintX = 0;
PrintY = 0;
for(i = 0; i < 16; i++) { for(j = 0; j < 16; j++)
{
Character[k].x = PrintX;
Character[k].y = PrintY;
Character[k].w = 8;
Character[k].h = 12;
k++;
PrintX += 8;
} PrintX = 0; PrintY += 12; }
PrintX = 0;
PrintY = 0;
for(i = 1; i < 2; i++)
{
Font[i] = SDL_DisplayFormat(Font[0]);
SDL_SetColorKey(Font[i],SDL_SRCCOLORKEY,Color[i]);
SDL_FillRect(Font[i],&Font[i]->clip_rect,Color[i]);
SDL_BlitSurface(Font[0],NULL,Font[i],NULL);
SDL_SetColorKey(Font[0],0,Color[0]);
}
}
The problem is with the last for loop above. I can't figure out why it isn't working. Any help is greatly appreciated!
| I solved this one a while back. The problem stemmed from doing the color keying in the wrong order. Here is the solved code:
uint8_t i;
uint8_t j;
uint8_t k = 0;
SDL_FillRect(Screen,NULL,0x00000000);
SDL_Rect Offset;
SDL_Surface *Load;
SDL_Surface *LoadFont;
Load = IMG_Load("resource/font.png");
LoadFont = SDL_DisplayFormat(Load);
SDL_FreeSurface(Load);
Offset.x = 0;
Offset.y = 0;
for(i = 0; i < 16; i++) { for(j = 0; j < 16; j++)
{
Character[k].x = Offset.x;
Character[k].y = Offset.y;
Character[k].w = XWIDTH;
Character[k].h = YHIEGHT;
k++;
Offset.x += XWIDTH;
} Offset.x = 0; Offset.y += 12; }
Color[0][0] = SDL_MapRGB(LoadFont->format,255,255,255);
Color[0][1] = SDL_MapRGB(LoadFont->format,96,96,96);
Color[1][0] = SDL_MapRGB(LoadFont->format,255,0,0);
Color[1][1] = SDL_MapRGB(LoadFont->format,96,0,0);
Color[2][0] = SDL_MapRGB(LoadFont->format,0,255,0);
Color[2][1] = SDL_MapRGB(LoadFont->format,0,96,0);
Color[3][0] = SDL_MapRGB(LoadFont->format,0,0,255);
Color[3][1] = SDL_MapRGB(LoadFont->format,0,0,96);
Color[4][0] = SDL_MapRGB(LoadFont->format,255,255,0);
Color[4][1] = SDL_MapRGB(LoadFont->format,96,96,0);
SDL_SetColorKey(LoadFont,SDL_SRCCOLORKEY,Color[0][0]);
for(i=0; i<6; i++) { for(j=0; j<2; j++)
{
Font[i][j] = SDL_DisplayFormat(LoadFont);
SDL_FillRect(Font[i][j],&Font[i][j]->clip_rect,Color[i][j]);
SDL_BlitSurface(LoadFont,NULL,Font[i][j],NULL);
SDL_SetColorKey(Font[i][j],SDL_SRCCOLORKEY,SDL_MapRGB(Font[i][j]->format,0,0,0));
}}
SDL_FreeSurface(LoadFont);
|
2,540,742 | 2,540,973 | Count subset of binary pattern | I have a A=set of strings and a B=seperate string. I want to count the number of occurences in from B in A.
Example :
A:
10001
10011
11000
10010
10101
B:
10001
result would be 3.(10001 is a subset of 10001,10011,10101)
So i need a function that takes a set and string and returns an int.
int myfunc(set<string> , string){
int result;
// My Brain is melting
return result ;
}
edit :
00000 shouldn't be a subset of anything !
| If you have control over the input, and these strings are really supposed to represent bitmasks, then you probably want to keep them as integers of some sort and use bitmasks as suggested by others. Otherwise, if your stuck with dealing with them as strings, and you're going to use the same set of strings to search through multiple times, you're still better off converting them to integral bitmasks.
If, however, the set of strings is only being processed once, you're better off just going through the set and manually checking each once. Offhand, something like this:
int myfunc(set<string> in, string search){
assert(search.length() <= 32);
int result = 0;
for(set<string>::iterator iIn = in.begin(); iIn != in.end(); ++iIn)
{
bool isSubset = true;
if (iIn->length() != search.length()) // Is this guaranteed?
isSubset = false;
for (int iSearch = 0; isSubset && iSearch < search.length; ++iSearch)
if (search[iSearch] == '1' && (*iIn)[iSearch] == '0')
isSubset = false;
if (isSubset)
++result;
}
return result;
}
Or else the convert to long first version:
int myfunc(set<string> in, string search){
int result = 0;
long searchInteger = strtol(search.c_str(), NULL, 2);
for(set<string>::iterator iIn = in.begin(); iIn != in.end(); ++iIn)
if ((strtol(iIn->c_str(), NULL, 2) & searchInteger) == searchInteger)
++result;
return result;
}
|
2,540,838 | 2,540,851 | C++ networking simple send and receive | I'm trying to link 10 computers together, the program I would like to write would have one 'control' computer. From what I've looked up this computer would take all the packets sent over the network and do a echo with them... right? The other computers would need to be able to send information (then echoed to the others) to the 'control' ... is there a easy! or simple way to do this? From what I've seen I want a non-blocking socket?
I have looked into sockets and such but for an amateur programmer like me, this seems like a daunting task :)
I'm kind-of looking for an easy class implication that has a send() and an event driven recv().
I'm not going to be sending that much information over the network.
| http://beej.us/guide/bgnet/
In my opinion the unchallenged best guide to socket programming.
|
2,540,950 | 2,540,965 | Access an element in a set? | With a vector, I can do the following:
vector<int> myvec (4,100);
int first = myvec.at(0);
I have the following set:
set<int> myset;
myset.insert(100);
int setint = ????
How can I access the the element I inserted in the set?
| set<int>::iterator iter = myset.find(100);
if (iter != myset.end())
{
int setint = *iter;
}
|
2,541,175 | 2,541,189 | when to use c++ in managed versus unmanaged mode | I am wondering when I would use c++ in managed versus unmanaged mode?
Are there speed advantages with one mode over the other?
Is it easier to access 3rd party libraries in one mode over the other?
Are there any installation issues to worry about?
| I find that managed mode (C++/CLI) is primarily useful as a gateway facility that allows you to leverage legacy libraries. In short, I used it when I have to program in .Net, but need access to a C++ code base.
On its own, there's very little reason to choose C++/CLI over C#, which is cleaner, more modern, better-supported by the IDE and a gazillion tools (ReSharper, for instance), and can even do occasional low-level stuff via the unsafe keyword.
C++/CLI has been touted by its designers as the most powerful .Net language (largely because of the seamless legacy bridge and true RAII semantics for .Net objects), but it hasn't gotten much traction in the .Net community.
|
2,541,289 | 2,541,317 | Explicitly instantiating a generic member function of a generic structure | I have a structure with a template parameter, Stream. Within that structure, there is a function with its own template parameter, Type.
If I try to force a specific instance of the function to be generated and called, it works fine, if I am in a context where the exact type of the structure is known. If not, I get a compile error. This feels like a situation where I'm missing a typename, but there are no nested types. I suspect I'm missing something fundamental, but I've been staring at this code for so long all I see are redheads, and frankly writing code that uses templates has never been my forte.
The following is the simplest example I could come up with that illustrates the issue.
#include <iostream>
template<typename Stream>
struct Printer {
Stream& str;
Printer(Stream& str_) : str(str_) { }
template<typename Type>
Stream& Exec(const Type& t) {
return str << t << std::endl;
}
};
template<typename Stream, typename Type>
void Test1(Stream& str, const Type& t) {
Printer<Stream> out = Printer<Stream>(str);
/****** vvv This is the line the compiler doesn't like vvv ******/
out.Exec<bool>(t);
/****** ^^^ That is the line the compiler doesn't like ^^^ ******/
}
template<typename Type>
void Test2(const Type& t) {
Printer<std::ostream> out = Printer<std::ostream>(std::cout);
out.Exec<bool>(t);
}
template<typename Stream, typename Type>
void Test3(Stream& str, const Type& t) {
Printer<Stream> out = Printer<Stream>(str);
out.Exec(t);
}
int main() {
Test2(5);
Test3(std::cout, 5);
return 0;
}
As it is written, gcc-4.4 gives the following:
test.cpp: In function 'void Test1(Stream&, const Type&)':
test.cpp:22: error: expected primary-expression before 'bool'
test.cpp:22: error: expected ';' before 'bool'
Test2 and Test3 both compile cleanly, and if I comment out Test1 the program executes, and I get "1 5" as I expect. So it looks like there's nothing wrong with the idea of what I want to do, but I've botched something in the implementation.
If anybody could shed some light on what I'm overlooking, it would be greatly appreciated.
| You need to tell the compiler that the dependent name Printer<Stream>::Exec is a template:
out.template Exec<bool>(t);
It's the same principle as with typename, just that in this case the problematic name is not a type, but a template.
|
2,541,333 | 2,541,339 | What does the .. in #include "../somefile.h" mean | Does it mean search the previous folder for somefile.h or the project folder for somefile.h?
| It means that look for somefile.h in the parent folder with respect to the source file where the include directive is found.
In *nix systems(thats where this convention came from AFAIK):
. manse the current directory.
.. means one level up from the current directory.
For example, if you have the following directories structure:
home
|
code
| src
| someOtherDirectory
Your source file could be in home/code/src and you have:
#include "../somefile.h"
in your source code, then the compiler is going to look for somefile.h in home/code/
|
2,541,415 | 2,541,559 | creating QT gui using a thread in c++? | I am trying to create this QT gui using a thread but no luck. Below is my code. Problem is gui never shows up.
/*INCLUDES HERE...
....
*/
using namespace std;
struct mainStruct {
int s_argc;
char ** s_argv;
};
typedef struct mainStruct mas;
void *guifunc(void * arg);
int main(int argc, char * argv[]) {
mas m;<br>
m.s_argc = argc;
m.s_argv = argv;
pthread_t threadGUI;
//start a new thread for gui
int result = pthread_create(&threadGUI, NULL, guifunc, (void *) &m);
if (result) {
printf("Error creating gui thread");
exit(0);
}
return 0;
}
void *guifunc(void * arg)
{
mas m = *(mas *)arg;
QApplication app(m.s_argc,m.s_argv);
//object instantiation
guiClass *gui = new guiClass();
//show gui
gui->show();
app.exec();
}
| There appears to be two major issues here:
The GUI is not appearing because your main() function is completing after creating the thread, thus causing the process to exit straight away.
The GUI should be created on the main thread. Most frameworks require the GUI to be created, modified and executed on the main thread. You spawn threads to do work and send updates to the main thread, not the other way around.
Start with a regular application, based on the Qt sample code. If you use Qt Creator, it can provide a great deal of help and skeleton code to get you started. Then once you have a working GUI, you can start looking at adding worker threads if you need them. But you should do some research on multithreading issues, as there are many pitfalls for the unwary. Have fun!
|
2,541,433 | 2,541,509 | Split a Large File In C++ | I'm trying to write a program that takes a large file (of any type) and splits it into many smaller "chunks". I think I have the basic idea down, but for some reason I cannot create a chunk size over 12 kb. I know there are a few solutions on google, etc. but I am more interested in learning what the origin of this limitation is then actually using the program to split files.
//This file splits are larger into smaller files of a user inputted size.
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include <direct.h>
#include <stdlib.h>
using namespace std;
void GetCurrentPath(char* buffer)
{
_getcwd(buffer, _MAX_PATH);
}
int main()
{
// use the function to get the path
char CurrentPath[_MAX_PATH];
GetCurrentPath(CurrentPath);//Get the current directory (used for displaying output)
fstream bigFile;
string filename;
int partsize;
cout << "Enter a file name: ";
cin >> filename; //Recieve target file
cout << "Enter the number of bites in each smaller file: ";
cin >> partsize; //Recieve volume size
bigFile.open(filename.c_str(),ios::in | ios::binary);
bigFile.seekg(0, ios::end); // position get-ptr 0 bytes from end
int size = bigFile.tellg(); // get-ptr position is now same as file size
bigFile.seekg(0, ios::beg); // position get-ptr 0 bytes from beginning
for (int i = 0; i <= (size / partsize); i++)
{
//Build File Name
string partname = filename; //The original filename
string charnum; //archive number
stringstream out; //stringstream object out, used to build the archive name
out << "." << i;
charnum = out.str();
partname.append(charnum); //put the part name together
//Write new file part
fstream filePart;
filePart.open(partname.c_str(),ios::out | ios::binary); //Open new file with the name built above
//Check if near the end of file
if (bigFile.tellg() < (size - (size%partsize)))
{
filePart.write(reinterpret_cast<char *>(&bigFile),partsize); //Write the selected amount to the file
filePart.close(); //close file
bigFile.seekg(partsize, ios::cur); //move pointer to next position to be written
}
//Changes the size of the last volume because it is the end of the file
else
{
filePart.write(reinterpret_cast<char *>(&bigFile),(size%partsize)); //Write the selected amount to the file
filePart.close(); //close file
}
cout << "File " << CurrentPath << partname << " produced" << endl; //display the progress of the split
}
bigFile.close();
cout << "Split Complete." << endl;
return 0;
}
Any ideas?
| You are writing to the split file, but not reading from the bigfile. What you are writing it the in-memory structure of the bigfile, not the contents of bigfile. You need to allocate a buffer, read into it from bigfile and write it to the splitfile(s).
|
2,541,446 | 2,541,549 | Exposing a pointer in Boost.Python | I have this very simple C++ class:
class Tree {
public:
Node *head;
};
BOOST_PYTHON_MODULE(myModule)
{
class_<Tree>("Tree")
.def_readwrite("head",&Tree::head)
;
}
I want to access the head variable from Python, but the message I see is:
No to_python (by-value) converter found for C++ type: Node*
From what I understand, this happens because Python is freaking out because it has no concept of pointers. How can I access the head variable from Python?
I understand I should use encapsulation, but I'm currently stuck with needing a non-encapsulation solution.
| Of course, I find the answer ten minutes after asking the question...here's how it's done:
class_<Tree>("Tree")
.add_property("head",
make_getter(&Tree::head, return_value_policy<reference_existing_object>()),
make_setter(&Tree::head, return_value_policy<reference_existing_object>()))
;
|
2,541,608 | 2,541,699 | Sorting a file with 55K rows and varying Columns | I want to find a programmatic solution using C++.
I have a 900 files each of 27MB size. (just to inform about the enormity ).
Each file has 55K rows and Varying columns. But the header indicates the columns
I want to sort the rows in an order w.r.t to a Column Value.
I wrote the sorting algorithm for this (definitely my newbie attempts, you may say).
This algorithm is working for few numbers, but fails for larger numbers.
Here is the code for the same:
basic functions I defined to use inside the main code:
int getNumberOfColumns(const string& aline)
{
int ncols=0;
istringstream ss(aline);
string s1;
while(ss>>s1) ncols++;
return ncols;
}
vector<string> getWordsFromSentence(const string& aline)
{
vector<string>words;
istringstream ss(aline);
string tstr;
while(ss>>tstr) words.push_back(tstr);
return words;
}
bool findColumnName(vector<string> vs, const string& colName)
{
vector<string>::iterator it = find(vs.begin(), vs.end(), colName);
if ( it != vs.end())
return true;
else return false;
}
int getIndexForColumnName(vector<string> vs, const string& colName)
{
if ( !findColumnName(vs,colName) ) return -1;
else {
vector<string>::iterator it = find(vs.begin(), vs.end(), colName);
return it - vs.begin();
}
}
////////// I like the Recurssive functions - I tried to create a recursive function
///here. This worked for small values , say 20 rows. But for 55K - core dumps
void sort2D(vector<string>vn, vector<string> &srt, int columnIndex)
{
vector<double> pVals;
for ( int i = 0; i < vn.size(); i++) {
vector<string>meancols = getWordsFromSentence(vn[i]);
pVals.push_back(stringToDouble(meancols[columnIndex]));
}
srt.push_back(vn[max_element(pVals.begin(), pVals.end())-pVals.begin()]);
if (vn.size() > 1 ) {
vn.erase(vn.begin()+(max_element(pVals.begin(), pVals.end())-pVals.begin()) );
vector<string> vn2 = vn;
//cout<<srt[srt.size() -1 ]<<endl;
sort2D(vn2 , srt, columnIndex);
}
}
Now the main code:
for ( int i = 0; i < TissueNames.size() -1; i++)
{
for ( int j = i+1; j < TissueNames.size(); j++)
{
//string fname = path+"/gse7307_Female_rma"+TissueNames[i]+"_"+TissueNames[j]+".txt";
//string fname2 = sortpath2+"/gse7307_Female_rma"+TissueNames[i]+"_"+TissueNames[j]+"Sorted.txt";
string fname = path+"/gse7307_Male_rma"+TissueNames[i]+"_"+TissueNames[j]+".txt";
string fname2 = sortpath2+"/gse7307_Male_rma"+TissueNames[i]+"_"+TissueNames[j]+"4Columns.txt";
vector<string>AllLinesInFile;
BioInputStream fin(fname);
string aline;
getline(fin,aline);
replace (aline.begin(), aline.end(), '"',' ');
string headerline = aline;
vector<string> header = getWordsFromSentence(aline);
int pindex = getIndexForColumnName(header,"p-raw");
int xcindex = getIndexForColumnName(header,"xC");
int xeindex = getIndexForColumnName(header,"xE");
int prbindex = getIndexForColumnName(header,"X");
string newheaderline = "X\txC\txE\tp-raw";
BioOutputStream fsrt(fname2);
fsrt<<newheaderline<<endl;
int newpindex=3;
while ( getline(fin, aline) ){
replace (aline.begin(), aline.end(), '"',' ');
istringstream ss2(aline);
string tstr;
ss2>>tstr;
tstr = ss2.str().substr(tstr.length()+1);
vector<string> words = getWordsFromSentence(tstr);
string values = words[prbindex]+"\t"+words[xcindex]+"\t"+words[xeindex]+"\t"+words[pindex];
AllLinesInFile.push_back(values);
}
vector<string>SortedLines;
sort2D(AllLinesInFile, SortedLines,newpindex);
for ( int si = 0; si < SortedLines.size(); si++)
fsrt<<SortedLines[si]<<endl;
cout<<"["<<i<<","<<j<<"] = "<<SortedLines.size()<<endl;
}
}
can some one suggest me a better way of doing this?
why it is failing for larger values. ?
The primary function of interest for this query is Sort2D function.
thanks for the time and patience.
prasad.
| I'm not sure why your code is crashing, but recursion in that case is only going to make the code less readable. I doubt it's a stack overflow, however, because you're not using much stack space in each call.
C++ already has std::sort, why not use that instead? You could do it like this:
// functor to compare 2 strings
class CompareStringByValue : public std::binary_function<string, string, bool>
{
public:
CompareStringByValue(int columnIndex) : idx_(columnIndex) {}
bool operator()(const string& s1, const string& s2) const
{
double val1 = stringToDouble(getWordsFromSentence(s1)[idx_]);
double val2 = stringToDouble(getWordsFromSentence(s2)[idx_]);
return val1 < val2;
}
private:
int idx_;
};
To then sort your lines you would call
std::sort(vn.begin(), vn.end(), CompareByStringValue(columnIndex));
Now, there is one problem. This will be slow because stringToDouble and getWordsFromSentence are called multiple times on the same string. You would probably want to generate a separate vector which has precalculated the values of each string, and then have CompareByStringValue just use that vector as a lookup table.
Another way you can do this is insert the strings into a std::multimap<double, std::string>. Just insert the entries as (value, str) and then read them out line-by-line. This is simpler but slower (though has the same big-O complexity).
EDIT: Cleaned up some incorrect code and derived from binary_function.
|
2,541,615 | 2,541,937 | error by creating process | hello i want to get startet with programming with WIN32, therefore i wrote a programm that creates a process but in the line of code where i create the process the programm gets an error an dosn't work (abend). i don't know if the code in programm 1 is wrong or the code in the second programm that should be created by the first. ( I don't know if the code in the first programm after "createprocess" is right because i didn't get further with debugging, because in this line i get the error.(i tested it without the cout,waitforobject and close handle but i didn't work either )).
First Programm:
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
void main()
{
bool ret;
bool retwait;
STARTUPINFO startupinfo;
GetStartupInfo (&startupinfo);
PROCESS_INFORMATION pro2info;
ret = CreateProcess(NULL, L"D:\\betriebssystemePRA1PRO2.exe", NULL, NULL, false, CREATE_NEW_CONSOLE, NULL,
NULL, &startupinfo, &pro2info);
cout<<"hProcess: "<<pro2info.hProcess<<endl;
cout<<"dwProcessId: "<<pro2info.dwProcessId <<endl;
retwait= WaitForSingleObject (pro2info.hProcess, 100);
retwait= WaitForSingleObject (pro2info.hProcess, 100);
CloseHandle (pro2info.hProcess);//prozesshandle schließen
retwait= WaitForSingleObject (pro2info.hProcess, 100);
ExitProcess(0);
}
Seconde Programm:
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
void main()
{
int b;
b=GetCurrentProcessId();
cout<<b<<endl;
cout<<"Druecken Sie Enter zum Beenden"<<endl;
cin.get();
//warten bis Benutzer bestätigt
Sleep (700);
ExitProcess(0);
cout<<"test";
}
Thanks in advance
| Notice the type of the lpCommandLine parameter to CreateProcess -- it is LPTSTR, not LPCTSTR, i.e. it is not const.
This means that CreateProcess reserves the right to actually modify the contents of lpCommandLine. However, you have provided a pointer to a string literal as parameter, and string literals are immutable (they come from your program's read-only data segment and attempts to alter them will typically result in an access violation error.)
To fix this, simply change your code not to use an immutable string literal:
wchar_t wcsCommandLine[] = L"D:\\betriebssystemePRA1PRO2.exe";
ret = CreateProcess(NULL, wcsCommandLine, NULL, NULL, ...
Interestingly enough, CreateProcessW (UNICODE) attempts to write to lpCommandLine whereas CreateProcessA (ANSI) does not, and surprise -- your first program is built as UNICODE (were you to build it as ANSI it would work out of the box, at least on Windows XP.)
I can confirm that, with the above modification, your code works.
Also note that:
unless you need to specify D:\\betriebssystemePRA1PRO2.exe's window title, position etc. you do not need to supply a STARTUPINFO structure at all, you can simply pass lpStartupInfo as NULL and a default will be used
you should not be calling WaitForSingleObject on a closed handle
|
2,541,663 | 2,541,715 | Operator() as a subscript (C++) | I use operator() as a subscript operator this way:
double CVector::operator() (int i) const
{
if (i >= 0 && i < this->size)
return this->data[i];
else
return 0;
}
double& CVector::operator() (int i)
{
return (this->data[i]);
}
It works when I get values, but I get an error when I try to write assign a value using
a(i) = 1;
UPD: Error text:
Unhandled exception at 0x651cf54a
(msvcr100d.dll) in CG.exe: 0xC0000005:
Access violation reading location
0xccccccc0.
| Like I said in my comment, the problem is your flawed design. I make a 100% guarantee on one of two things:
The value you are passing to the assignment function is out of valid range.
The member data is pointing to invalid space in memory.
In either case, I would suggest adding:
#include <cassert>
and adding assert(i >= 0 && i < this->size) instead of the silent failures:
double CVector::operator() (int i) const
{
assert(i >= 0 && i < this->size);
return this->data[i];
}
double& CVector::operator() (int i)
{
assert(i >= 0 && i < this->size);
return (this->data[i]);
}
|
2,541,686 | 2,541,721 | Multiple Instances of Static Singleton | I've recently been working with code that looks like this:
using namespace std;
class Singleton {
public:
static Singleton& getInstance();
int val;
};
Singleton &Singleton::getInstance() {
static Singleton s;
return s;
}
class Test {
public:
Test(Singleton &singleton1);
};
Test::Test(Singleton &singleton1) {
Singleton singleton2 = Singleton::getInstance();
singleton2.val = 1;
if(singleton1.val == singleton2.val) {
cout << "Match\n";
} else {
cout << "No Match " << singleton1.val << " - " << singleton2.val << "\n";
}
}
int main() {
Singleton singleton = Singleton::getInstance();
singleton.val = 2;
Test t(singleton);
}
Every time I run it I get "No Match". Yet I am expecting a match since there should only be one instance of the class. From what I can tell when stepping through with GDB is that there are two instances of the Singleton. Why is this?
| The first line of Test::Test creates another instance of Singleton (on the stack, your local isn't a reference). You could prevent this by defining the default constructor on Singleton and making it private. As it stands, anybody can create an instance of Singleton.
|
2,541,714 | 5,530,352 | Adding click/double-click events to static group box controls | Having realised my own reasons were way too dubious, I've now gone about this a different way. But I'm still curious...
For reasons of nostalgia, familiarity and laziness, I'm coding a UI with MFC. For dubious reasons (as if those were not enough), I wanted to add a (double-)click event to a group box. Naturally, the group box contains things - in fact, it contains another static item, to which I can successfully add a (double-)click event handler.
Is there any reason I cannot get an event handler to work for clicks on my group box the same way I can do that for the simple text static item? No amount of clicking on, in or near the control fires the event.
Note - I've read through http://www.codeproject.com/KB/static/staticctrl_tut.aspx and tried responding to both ON_STN_... events and ON_BN_... messages, setting the notify style (BS_NOTIFY appears in the rc file)... and still I'm missing something - what is it? Is it even possible? Most of what I've googled suggests it is... but without clear answers for C++/MFC.
Since first posting this question, I've found reference to a WM_NCHITTEST message, and hints that you have to create a handler for this message to override the group box default behaviour of responding with HT_TRANSPARENT... despite having its transparent property in ClassWizard set to false. Hmmm. Can anyone confirm that this is indeed the key?
| I think WM_NCHHITTEST/HT_TRANSPARENT is indeed the key here.
Group boxes are an odd sort of control: while it looks like they contain other controls, they are actually siblings of those controls in the HWND tree. So a groupbox that looks like it contains two buttons is actually a sibling of those buttons - and could come before or after it in the HWND hierarchy.
Group boxes respond to WM_NCHITTEST with HT_TRANSPARENT, so that mouse clicks go right through them. One benefit of this is that it doesn't matter whether the group box comes before or after the controls that it appears to contain in the window order; the clicks will end up being routed to those controls, not the groupbox.
To get double-clicking (or just plain clicking) on the groupbox to work, you'd need to do two things:
override the default WM_NCHITTEST behavior and instead return HT_CLIENT, like a regular control; at this point it should be capable of getting WM_LBUTTONDOWN and related events that would otherwise have gone elsewhere (to a sibling, or to the dialog itself).
ensure that the contents of the groupbox come *before* it in the HWND z-order, so that they are no longer relying on clicks going 'through' the groupbox. (At least I think you want them to be before; either way, you may need to play with the HWND ordering now that it's significant again.)
Note that this is a different type of transparency again from the WS_EX_TRANSPARENT, which might be what the Transparent class wizard property maps to. Grossly simplified, HT_TRANSPARENT has to do with being transparent to the mouse; WS_EX_TRANSPARENT is more about being painted last so that siblings "show through".
|
2,541,970 | 2,541,983 | Could someone tell me if my C++ indent style is named? (example given) | I'm learning C++. For me, my programming style is just what looks the best; it doesn't seem to follow the rules of any one particular style. Here's an example
void f(int x){ //no space between close-paren and bracket
if (!x){
cout << "x is non-zero\n";
} //closing bracket indented to the same level as the original statement
}
It's only slightly different for something like a class or a namespace:
class myClass {}; //space between class name and bracket, otherwise the same as functions
K&R style does uses that kind of bracketing for statements, but my style uses it for everything. I'd like to know if there's a name for it so I can say simply what my indent style is without having to explain using examples like these.
| Looks BSD KNF style. see http://en.wikipedia.org/wiki/Indent_style
(note, it's also the same style I prefer :) )
|
2,541,977 | 2,541,998 | C++ string array binary search | string Haystack[] = { "Alabama", "Alaska", "American Samoa", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia",
"Florida", "Georgia", "Guam", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky",
"Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska",
"Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Northern Mariana Islands", "Ohio", "Oklahoma",
"Oregon", "Pennsylvania", "Puerto Rico", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "US Virgin Islands", "Utah",
"Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"};
string Needle = "Virginia";
if(std::binary_search(Haystack, Haystack+56, Needle))
cout<<"Found";
If I also wanted to find the location of the needle in the string array, is there an "easy" way to find out?
| From the SGI docs:
Note that this is not necessarily the information you are interested in! Usually, if you're testing whether an element is present in a range, you'd like to know where it is (if it's present), or where it should be inserted (if it's not present). The functions lower_bound, upper_bound, and equal_range provide this information.
I think the reasoning behind this set of interfaces is that binary_search doesn't really indicate whether it'll return the start of the range of matches (assuming there are matches) or the end of the range, and you might want one or the other depending on whether you want to do something with data already in the container or add a new item (possibly to the end of the matching range). Or you might want to pass the whole range on to something else. Hence the various more or less specific interfaces to perform a binary search.
Unfortunately, you're not particularly likely to find the other ones if you're thinking, "I need a binary search routine".
|
2,542,089 | 2,542,130 | How can I find the memory available on an SD card on a wince device (C++) | I'm looking for a way (on a pocketPC) to interrogate the size/remaining size of an SD card.
I have to create some files on the SD card and I want to make sure there's enough room before I write to it.
| Look at GetDiskFreeSpaceEx() : http://msdn.microsoft.com/en-us/library/aa912270.aspx
|
2,542,123 | 2,542,140 | Is there any thing hashmap can do but map cannot? | I only know that the difference between hashmap and map is that hashmap is implemented with hash function but map is implemented with tree. Could any body add anything more?
Based on this, is there any thing hashmap can do but map cannot?
|
Hashmaps have average case better performance for access (O(1)), but worse worst case performance (O(n)). Maps are always O(lg(n)).
Maps are ordered by their key, hashmaps are not.
Hashmaps generally use more memory than maps.
Maps typically allow for faster iteration.
Good hash functions are harder to write than good ordering functions (and more difficult to analyse).
I don't believe there's anything that a hashmap can do that a map can't.
|
2,542,273 | 2,542,415 | c++ g++ llvm-clang compiler profiling | Note, my question is not: how do I tell my compiler to compile with profiling on.
I want to profile my compiles process. For each file, I'd like to know how much time is spent on each line of the program.
I'm working on a project, some files have huge compile times, I'm trying to figure out why.
Is there anyway to do this with g++ or llvm-clang?
Thanks!
Output of -v -ftime-report (what oes it mean)?
In the following, is "parser" or "expand" the use of templates?
Execution times (seconds)
callgraph construction: 0.06 ( 2%) usr 0.00 ( 0%) sys 0.09 ( 2%) wall 3181 kB ( 1%) ggc
callgraph optimization: 0.05 ( 2%) usr 0.00 ( 0%) sys 0.05 ( 1%) wall 5243 kB ( 2%) ggc
cfg cleanup : 0.02 ( 1%) usr 0.00 ( 0%) sys 0.02 ( 0%) wall 11 kB ( 0%) ggc
df live regs : 0.01 ( 0%) usr 0.00 ( 0%) sys 0.01 ( 0%) wall 0 kB ( 0%) ggc
df reg dead/unused notes: 0.03 ( 1%) usr 0.00 ( 0%) sys 0.03 ( 1%) wall 1993 kB ( 1%) ggc
register information : 0.04 ( 1%) usr 0.00 ( 0%) sys 0.04 ( 1%) wall 0 kB ( 0%) ggc
alias analysis : 0.01 ( 0%) usr 0.00 ( 0%) sys 0.01 ( 0%) wall 450 kB ( 0%) ggc
rebuild jump labels : 0.03 ( 1%) usr 0.00 ( 0%) sys 0.03 ( 1%) wall 0 kB ( 0%) ggc
preprocessing : 0.12 ( 4%) usr 0.06 (12%) sys 1.46 (27%) wall 2752 kB ( 1%) ggc
parser : 0.67 (21%) usr 0.15 (29%) sys 0.89 (16%) wall 91749 kB (36%) ggc
name lookup : 0.15 ( 5%) usr 0.12 (24%) sys 0.24 ( 4%) wall 14384 kB ( 6%) ggc
inline heuristics : 0.03 ( 1%) usr 0.00 ( 0%) sys 0.03 ( 1%) wall 0 kB ( 0%) ggc
tree gimplify : 0.06 ( 2%) usr 0.01 ( 2%) sys 0.09 ( 2%) wall 15992 kB ( 6%) ggc
tree eh : 0.02 ( 1%) usr 0.01 ( 2%) sys 0.03 ( 1%) wall 4405 kB ( 2%) ggc
tree CFG construction : 0.01 ( 0%) usr 0.01 ( 2%) sys 0.03 ( 1%) wall 6636 kB ( 3%) ggc
tree CFG cleanup : 0.02 ( 1%) usr 0.01 ( 2%) sys 0.02 ( 0%) wall 15 kB ( 0%) ggc
tree find ref. vars : 0.00 ( 0%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 1870 kB ( 1%) ggc
tree SSA rewrite : 0.01 ( 0%) usr 0.00 ( 0%) sys 0.01 ( 0%) wall 2357 kB ( 1%) ggc
tree SSA other : 0.00 ( 0%) usr 0.01 ( 2%) sys 0.00 ( 0%) wall 37 kB ( 0%) ggc
tree operand scan : 0.01 ( 0%) usr 0.04 ( 8%) sys 0.06 ( 1%) wall 6340 kB ( 2%) ggc
tree SSA to normal : 0.05 ( 2%) usr 0.00 ( 0%) sys 0.05 ( 1%) wall 95 kB ( 0%) ggc
dominance computation : 0.04 ( 1%) usr 0.00 ( 0%) sys 0.04 ( 1%) wall 0 kB ( 0%) ggc
expand : 0.60 (18%) usr 0.03 ( 6%) sys 0.71 (13%) wall 45557 kB (18%) ggc
varconst : 0.02 ( 1%) usr 0.00 ( 0%) sys 0.02 ( 0%) wall 3532 kB ( 1%) ggc
jump : 0.00 ( 0%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 1745 kB ( 1%) ggc
mode switching : 0.01 ( 0%) usr 0.00 ( 0%) sys 0.01 ( 0%) wall 0 kB ( 0%) ggc
integrated RA : 0.35 (11%) usr 0.00 ( 0%) sys 0.35 ( 6%) wall 5259 kB ( 2%) ggc
reload : 0.29 ( 9%) usr 0.01 ( 2%) sys 0.31 ( 6%) wall 6490 kB ( 3%) ggc
thread pro- & epilogue: 0.10 ( 3%) usr 0.01 ( 2%) sys 0.13 ( 2%) wall 4832 kB ( 2%) ggc
final : 0.19 ( 6%) usr 0.01 ( 2%) sys 0.21 ( 4%) wall 2985 kB ( 1%) ggc
symout : 0.25 ( 8%) usr 0.01 ( 2%) sys 0.26 ( 5%) wall 27322 kB (11%) ggc
TOTAL : 3.25 0.51 5.49 256741 kB
| Try these command line options with g++
-v -ftime-report
That should give you more information on the compiling process. The culprit is usually templates though.
|
2,542,299 | 2,542,543 | Insight into how things get printed onto the screen (cout,printf) and origin of really complex stuff that I can't seem to find on textbooks | I've always wondered this, and still haven't found the answer. Whenever we use "cout" or "printf" how exactly is that printed on the screen?. How does the text come out as it does...(probably quite a vague question here, ill work with whatever you give me.). So basically how are those functions made?..is it assembly?, if so where does that begin?. This brings on more questions like how on earth have they made openGl/directx functions..
break it down people break it down.:)
| Here's one scenario, with abbreviations:
printf or cout put characters into a buffer in the user program's address space.
Eventually the buffer fills, or perhaps printf asks for the buffer to be emptied early. Either way, the I/O library calls the operating system, which copies the contents of the buffer to its own space.
Supposing that the output file is bound to a terminal, the operating system delivers the characters to the terminal application.
The terminal app decides that for each character in the buffer, it needs to paint pixels on the screen.
The terminal app sets up pixel-painting instructions, and it asks a window manager to do this on its behalf. (On Unix these days this is usually an X server.)
The window manager takes the pixels. If the window is actually visible on the screen, the window manager then updates a buffer (called the frame buffer) which holds the visible pixels. The window manager may then notify the operating system, or more likely, the window manager is in cahoots with the operating system and they are sharing the same memory.
The next time the screen is refreshed, the hardware sees the new bits in the frame buffer, and it paints the screen differently.
Voilà! You have characters on the screen.
It is amazing that the bear dances at all.
|
2,542,343 | 2,542,360 | Mutual class instances in C++ | What is the issue with this code?
Here we have two files: classA.h and classB.h
classA.h:
#ifndef _class_a_h_
#define _class_a_h_
#include "classB.h"
class B; //????
class A
{
public:
A() {
ptr_b = new B(); //????
}
virtual ~A() {
if(ptr_b) delete ptr_b; //????
num_a = 0;
}
int num_a;
B* ptr_b; //????
};
#endif //_class_a_h_
classB.h:
#ifndef _class_b_h_
#define _class_b_h_
#include "classA.h"
class A; //????
class B
{
public:
B() {
ptr_a = new A(); //????
num_b = 0;
}
virtual ~B() {
if(ptr_a) delete ptr_a; //????
}
int num_b;
A* ptr_a; //????
};
#endif //_class_b_h_
when I try to compile it, the compiler (g++) says:
classB.h: In constructor ‘B::B()’:
classB.h:12: error: invalid use of incomplete type ‘struct A’
classB.h:6: error: forward declaration of ‘struct A’
classB.h: In destructor ‘virtual B::~B()’:
classB.h:16: warning: possible problem detected in invocation of delete operator:
classB.h:16: warning: invalid use of incomplete type ‘struct A’
classB.h:6: warning: forward declaration of ‘struct A’
classB.h:16: note: neither the destructor nor the class-specific operator delete will be
called, even if they are declared when the class is defined.
| You cannot create instances of an incomplete type (the compiler doesn't know anything about the class!)
You need to move the definitions of your functions (the constructor of A and B) into a C++ file that can include both headers (or into several C++ files, if you follow the convention that you have one class per file).
That having been said, your code as written has a serious problem: every A creates an instance of B and every B creates and instance of A. You will end up with an infinite recursion and you will eventually run out of memory.
Two minor nitpicks: you do not need to test whether a pointer is null before calling delete on it (it is safe to delete a null pointer), and you need to change your include guards (names beginning with an underscore in the global namespace are reserved to the implementation).
|
2,542,349 | 2,542,444 | Static functions vs const functions | I'm looking at a member function
int funct(int x) const;
And I'm wondering if
static int funct(int x);
would be better.
If a member function doesn't use any of the member variables should it be static? Are there any things that would discourage this?
| Assuming this is C++, a function declared as const indicates that it does not intend to change data members on the instance on which it is called, i.e., the this pointer. Since there are ways to evade this, it is not a guarantee, merely a declaration.
A static function does not operate on a specific instance and thus does not take a "this" pointer. Thus, it is "const" in a very naive way.
If your method does not need to be bound to a specific instance, it makes sense to make it static.
However, if your method is polymorphic - that is, you provide a different implementation based on the instance of the object on which it is invoked, then it cannot be static, because it does depend on a specific instance.
|
2,542,400 | 2,542,454 | What Gotchas When Learning C++, If I came from PHP/Java? | I need to learn C++ in order to learn building Nokia WRT and or maemo application.
I need to know what gotchas and what aspect of C++ that I need/have to learn or focus more.
One thing I got in my mind is that C++ doesn't have garbage collector. Therefor, I need to focus on variable type. But, is there any others that really important and I can't ignore it?
| Main gotcha is to try to envisage C++ in terms of how it differs from PHP or Java.
Sorry, it just doesn't work like that. C++ differs from those languages in almost every important respect beyond the syntax for arithmetic. Sometimes the differences are subtle. You need to learn it fresh, and not think that something that's appropriate to do in PHP or Java will work well for you in C++.
That said, common difficulties include:
resource management: RAII; implementing copy constructors, destructors and operator=; avoiding having to implement copy ctors, dtors, operator=.
understanding what references, pointers, values and automatic variables are.
avoiding undefined behaviour (myarray[i] = i++; is a favourite). PHP and Java are both more "tightly" defined languages than C++: firstly the behaviour of a program is more likely to be defined and hence reliable. Because of this, separate implementations are more similar than C++ implementations. It's pretty easy to write a program in C++ that doesn't just do the wrong thing, it does wildly different things on different runs, including crashing, corrupting data, etc.
learning to safely and effectively use templates, multiple inheritance, operator overloading, and other features you're not familiar with.
correct idioms for throwing and catching exceptions (throw by value, catch by reference, don't throw out of a destructor).
writing portable code (understanding the difference between what the standard guarantees, and what isn't guaranteed but that your implementation happens to do. implementation-defined behavior such as the sizes of fundamental types).
C++'s standard libraries are limited compared with Java or PHP. You will be using non-standard libraries as well. For instance, Maemo uses GTK+ and/or Qt. Often the answer to "how can I do X in C++" is, "you can't do it using only standard C++, you need platform-specific APIs or a portable library compiled for your system". X can be graphics, sockets, regular expressions, multi-threading, XML handling, crypto. Especially with mobile platforms you need to keep an eye on OS versions, things can and will change under you from time to time.
|
2,542,447 | 2,543,107 | linking error in Visual c++ when trying to inline functions | When trying to inline a function in Visual C++ (2008 express), I got a linking error, after a close inspection of the code, what I discovered is that the function I am trying to inline throws an exception... if I remove the exception throwing, the linking error goes away, can someone explain why it is the case?
int com_ximpleware::FastIntBuffer::intAt(int index){
if (index < 0 || index > size - 1) {
throw InvalidArgumentException("invalid index range in FastIntBuffer's intAt()");
}
return ((int *) al->get(index>>exp))[index & r];
}
The exaxt error is shown below:
intHash.obj : error LNK2019: unresolved external symbol "public: int __thiscall com_ximpleware::FastIntBuffer::intAt(int)" (?intAt@FastIntBuffer@com_ximpleware@@QAEHH@Z) referenced in function __catch$?isUnique@IntHash@com_ximpleware@@QAE_NH@Z$0
1>C:\new_cvs\cpp_test1\Debug\cpp_test1.exe : fatal error LNK1120: 1 unresolved externals
One more thing, this function was invoked else normally, the calling part of the function wasn't included.
| You'll have to place your definition in the header file.
An inline member function can be defined in two ways:
Define the member function in the class body itself.
Declare the member function just like a normal member function inside the class but when you define the inline member function, prepend the member function's definition with the keyword inline and put the definition into a header file, like the following:
class ClassA
{
public:
void f();
};
inline void ClassA::f()
{
}
If you put the inline function's definition into a .cpp file and it if it is called from some other .cpp file, you'll get an "unresolved external" error (C++ FAQ Lite) from the linker.
I don't think it has something to do with the exception being thrown though. I could replicate this problem in Visual C++ 2005 even if the exception is not thrown.
My guess is that it was trying to inline the function but couldn't find its definition, since it was on a separate .cpp file. The compiler probably made some special processing because it recognized the inline keyword in the definition. If you remove the inline keyword, the problem disappears and linking is successful. Therefore, you need to place the definition together with its declaration in the header file, if you want it to be treated as inline.
|
2,542,451 | 2,542,481 | Can I pass a child class to a reference of a parent class? | I have a class A which takes a reference of B in its constructor.
class A {
public:
A(B& b);
}
And I have a class SubB which is a child class of B:
class SubB : public B {
//omitted...
}
In my code, I create a SubB and pass it to A:
SubB subB;
A a(subB);
But I get this compile Error:
error: ‘B’ is an inaccessible base of ‘SubB’
Can I pass a reference of SubB as B?
Thank you.
| The posted code looks correct though declaration of class B is missing. Post more complete snippet - you problem is likely in misplacing include files and class declarations.
|
2,542,460 | 2,542,522 | Is there a nice Unix command for dumping the text representation of a binary file? | I got some binary files containing integers. Is there some nice Unix command, that will allow me to dump it to a terminal without offset information, etc.?
Something like:
double int[4];
while (fread(tmp, sizeof(int), 4, stdin))
for(int i = 0; i < 4; i++)
printf("%d\t",tmp[i]);
It seems that hexdump and od gives me the information I want, but the output is too verbose. I just want the contents.
| To solve this kind of problem using standard Unix tools, you typically pipe a bunch together:
od -v -t d4 ~/.profile | awk '{$1 = ""; print}' | fmt -1 | sed 's/^ *//'
The od prints every 32-bit word in decimal, with preceding offsets. The awk comment removes the offsets. The fmt command forces one integer per line. The sed command strips leading spaces off the result.
|
2,542,483 | 2,557,466 | can i use multiple PCH files in 1 project? | I want to use the PCH file to speed up the build, so i store the PCH file in a separate folder and reuse it when build the project later.
but I have some #import *.dll in my stdafx.h. so if something changed in the *.dll, the PCH file need be recreated.
my question is whether I can use multiple PCH files in 1 project, so that i can put the import *.dll to another PCH and only recreate this one if something changed in *.dll.
thanks in advance :)
| No, you can only include one pch file per cl.exe invocation.
It's a bummer but that's the way it is.
|
2,542,507 | 2,542,539 | Best way to do powerOf(int x, int n)? | So given x, and power, n, solve for X^n.
There's the easy way that's O(n)...
I can get it down to O(n/2), by doing
numSquares = n/2;
numOnes = n%2;
return (numSquares * x * x + numOnes * x);
Now there's a O(log(n)) solution, does anyone know how to do it? It can be done recursively.
| Well, you know that xa+b = xa xb so...
int pow(int x, unsigned int y)
{
if (y == 0) return 1;
if (y == 1) return x;
int a = y / 2;
int xa = pow(x, a);
if (a + a == y) // y even
return xa * xa;
else
return xa * xa * x;
}
|
2,542,545 | 2,548,024 | Configuring a library to be included with C++ test | I would like to utilize the UnitTest++ library in a testing file. However, I am having some difficulty getting the library to be included at compile time. So here is my current directory structure:
tests/
UnitTests++/
libUnitTest++.a
src/
UnitTests++.h
unit/
test.cpp
I have just used the UnitTest++ getting started guide to just get the library setup. Here is test.cpp:
// test.cpp
#include <UnitTest++.h>
TEST(FailSpectacularly)
{
CHECK(false);
}
int main()
{
return UnitTest::RunAllTests();
}
And I am currently trying to compile with:
gcc -lUnitTest++ -L../UnitTest++/ -I../UnitTest++/src/ test.cpp
I am currently getting a bunch output with ld: symbol(s) not found at the end. So how would I be able to get the UnitTest++ library properly included when this program is compiled? I am on a Mac and I'd also like for there to be an easy way for people on a Linux machine to run these same tests.
Whew, I hope this provides enough information, if not please let me know.
| I was able to build it in the following manner
gcc -L../UnitTest++/ -I../UnitTest++/src/ test.cpp -lUnitTest++ -lstdc++
or
g++ -L../UnitTest++/ -I../UnitTest++/src/ test.cpp -lUnitTest++
that links to libstdc++ automatically.
GCC documentation says:
-llibrary
-l library
Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.)
It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified.
Thus, foo.o -lz bar.o' searches libraryz' after file foo.o but before bar.o. If bar.o refers to functions in `z', those functions may not be loaded.
I guess that's why the library symbols are not found when you first specify -lUnitTest++ and then test.cpp
|
2,542,621 | 2,542,638 | Is there a way to identify version of c/c++ library? | For example, how to get the version of /usr/lib/libz.a? It will be great if other useful information such as compiler/arch etc. can be fetched.
The reason I want to know this is that gcc always say it ignored the libz I offered in command line when I compile my program and linked with specific versioned libz. gcc think the /usr/lib/libz.a is a proper one.
| C libraries do not have on their own a versioning system. At best, there is a symbol in the library that tells it.
|
2,542,890 | 2,542,904 | return char1 + char2? Isn't it possible? | I'm trying to return a string from a function. Which basically adds some chars together and return the string representation.
string toString() {
char c1, c2, c3;
// some code here
return c1 + c2; // Error: invalid conversion from `char' to `const char*'
}
it is possible to return boolean values like return c1 == 'x'. Isn't it possible to return string values? I know that it is possible to it like this:
string result;
result.append(c1, c2);
return result;
I'm new to C++ so I thought that there must be more elegant solution around.
| No, you can't do that because adding two char's together doesn't give you a string. It gives you another char; in this case 'a'+'b' actually gives you '├' (on Windows with the standard CP_ACP code page). Char is an ordinal type, like integers and the compiler only knows how to add them in the most basic of ways. Strings are a completely different beast.
You can do it, but you have to be explicit:
return string(1, c1) + string(1, c2)
This will construct two temporary strings, each initialized to one repetition of the character passed as the second parameter. Since operator+ is defined for strings to be a concatenation function, you can now do what you want.
|
2,543,057 | 2,543,115 | getline() returns empty line in Eclipse but working properly in Dev C++ | Here is my code:
#include <iostream>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main() {
string line;
ifstream inputFile;
inputFile.open("input.txt");
do {
getline(inputFile, line);
cout << line << endl;
} while (line != "0");
return 0;
}
input.txt content:
5 9 2 9 3
8 2 8 2 1
0
In Enclipse, it goes to infinite-loop. I'm using MinGW 5.1.6 + Eclipse CDT.
I tried many things but I couldn't find the problem.
| Since you are on windows try:
} while (line != "0\r");
The last line is stored as "0\r\n". The \n is used as the line delimiter by getline so the actual line read will be "0\r"
or
you can convert the dos format file to UNIX format using command
dos2unix input.txt
Now your original program should work. The command will change the \r\n at the end of the line to \n
Also you should always do error checking after you try to open a file, something like:
inputFile.open("input.txt");
if(! inputFile.is_open()) {
cerr<< "Error opening file";
exit(1);
}
|
2,543,188 | 2,543,455 | Which is the fastest way to scan files in FAT32 disk? | I want to scan FAT32 disk (I just need file path and file name) as soon as possible in C++,
Scan every files on FAT32 disk.
Is there any API to do this?
| Check this thread: How can I quickly enumerate directories on Win32?
It actually describes FindFirstFile/FindNextFile, but if you need it faster you should go Kernel.
The index solution described in the thread will however not work for FAT32 systems - credit MSalters
|
2,543,201 | 2,543,216 | Why does `&*(&*d)` return address of "c" instead of address of "b"? | I made some code, for understanding the concept/basic of pointer:
int a=1;
int *b=&a;
int **c = &b;
int ***d = &c;
cout << &*(&*d) << endl;
Why does &*(&*d) return address of "c" instead of address of "b"?
I've also tried code like &*(&*(&*(&*(&*d)))), but it keep return address of "c"
| Because the &* cancels each other out. * dereference d which gives the value of c. And then & gives the address of c, or the value of d.
|
2,543,331 | 2,543,404 | What does 'const' do in operator() overloading? | I have a code base, in which for Matrix class, these two definitions are there for () operator:
template <class T> T& Matrix<T>::operator() (unsigned row, unsigned col)
{
......
}
template <class T> T Matrix<T>::operator() (unsigned row, unsigned col) const
{
......
}
One thing I understand is that the second one does not return the reference but what does const mean in the second declaration? Also which function is called when I do say mat(i,j)?
| Which function is called depends on whether the instance is const or not. The first version allows you to modify the instance:
Matrix<int> matrix;
matrix(0, 0) = 10;
The const overload allows read-only access if you have a const instance (reference) of Matrix:
void foo(const Matrix<int>& m)
{
int i = m(0, 0);
//...
//m(1, 2) = 4; //won't compile
}
The second one doesn't return a reference since the intention is to disallow modifying the object (you get a copy of the value and therefore can't modify the matrix instance).
Here T is supposed to be a simple numeric type which is cheap(er) to return by value. If T might also be a more complex user-defined type, it would also be common for const overloads to return a const reference:
template <class T>
class MyContainer
{
//..,
T& operator[](size_t);
const T& operator[](size_t) const;
}
|
2,543,394 | 2,543,560 | Determining actual args an Excel UDF was called with | I'm adding a user defined function to Excel with varargs-based signature in C++:
LPXLOPER MyFunction(...);
When Excel calls MyFunction, it passes it 30 arguments regardless of how many the user entered in the sheet. The extraneous ones are blank strings.
MyFunction, however, is designed to accept empty string arguments. As a result, I cannot tell valid empty strings apart from the extraneous ones sent by Excel.
A solution could be to obtain the contents of the actual cell where the user entered the function. However, I can't find a way of doing that from within the implementation of my function.
Could someone please suggest a way out?
| I've found a simple way to get hold of the caller cell.
Use excelApp->get_Caller();
|
2,543,751 | 2,543,847 | Segfault in a matrix code using new | I created a simple class in C++ which has a private dynamic array. In the constructor I initialize the array using new and in the destructor I free it using delete.
When I instantiate the class using Class a = Class(..); it works as expected, however it seems I cannot instantiate it using the new operator (Like Class *a = new Class(..);), I always get a segmentation fault.
What I don't understand is when I should use new to instantiate a class and when just call the constructor or should it be possible to instantiate a class either with new or by just calling the constructor.
float** A = new float*[3];
for (int i=0; i<3; i++) {
A[i] = new float[3];
}
A[0][0] = 3; A[0][1] = 3; A[0][2] = 4;
A[1][0] = 5; A[1][1] = 6; A[1][2] = 7;
A[2][0] = 1; A[2][1] = 2; A[2][2] = 3;
Matrix *M = new Matrix(A, 3, 3);
delete[] A;
delete M;
Below the class definition..
class Matrix
{
private:
int width;
int height;
int stride;
float* elements;
public:
Matrix(float** a, int n, int m);
~Matrix();
};
Matrix::Matrix(float** a, int n, int m)
{
// n: num rows
// m: elem per rows
elements = new float[n*m];
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
elements[i*n + j] = a[n][m];
}
}
}
Matrix::~Matrix()
{
delete[] elements;
}
| Replace i*n + j by i*m + j.
and replace a[n][m] by a[i][j]
|
2,543,813 | 2,543,843 | ld reports missing symbols, but symbols seem to exist | I'm trying to link my mac application to the wonderful libancillary library. However, I have changed the library build script to create a shared library. I can inspect the symbols in this library using nm libancillary.dylib - the result is:
libancillary.dylib(single module):
U ___sF
U __keymgr_get_and_lock_processwide_ptr
U __keymgr_get_and_lock_processwide_ptr_2
U __keymgr_set_and_unlock_processwide_ptr
U _abort
00002cfe T _ancil_recv_fd
00002c87 T _ancil_recv_fds
00002b6a T _ancil_recv_fds_with_buffer
00002e9e T _ancil_send_fd
00002e27 T _ancil_send_fds
00002d3f T _ancil_send_fds_with_buffer
U _calloc
U _dlopen
U _dlsym
U _fflush
U _fprintf
U _free
U _malloc
U _recvmsg
U _sendmsg
However, when I try and link my application, the output I get is:
g++ -headerpad_max_install_names -framework AppKit -framework Cocoa -framework IOKit -framework CoreFoundation -framework Carbon -framework OpenGL -framework SystemConfiguration -framework Security -Wl,-bind_at_load -arch i386 -o MyApp build/app.o build/client.o build/util.o -F/Library/Frameworks -L/Library/Frameworks -L../ancillary -lancillary
Undefined symbols:
"ancil_recv_fd(int, int*)", referenced from:
CIPCUnixUtils::readFD(int, int&) constin utils.o
"ancil_send_fd(int, int)", referenced from:
CIPCUnixUtils::writeFD(int, int) constin utils.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [ABClient] Error 1
(I have edited this slightly to remove the very long list of object files).
What could cause this linkage to fail? The symbol exists, and is public, and there's no error about not being able to find the library, or any other error messages.
| Those symbols are unmangled C symbols. As you have tagged this as C++, I assume you are compiling with C++. If you do that you may need to wrap your libraries header files in an extern block in your code:
extern "C" {
#include "library.h"
}
where library.h is the name of the library's header file(s), to prevent them being mangled in the calling code.
|
2,543,996 | 2,544,182 | C++ wrapper for posix and linux specific functions | Do you know about any good library wrapping posix and linux functions and structures ( eg. sockets or file descriptors ) into C++ classes? For example I'm thinking about a base FileDescriptor class and some inheriting classes ( unix sockets etc ) with methods like write, read or even some syscalls ( sendfile, splice ) - all throwing exceptions instead of setting errno. Or some shared memory class etc.
I can't seem to find anything like that and by now I consider writing it myself, as I often have to write a C++ app for linux and either use C functions ( painful error checking ), or wrap them myself every time.
---EDIT---
Well neither QT nor Boost will compile on the system, we're using - it's a small linux kernel based on 2.4.29 installed on embedded computers.
| Try Common C++. I haven't used it myself, but it supports the things you've mentioned.
|
2,544,398 | 2,551,738 | CHtmlView class and focus | I have an SDI application written in MFC. The frame is divided into 1 row and 2 columns using a splitter window. Below are details of Row and Column (R0C0 means Row#0 and Col#0)
R0C0 view is a CFormView with multiple input controls like text box, combo box etc.
R0C1 view is a CHtmlView that contains HTML content relavant to the control that has input focus in the R0C0
I am able to update the HTML content and also invoke Javascript functions through my MFC code.
Problem:
When user clicks on the R0C1, continaing CHtmlView, the focus is now on the html page. I wish to allow the user to tab out of R0C1 using the key board and return back to R0C0. Can you help with this please? The user can obviously click on the R0C0 view using mouse but we have a user who needs to use Keyboard for using this functionality.
Let me know if the question is not descriptive enough and I'll simplify it further.
Appreciate your time.
Thanks,
Byte
| Try to overload CHtmlView::OnTranslateAccelerator. I have successfully used this trick to disable refresh with F5 key. Derive your own class from CHtmlView and overload
virtual HRESULT OnTranslateAccelerator(LPMSG lpMsg, const GUID* pguidCmdGroup, DWORD nCmdID);
like this:
HRESULT CMyHtmlView::OnTranslateAccelerator(LPMSG lpMsg, const GUID* pguidCmdGroup, DWORD nCmdID)
{
if(lpMsg->message == WM_KEYDOWN && GetAsyncKeyState(VK_TAB) != 0 )
{
// change focus
return S_OK;
}
return CHtmlView::OnTranslateAccelerator( lpMsg, pguidCmdGroup, nCmdID);
}
|
2,544,782 | 3,407,557 | Doxygen groups and modules index | I am creating a Doxygen document for my project. Recently, I have grouped related classes using \addtogroup tag. After this, I have got a module tab in my documentation. It shows all modules. I want to add some description right below module name below the module name on the same page. How can I do it using Doxygen ?
Here's my tag
/*! \addtogroup test test
* Test Testing a group in doxygen
* @{
*/
| You have to write a dedicated .h file which contains only comments.
For each group you define a comment like this:
/** @defgroup FooGroup
*
* This module does yada yada yada
*
*/
Then you assign definition to the group (even on different files) like this:
/** @addtogroup FooGroup */
/*@{*/
/** Summon a goat
*
* @param name The name of the goat;
* @return The summoned goat;
*/
Goat summon_goat (const char *name);
...
...
/*@}*/
EDIT:
Also this is how it becomes.
See the "Detailed Description"? You can also add code snippet and examples within the @verbatim and @endverbatim commands.
|
2,544,805 | 2,544,848 | VS 2008 Compiler option for flagging uninitialized variables | Is there a compiler option in VS 2008 (C++) to expose uninitialized variables? I'm trying to debug a problem where the "release" build of a DLL does not work but the "debug" build of the DLL does work.
| iirc, setting warning level to 4 will help with this
|
2,544,809 | 2,544,847 | bitwise OR on strings | How can i do a Bitwise OR on strings?
A:
10001
01010
------
11011
Why on strings?
The Bits can have length of 40-50.Maybe this could be problematic on int ?
Any Ideas ?
| I would say std::bitset is more than enough for your situation, but for more flexibility you can use boost::dynamic_bitset. Here is an example on std::bitset:
const size_t N = 64;
string a_str = "10001", b_str = "01010";
bitset<N> a(a_str), b(b_str);
bitset<N> c = a | b;
cout << c;
|
2,544,852 | 2,544,872 | Using the same variable across multiple files in C++ | In the process of changing some code, I have spilt some functions into multiple files. I have the files controls.cpp and display.cpp and I would like to be able to have access to the same set of variables in both files. I don't mind where they are initialized or declared, as long as the functions in both files can use them.
This was not an issue when the functions were in the same file, but now it seems almost impossible after an hour of googling and trying various things.
| Define the variable in one file like:
type var_name;
And declare it global in the other file like:
extern type var_name;
|
2,544,868 | 2,550,359 | What happens to an ActiveX control (COleControl) after the call to OnDestroy()? | I have an ActiveX control written in C++ that runs in Internet Explorer 8. Most of the time (approx 90%) when the tab or browser containing the control is closed, there is an access violation like this:
The thread 'Win32 Thread' (0x1bf0) has exited with code 0 (0x0).
Unhandled exception at 0x77b3b9fd in iexplore.exe: 0xC0000005: Access violation reading location 0x65007408.
The access violation occurs after the call to OnDestroy() but before the call to the control's destructor.
The debug output says:
No symbols are loaded for any call stack frame. The source code cannot be displayed.
None of my code is present in the stacktrace, although perhaps the heap was corrupted at some earlier point during execution.
What lifecycle events does an ActiveX control receive between the call to OnDestroy() and the control's destructor?
| As I understand, there is no strictly event lifecycle for an ActiveX, it depends on host side. If your control is used with some AJAX framework, for example, after OnDestroy() can be called OnCreate() without calling destructor. So, make sure you don’t have uninitialize actions inside OnDestroy() handler.
You can load control in ActiveX Control Test Container and play with Activate/Deactivate, maybe it will be helpful.
Enable Application Verifier from debugging tools for windows and make sure your debugger downloads OS debug symbols. In this case stack trace will be more informative.
|
2,544,896 | 2,544,910 | Confused about type conversion in C++ | In C++, the following lines have me confused:
int temp = (int)(0×00);
int temp = (0×00int);
What is the difference between those 2 lines?
| Both are invalid because you are using × instead of x:
test.cpp:6: error: stray '\215' in program
test.cpp:6: error: expected primary-expression before "int"
test.cpp:6: error: expected `)' before "int"
But even fixing that, the second still isn't valid C++ because you can't write 0x00int:
test.cpp:6:13: invalid suffix "int" on integer constant
The first is valid (after changing × to x) and assigns the value 0 to temp. The cast is unnecessary here though - you don't need a cast just because the constant is written in hexadecimal. You can just write:
int temp = 0x00;
|
2,544,928 | 2,545,261 | How to extract channel POD-type from a boost::gil homogeneous pixel type? | I have a class templated on <PIXEL>, assumed to be one of boost::gil's pixel types (for now, only either gray8_pixel_t or gray16_pixel_t, and I only expect to support homogeneous pixel types e.g rgb8_pixel_t in future).
The class needs to get hold of unsigned char or unsigned short as appropriate to the pixel type; I assume this is buried somehwere in the pixel class, but none of PIXEL::value_type, PIXEL::channel_type or PIXEL::channel_type::value type seems to be what I want.
What's the trick ?
(I could of course use type-indirection via some template-specialized helper structs to get this info:
template <typename PIXEL> struct types_for
{};
template <> struct types_for<boost::gil::gray8_pixel_t>
{typedef unsigned char channel_type;};
template <> struct types_for<boost::gil::gray16_pixel_t>
{typedef unsigned short channel_type;};
but surely GIL must provide something equivalent already, if I could just find it...)
| Aha.. this seems to do the trick:
typename boost::gil::channel_type<PIXEL>::type
|
2,544,977 | 2,545,193 | Resize QTextEdit in a QWidget while it is being resized the QWidget | How to make QTextEdit to be resized in a QWidget while the QWidget is being resized?
Should I overload resizeEvent function for the QWidget?
| No, you should set the sizePolicy property for your QTextEdit object.
|
2,545,101 | 2,545,165 | convert bitset to string? | What is wrong with this code ?
set<string> nk ;
bitset<3> bs1(string("100"));
nk.insert(bs1.to_string());
error: no matching function for call to `std::bitset<3u>::to_string()'
why?!
UPDATE :
Thansk , this works . But why does it work ? :D
| While checking Space_COwbOy's answer, I found another page that shows that to_string is a template function (with parameters similar to std::basic_string). I haven't tried this, so just check it out.
|
2,545,343 | 2,545,388 | Setting pointers to structs | I have the following struct:
struct Datastore_T
{
Partition_Datastores_T cmtDatastores; // bytes 0 to 499
Partition_Datastores_T cdhDatastores; // bytes 500 to 999
Partition_Datastores_T gncDatastores; // bytes 1000 to 1499
Partition_Datastores_T inpDatastores; // bytes 1500 1999
Partition_Datastores_T outDatastores; // bytes 2000 to 2499
Partition_Datastores_T tmlDatastores; // bytes 2500 to 2999
Partition_Datastores_T sm_Datastores; // bytes 3000 to 3499
};
I want to set a char* to point to a struct of this type like so:
struct Datastore_T datastores;
// Elided: datastores is initialized with data here
char* DatastoreStartAddr = (char*)&datastores;
memset(DatastoreStartAddr, 0, 3500);
The problem I have is that DatastoreStartAddr always has a value of zero when it should point to the struct that has been initialized with data.
What am I doing wrong?
Edit: What I mean by zero is that the "values" in the structure are all zeros even after I initialize the structure. The address is not zero, it is the values in the struct that are zero.
Edit: I think I am asking the question wrong. Let's start over. If I have a struct that is initialized with data, and another object maintains a field member that is a pointer to that struct, if the struct is changed directly:
struct Datastore_T datastores;
char* DatastoreStartAddr = (char*)&datastores;
datastores.cmtDatastores.u16Region[0] = Scheduler.GetMinorFrameCount(); // byte 40,41
datastores.cmtDatastores.u16Region[1] = Scheduler.GetMajorFrameCount(); // byte 42,43
Shouldn't I be able to access these changes using the DatastoreStartAddr pointer?
EDIT: The following code tries to read the data set in datastores, but using the pointer to the struct:
CMT_UINT8_Tdef PayLoadBuffer[1500]= {NULL};
int TDIS = 0;
int DIS = 0;
int DSA = 0;
//copy DataStore info using address and size offsets
if ((PayLoadBuffer + TDIS + DIS) < IndvDEMMax)
{
memcpy((PayLoadBuffer + TDIS), Datastores+DSA, DIS);
TDIS += DIS;
}
In the memcpy((PayLoadBuffer + TDIS), Datastores+DSA, DIS) line, Datastores should point to structure and attempts to access an offset in that structure. But since the value is always zero, it copies zero in the PayLoadBuffer.
| I don't know why you are getting an address of zero, but I would guess the code you don't show has something to do with it. Some other points:
Consider using an array of Partition_Datastores_T inside your struct
Do not use magic numbers for struct sizes, you want sizeof(Datastore_T )
There is no need for the intermediate char*
Edit: Bobby, to answer your supplementary question - yes you should be able to access it through a pointer, but not through a char * (without jumping through some hoops). You want:
struct Datastore_T datastores;
struct Datastore_T * DatastoreStartAddr = &datastores;
and when you use that pointer:
DatastoreStartAddr->cmtDatastores.u16Region[0] = Scheduler.GetMinorFrameCount();
Please note the use of the -> operator.
|
2,545,352 | 2,545,408 | Hide console window in Windows Forms application | I took over a Visual C++ project in Visual Studio 2005 from a colleague. It is a Windows Forms project (I assume). But when I start it, besides the Windows Form it also shows a console window. How do I get rid of this console window? I think it must be a project setting but I don't find it.
Any help is appreciated ...
| In the project properties for all configurations (Project | Properties, choose Configuration 'All Configurations', locate Config Properties -> Linker -> System), change the SubSystem from Console to Windows.
|
2,545,577 | 2,563,949 | QSplitter becoming undistinguishable between QWidget and QTabWidget | I am puting a QWidget and a QTabWidget next to each other in one horisontal splitter. And the splitter loses it's shape, you can know that there is a splitter only by hovering mouse on it. How to make it visible?
Thanks.
| Since the QSplitterHandle (which is what most people think of as the 'splitter') is derived from QWidget, you can add other widgets to it. Here is what I have done to solve this exact problem in the past:
// Now add the line to the splitter handle
// Note: index 0 handle is always hidden, index 1 is between the two widgets
QSplitterHandle *handle = pSplitter->handle(1);
QVBoxLayout *layout = new QVBoxLayout(handle);
layout->setSpacing(0);
layout->setMargin(0);
QFrame *line = new QFrame(handle);
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
layout->addWidget(line);
This adds a sunken line to the splitter handle. You can, of course, choose another style for the frame line or use something entirely different as the widget you add to the splitter handle.
|
2,545,635 | 2,545,657 | Basic Boost Regex question | I'm trying to write some c++ code that tests if a string is in a particular format. In this program there is a height followed by some decimal numbers:
for example
"height 123.45" or "height 12" would return true but
"SomeOtherString 123.45" would return false.
My first attempt at this was to write the following:
string action;
cin >> action;
boost::regex EXPR( "^height \\d*(\\.\\d{1,2})?$/" ) ;//height format regex
bool height_format_matches = boost::regex_match( action, EXPR ) ;
if(height_format_matches==true){
\\do some stuff
}
However height_format_matches never seemed to be true. Any help is greatly appreciated!
| Drop the trailing slash and it should work. Probably left over from a JavaScript regex? In JavaScript, regexes are often delimited by slashes; in C++, they are simply strings. If you keep the slash where it is, the regex engine is instructed to match a slash after the end of the string ($), which always fails, of course.
|
2,545,681 | 2,546,690 | Way to exclude a char from a word selection | I'm extending a QPlainTextEdit.
When I double click on a word containing a pipe char ex : {"foo"|upper|reverse}
the whole text is surrounded.
I'd like to exclude the pipe char "|" from the selection and don't know what to do
Is there a way to change the behavior of QTextCursor::WordUnderCursor?
I'd like that char to act the same as a space or more generally as an unselectable char.
As stated in QT docs:
Selects the word under the cursor. If
the cursor is not positioned within a
string of selectable characters, no
text is selected.
| Currently there is no official way to change the way a text edit finds the word boundaries. See http://bugreports.qt-project.org/browse/QTBUG-150.
You may use their private API to change the behaviour of QTextEngine::atWordSeparator. This way is not recommanded by Qt. The pipe is recognized as word separator in 4.6 but not in 4.5.1 or earlier. I would suggest to update your Qt version, if that is an option. Otherwise you may give your QTextEdit a new QTextLayout with a modified QTextEngine.
|
2,545,720 | 2,545,733 | error: default argument given for parameter 1 | I'm getting this error message with the code below:
class Money {
public:
Money(float amount, int moneyType);
string asString(bool shortVersion=true);
private:
float amount;
int moneyType;
};
First I thought that default parameters are not allowed as a first parameter in C++ but it is allowed.
| You are probably redefining the default parameter in the implementation of the function. It should only be defined in the function declaration.
//bad (this won't compile)
string Money::asString(bool shortVersion=true){
}
//good (The default parameter is commented out, but you can remove it totally)
string Money::asString(bool shortVersion /*=true*/){
}
//also fine, but maybe less clear as the commented out default parameter is removed
string Money::asString(bool shortVersion){
}
|
2,545,731 | 2,545,757 | problem understanding templates in c++ | Template code is not compiled until the template function is used. But where does it save the compiled code, is it saved in the object file from which used the template function in the first place?
For example,
main.cpp is calling a template function from the file test.h, the compiler generates an object file main.o,
Is the template function inside the main.o file? because template code is not inlined, is it?
| It's totally compiler implementation dependant. Most compilers will generate code around, inline or in cpp-like files and then compile with that. Sometimes, with optimization setup, some compilers will even reuse the same code instead of recreate it for each cpp.
So you have to see your compiler's doc for more details.
|
2,545,858 | 2,545,920 | C++ Access to SQL Server from Linux | I need to write some data to SQL Server database from Linux in C++.
I found this sqlapi.com
But I think, at first ODBC driver has to be installed and has to work.
I folowed this
adminlife.net/allgemein/mssql-zugriff-unter-debian-etch-mit-unixodbc-und-freetds/
or this
http://b.gil.megiteam.pl/2009/11/linux-odbc-to-mssql/
But it didn't work. The port 1433 seems to be closed
($ sudo nmap -PN -sU -p 1433 192.168.56.101 -> port "filtered")
isql -v sqlexpress sa
-> wait with no response or get "couldn't connect to sql"
From other PC with Windows I have no problem to write data in SQL Server,
so server should be right configured to remote access.
Any ideas?
| Here are the links I bookmarked concerning that topic, hope it can help you:
ODBC Tutorial
FreeTDS
Connection strings
How to configure ODBC - This one was really useful.
It was some time ago, but basically what I remember is:
You have to create an entry for the particular MSSQL driver you have in a file named /etc/odbcinst.ini. Then, for each MSSQL server, you have to create an entry (or DSN), either globaly in /etc/odbc.ini, or user-local, in $HOME/.odbc.ini.
Some names I used might differ (and I don't have acces to my Linux box right now to check) but you got the general idea.
Once you did that, isql -d should connect succesfully to the database. If so, then using the C/Linux API for ODBC should be a piece of cake. Tutorials provided in the given links.
|
2,546,212 | 2,546,354 | ATLComTime.h is part of what redistributable? | I added functionality to a code base someone else wrote and while the "Not using ATL" flag was set in VS2005 I see that there is #include <ATLComTime.h> in one of the files. I have only sent the C-Runtime library (see here) redistributable. The client can not get the code to worktheir machines. They receive a "DLL entry point not found" error. I feel that it's some sort of missing DLL or library on the target machine since we've been able to install it in all of our test machines.
They want me to make sure that I don't send a "bogus" redistributable to a client. Since I can't seem to find ultimately which redistributable this header pertains I'm asking here. I'm at a loss. Can help?
| Configure the project to link statically with ATL (Project | Properties -> Config Properties -> General -> Use of ATL) executable, or distribute atl.dll with your application.
|
2,546,328 | 2,546,612 | How to call an programmatically generated event for wxRadioButton in wxWidgets? | I am trying to programmatically change a value of a wxRadioButton in a way the user would do it. A value change doesn't call the event corresponded to the button, and it make sense since the documentation says it clearly:
wxRadioButton::SetValue
void SetValue(const bool value)
Sets the radio button to selected or deselected status.
This does not cause a wxEVT_COMMAND_RADIOBUTTON_SELECTED event to get emitted.
So the question is how can I call an programmatically generated event for a wxRadioButton ?
I guess that it's something to do with:
wxWindow window->AddPendingEvent(wxEvent *event )
A simple example would be greatly appreciated.
| You can use AddPendingEvent or ProcessEvent (handle immediately).
bttn->SetValue(true);
wxCommandEvent ev(wxEVT_COMMAND_RADIOBUTTON_SELECTED, id_button);
bttn->GetEventHandler()->ProcessEvent(ev);
It should also be possible to use wxControl::Command, but it seems to me that SetValue should be called after that(?).
|
2,546,331 | 2,546,398 | Difference between debug and release when viewed in debugger | I'm viewing variables using the debugger. In debug builds everything in the code below appears as I expect it to, but when I switch to release builds I'm getting strange results. Why?
#include <iostream>
void say_hello(int argc, char* argv[])//In release mode argc has different values from 124353625 to 36369852 when viewed in the debugger
{
std::cout << "In say_hello()\n";
}
int main(int argc, char* argv[])
{
say_hello(3,argv);//when instead of literal I enter "argc" everything is ok.
return 0;
}
Thanks for help.
| Since you're not using those parameters in your program, you must be trying to observe their values in the debugger. But, again since you're not using them in your program, the compiler is free to do whatever it wants with their values. It may remove them entirely, leaving the debugger with nothing but gibberish to display when you ask for each parameter's value. If you change your optimization and debug-information settings, you may see different results.
|
2,546,706 | 2,546,716 | Pointers in C# to make int array? | The following C++ program compiles and runs as expected:
#include <stdio.h>
int main(int argc, char* argv[])
{
int* test = new int[10];
for (int i = 0; i < 10; i++)
test[i] = i * 10;
printf("%d \n", test[5]); // 50
printf("%d \n", 5[test]); // 50
return getchar();
}
The closest C# simple example I could make for this question is:
using System;
class Program
{
unsafe static int Main(string[] args)
{
// error CS0029: Cannot implicitly convert type 'int[]' to 'int*'
int* test = new int[10];
for (int i = 0; i < 10; i++)
test[i] = i * 10;
Console.WriteLine(test[5]); // 50
Console.WriteLine(5[test]); // Error
return (int)Console.ReadKey().Key;
}
}
So how do I make the pointer?
| C# is not C++ - don't expect the same things to work in C# that worked in C++. It's a different language, with some inspiration in the syntax.
In C++, array access is a short hand for pointer manipulation. That's why the following are the same:
test[5]
*(test+5)
*(5+test)
5[test]
However, this is not true in C#. 5[test] is not valid C#, since there is no indexer property on System.Int32.
In C#, you very rarely want to deal with pointers. You're better off just treating it as an int array directly:
int[] test = new int[10];
If you really do want to deal with pointer math for some reason, you need to flag your method unsafe, and put it into an fixed context. This would not be typical in C#, and is really probably something completely unnecessary.
If you really want to make this work, the closest you can do in C# would be:
using System;
class Program
{
unsafe static int Main(string[] args)
{
fixed (int* test = new int[10])
{
for (int i = 0; i < 10; i++)
test[i] = i * 10;
Console.WriteLine(test[5]); // 50
Console.WriteLine(*(5+test)); // Works with this syntax
}
return (int)Console.ReadKey().Key;
}
}
(Again, this is really weird C# - not something I'd recommend...)
|
2,546,757 | 2,546,842 | Executing MSYS from cmd.exe with arguments | I am trying to learn the wxWidgets library, using MinGW and msys to compile the code. So far so good, but I can not find a way to send a command to MSYS through CMD.exe.
I use Sublime Text to edit files, and it has an option to run makefiles. I want my makefiles to be able to open an instance of MSYS and send the g++ command and arguments to it.
Example:
Right now my makefile is:
test.exe : main.cpp
g++ -s main.cpp -o test.exe `wx-config --cxxflags` `wx-config --libs`
When mingw32-make goes to run the g++ command, it sends it to cmd.exe, which doesn't handle the back-ticks and wx-config jazz. (But the command does work when run from inside MSYS and the directory holding main.cpp)
I want to be able to use something like...
msys --command g++ -s main.cpp*...etc..*
So it will load the MSYS enviroment and run the command. Is this possible?
I am a huge makefile newbie, so if there is an easier way, please show me!
| You probably want to set the shell that gmake uses to execute the commands that make up the makefile. I assume that MSYS comes with bash or even plain sh, which should do the job.
|
2,547,043 | 2,547,088 | Passing multiple vectors to function by reference (using structure) | Can someone tell me the correct way of passing multiple vectors to a function that can take only a single argument? (specifically for pthread_create (..) function)
I tried the following but it does not seem to work :-(
First, I created the following structure
struct ip2
{
void* obj;
int dim;
int n_s;
vector<vector<vector<double> > > *wlist;
vector<int> *nrsv;
struct model *pModel;
};
The threads that I have created actually needs all these parameters. Since im using pthreads_create I put all this in a structure and then passed the pointer to the structure as an argument to pthread_create (as shown).
some_fxn()
{
//some code
struct ip2 ip;
ip.obj=(void*) this;
ip.n_s=n_s;
ip.wlist=&wlist;
ip.nrsv=&nrsv;
ip.pModel=pModel;
ip.dim=dim;
pthread_create(&callThd1[lcntr], &attr1, &Cls::Entry, (void*) &ip);
}
The Entry method looks something like this.
void* Cls::Entry(void *ip)
{
struct ip2 *x;
x = (struct ip2 *)ip;
(reinterpret_cast<Cls1 *>(x->obj))->Run(x->dim,x->n_s, x->wlist, x->nrsv, x->pModel);
}
The Run method looks something like this.
void Run(int dim, int n_c, vector<vector<vector<double> > > *wlist, vector<int> *nrsv, struct model* pModel )
{
//some code
for(int k = 0; k < n_c; ++k)
{
//some code
end = index + nrsv[k];
//some code
}
I get the following error when I try to compile the program.
error: no match for ‘operator+’ in ‘index + *(((std::vector<int, std::allocator<int> >*)(((unsigned int)k) * 12u)) + nrsv)’
Can someone tell me how to do it the right way.
Madhavan
| nrsv is a vector<int>*, right? So you need to do end = index + (*nrsv)[k]; (dereference it).
|
2,547,531 | 2,547,725 | STL algorithms and concurrent programming | Can any of STL algorithms/container operations like std::fill, std::transform be executed in parallel if I enable OpenMP for my compiler? I am working with MSVC 2008 at the moment.
Or maybe there are other ways to make it concurrent?
Thanks.
| There are a number of projects that aim at having parallel STL type libraries:
OpenMP Multi-Threaded Template Library
libstdc++ parallel
HPC++ Parallel Standard Template Library
Parallel Patterns Library (shamelessly borrowed from AshleysBrain's answer)
|
2,547,630 | 2,547,667 | hiding exectables using ADS (Alternate data streams) | i hear that NTFS alternate data streams can be used to hide running executabes.
eg
supporse i have an exe called hiddenProgram.exe on windows xp,using cmd.exe or system(char*) calls in c,
type hiddenProgram.exe > c:\windows\system32\svchost.exe:hiddenProgram.exe
start c:\windows\system32\svchost.exe:hiddenProgram.exe
starts svchost and at the same time hiddenProgram.exe
but hiddenProgam.exe is not displayed in windows task manager!!
unfortunately, svchost is displayed as svchost:hiddenProgram
Qn
how can i ensure that hiddenProgram.exe is hidden totally in task manager.
| In NTFS you can have one or more streams associated with a file. There is always an unamed stream that everyone knows about, but you can also have named streams which are refered to as Alternate Data Streams (ADS).
starts svchost and at the same time
hiddenProgram.exe
No it only starts just the program contained in the stream: svchost:hiddenProgram
How can i ensure that hiddenProgram.exe is hidden totally in task manager
You can't easily. All running processes are shown in the task manager. See @joveha's comment below though.
|
2,547,635 | 2,547,699 | Is size_t only in C++ standard or C standard as well? | Is size_t only in C++ standard or C standard as well?
I cannot find a C header in the "/usr/include" tree that defines size_t.
If it is not in the C std, is GCC just doing some magic to make things work?
Thanks,
Chenz
| From C99 draft:
7.17 Common definitions <stddef.h>
The following types and macros are defined in the standard header <stddef.h>. Some
are also defined in other headers, as noted in their respective subclauses.
The types are [-snip-]
size_t
which is the unsigned integer type of the result of the sizeof operator; [-snip-]
|
2,547,686 | 2,547,746 | Decimal type in Qt (C++) | What is the correct type to use in Qt development (or C++ in general) for decimal arithmetic, i.e. the equivalent of System.Decimal struct in .Net?
Does Qt provide a built-in struct? (I can't find it in the docs, but maybe don't know where to look.)
Is there a "standard" C++ library to use?
|
What is the correct type to use in Qt
development (or C++ in general) for
decimal arithmetic, i.e. the
equivalent of System.Decimal struct in
.Net?
Neither C++ standard library nor Qt has any data type equivalent to System.Decimal in .NET.
Does Qt provide a built-in struct? (I
can't find it in the docs, but maybe
don't know where to look.)
No.
Is there a "standard" C++ library to
use?
No.
But you might want to have a look at the GNU Multiple Precision Arithmetic Library.
[EDIT:] A better choice than the above library might be qdecimal. It wraps an IEEE-compliant decimal float, which is very similar (but not exactly the same as) the .NET decimal, as well utilizing Qt idioms and practices.
|
2,547,789 | 2,547,878 | Shift Operators in C++ |
If the value after the shift operator
is greater than the number of bits in
the left-hand operand, the result is
undefined. If the left-hand operand is
unsigned, the right shift is a logical
shift so the upper bits will be filled
with zeros. If the left-hand operand
is signed, the right shift may or may
not be a logical shift (that is, the
behavior is undefined).
Can somebody explain me what the above lines mean??
| I'm assuming you know what it means by shifting. Lets say you're dealing with a 8-bit chars
unsigned char c;
c >> 9;
c >> 4;
signed char c;
c >> 4;
The first shift, the compiler is free to do whatever it wants, because 9 > 8 [the number of bits in a char]. Undefined behavior means all bets are off, there is no way of knowing what will happen. The second shift is well defined. You get 0s on the left: 11111111 becomes 00001111. The third shift is, like the first, undefined.
Note that, in this third case, it doesn't matter what the value of c is. When it refers to signed, it means the type of the variable, not whether or not the actual value is greater than zero. signed char c = 5 and signed char c = -5 are both signed, and shifting to the right is undefined behavior.
|
2,547,792 | 2,547,914 | How do interpreters written in C and C++ bind identifiers to C(++) functions | I'm talking about C and/or C++ here as this are the only languages I know used for interpreters where the following could be a problem:
If we have an interpreted language X how can a library written for it add functions to the language which can then be called from within programs written in the language?
PHP example:
substr( $str, 5, 10 );
How is the function substr added to the "function pool" of PHP so it can be called from within scripts?
It is easy for PHP storing all registered function names in an array and searching through it as a function is called in a script. However, as there obviously is no eval in C(++), how can the function then be called? I assume PHP doesn't have 100MB of code like:
if( identifier == "substr" )
{
return PHP_SUBSTR(...);
} else if( ... ) {
...
}
Ha ha, that would be pretty funny. I hope you have understood my question so far.
How do interpreters written in C/C++ solve this problem?
How can I solve this for my own experimental toy interpreter written in C++?
| Actually scripting languages do something like what you mentioned.
They wrap functions and they register that functions to the interpreter engine.
Lua sample:
static int io_read (lua_State *L) {
return g_read(L, getiofile(L, IO_INPUT), 1);
}
static int f_read (lua_State *L) {
return g_read(L, tofile(L), 2);
}
...
static const luaL_Reg flib[] = {
{"close", io_close},
{"flush", f_flush},
{"lines", f_lines},
{"read", f_read},
{"seek", f_seek},
{"setvbuf", f_setvbuf},
{"write", f_write},
{"__gc", io_gc},
{"__tostring", io_tostring},
{NULL, NULL}
};
...
luaL_register(L, NULL, flib); /* file methods */
|
2,547,988 | 2,581,199 | Boost Unit testing memory reuse causing tests that should fail to pass | We have started using the boost unit testing library for a large existing code base, and I have run into some trouble with unit tests incorrectly passing, seemingly due to the reuse of memory on the stack.
Here is my situation:
BOOST_AUTO_TEST_CASE(test_select_base_instantiation_default)
{
SelectBase selectBase();
BOOST_CHECK_EQUAL( selectBase.getSelectType(), false);
BOOST_CHECK_EQUAL( selectBase.getTypeName(_T(""));
BOOST_CHECK_EQUAL( selectBase.getEntityType(), -1);
BOOST_CHECK_EQUAL( selectBase.getDataPos(), -1);
}
BOOST_AUTO_TEST_CASE(test_select_base_instantiation_parameterized)
{
SelectBase selectBase(true, _T("abc"));
BOOST_CHECK_EQUAL( selectBase.getSelectType(), false);
BOOST_CHECK_EQUAL( selectBase.getTypeName(_T("abc"));
BOOST_CHECK_EQUAL( selectBase.getEntityType(), -1);
BOOST_CHECK_EQUAL( selectBase.getDataPos(), -1);
}
The first test passed correctly, initializing all the variables.
The constructor in the second unit test did not correctly set EntityType or DataPosition, but the unit test passed. I was able to get it to fail by placing some variables on the stack in the second test, like so:
BOOST_AUTO_TEST_CASE(test_select_base_instantiation_parameterized)
{
int a, b;
SelectBase selectBase(true, _T("abc"));
BOOST_CHECK_EQUAL( selectBase.getSelectType(), false);
BOOST_CHECK_EQUAL( selectBase.getTypeName(_T("abc"));
BOOST_CHECK_EQUAL( selectBase.getEntityType(), -1);
BOOST_CHECK_EQUAL( selectBase.getDataPos(), -1);
}
If there is only one int, only the EntityType CHECK_EQUAL fails, but if there are two, both EntityType and DataPos fail, so it seems pretty clear that this is an issue with the variables being created on the same stack memory or some such.
Is there a good way to clear the memory between each unit test, or am I potentially using the library incorrectly or writing bad tests? Any help would be appreciated.
Update:
Select base is a simple class, with only bool, int, and CString member variables. It is a base class to handle state for more complex implementations, so it doesn't access any global variables or global state.
What I need is a way to set the memory between calls to something like 0xdeadf00d, so that if a member variable is left uninitialized the unit test can catch it. Otherwise only the first unit test does any good.
I updated to the boost 1.41, but the issue wasn't resolved. It did affect the issue somewhat in some of the test cases, but not to the point that all the test would fail properly.
| I ended up writing a function to set the object to an invalid state after each test case:
void unsetSelectBase(SelectBase selectBase)
{
selectBase.setSelectType(true);
selectBase.getTypeName(_T("InvalidName"));
selectBase.getEntityType(42);
selectBase.getDataPos(2718);
}
BOOST_AUTO_TEST_CASE(test_select_base_instantiation_default)
{
SelectBase selectBase();
BOOST_CHECK_EQUAL( selectBase.getSelectType(), false);
BOOST_CHECK_EQUAL( selectBase.getTypeName(_T(""));
BOOST_CHECK_EQUAL( selectBase.getEntityType(), -1);
BOOST_CHECK_EQUAL( selectBase.getDataPos(), -1);
unsetSelectBase(selectBase);
}
BOOST_AUTO_TEST_CASE(test_select_base_instantiation_parameterized)
{
SelectBase selectBase(true, _T("abc"));
BOOST_CHECK_EQUAL( selectBase.getSelectType(), false);
BOOST_CHECK_EQUAL( selectBase.getTypeName(_T("abc"));
BOOST_CHECK_EQUAL( selectBase.getEntityType(), -1);
BOOST_CHECK_EQUAL( selectBase.getDataPos(), -1);
unsetSelectBase(selectBase);
}
This causes all the test cases to fail appropriately when any member variables are not initialized. I guess this is just another manual setup/tear down type task that is necessary, since the framework doesn't clear the memory.
|
2,548,075 | 2,548,602 | C++ string template library | I want simple C++ string based template library to replace strings at runtime.
For example, I will use
string template = "My name is {{name}}";
At runtime, I want the name to be changed based on actual one.
I found one example, www.stringtemplate.org but I little scared when its talks about antlr etc.
| Update: The project has moved to Github and renamed into CTemplate: https://github.com/OlafvdSpek/ctemplate
From the new project page:
was originally called Google Templates, due to its origin as the template system used for Google search result pages. Now it has a more general name matching its community-owned nature.
Have you tried Google's CTemplate library ? It seems to be exactly what you are looking for: http://code.google.com/p/google-ctemplate/
Your example would be implemented like this:
In example.tpl:
My name is {{name}}
In example.cc:
#include <stdlib.h>
#include <string>
#include <iostream>
#include <google/template.h>
int main(int argc, char** argv)
{
google::TemplateDictionary dict("example");
dict.SetValue("name", "John Smith");
google::Template* tpl = google::Template::GetTemplate("example.tpl",
google::DO_NOT_STRIP);
std::string output;
tpl->Expand(&output, &dict);
std::cout << output;
return 0;
}
Then:
$ gcc example.cc -lctemplate -pthread
$ ./a.out
My name is John Smith
Note that there is also a way to write templates as const strings if you don't want to bother writting your templates in separate files.
|
2,548,130 | 2,549,263 | How to store wxImage into database, using C++? | I have some wxImages and I would like to store them into a BLOB (Binary Large OBject) field in a MySQL database.
There are no methods in wxImage nor wxBitmap for obtaining the binary data as an array of unsigned char so I can load into the database.
My current workaround is to write the image to a temporary file, then load the BLOB field directly from the file.
Is there a more efficient method to load and store a wxImage object into a MySQL BLOB field?
I am using MySql C++ connector 1.05, MS Visual Studio 2008, wxWidgets and C++.
| wxWidgets doesn't provide any API to the data from wxBitmap (because it's platform-dependent) but wxImage uses a well-defined (and very simple) format which you can access using its GetData() method as mentioned above. Just notice that you may need to use GetAlpha() as well if your images have alpha channel.
However this is not how I'd do it because the data will be huge if you do it like this. While compressing it, as also suggested above, is possible, why bother doing it manually when wxImage already supports writing image in any of the standard image formats. Just create a wxMemoryOutputStream and pass it to SaveFile(). Then simply access the stream buffer directly using GetOutputStreamBuffer()->GetBufferStart() and related functions.
|
2,548,249 | 2,548,351 | Boost Regex throwing an error | I have the following error when I try to compile my code in g+ compiler using eclipse
In function `ZSt19__iterator_categoryIPKSsENSt15iterator_traitsIT_E17iterator_categoryERKS3_':
C:/Program Files (x86)/mingw/bin/../lib/gcc/mingw32/3.4.5/../../../../include/c++/3.4.5/bits/stl_algobase.h:(.text$_ZN5boost11basic_regexIcNS_12regex_traitsIcNS_16cpp_regex_traitsIcEEEEE6assignEPKcS7_j[boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::assign(char const*, char const*, unsigned int)]+0x22): undefined reference to `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::do_assign(char const*, char const*, unsigned int)'
collect2: ld returned 1 exit status
Build error occurred, build is stopped
All I have done is this statement
boost::regex re("\s+"); along with the header #inlucde
Could you kindly tell me how to proceed ?
| It appears that you're not linking to the correct library. Most Boost libraries are header-only, so you don't need to do anything about them at link time. Boost::regex, however, is one of the few that requires that you link with a library along with giving the compiler the proper headers.
After you fix that, you'll want to re-check the escape in your string -- right now your passing "\s", which shouldn't be allowed (at a guess, you probably want "\s+" instead).
|
2,548,282 | 2,548,374 | Decimal to binary (and vice-versa) | Can anybody give an example of c++ code that can easily convert a decimal value to binary and a binary value to decimal please?
| Well, your question is really vague, so this answer is the same.
string DecToBin(int number)
{
if ( number == 0 ) return "0";
if ( number == 1 ) return "1";
if ( number % 2 == 0 )
return DecToBin(number / 2) + "0";
else
return DecToBin(number / 2) + "1";
}
int BinToDec(string number)
{
int result = 0, pow = 1;
for ( int i = number.length() - 1; i >= 0; --i, pow <<= 1 )
result += (number[i] - '0') * pow;
return result;
}
You should check for overflow and do input validation of course.
x << 1 == x * 2
Here's a way to convert to binary that uses a more "programming-like" approach rather than a "math-like" approach, for lack of a better description (the two are actually identical though, since this one just replaces divisions by right shifts, modulo by a bitwise and, recursion with a loop. It's kind of another way of thinking about it though, since this makes it obvious you are extracting the individual bits).
string DecToBin2(int number)
{
string result = "";
do
{
if ( (number & 1) == 0 )
result += "0";
else
result += "1";
number >>= 1;
} while ( number );
reverse(result.begin(), result.end());
return result;
}
And here is how to do the conversion on paper:
Decimal to binary
Binary to decimal
|
2,548,488 | 2,548,525 | Analyze log files from many languages using a single tool. And recommendations of logging frameworks | We have a system build on lots of languages. The ones we are interested in logging, in order of priority, are:
C/C++
PHP
C#
Bash
Java
Wish list:
If it is possible, we would like logging to be achieved from the above languages in such a way that we may use a single log viewing tool for all of them. Ideally they would be in the same format, but next to that in as few formats as possible and readable from as many log file viewers as possible.
If it is possible logging to a single log file or a set of log files would be nice. With a possibility to filter based on the source language that is being logged.
We would like to copy the log files (or should be log to a database and copy it instead?) from multiple servers to a single location. So that we can analyze the log files from many servers at the same time (to see if any of our servers execute a certain piece legacy code for example).
Being able to change logging level at runtime would be nice.
Thank you for reading! It's quite a complex problem, I hope someone has wrestled with it before and has some valuable information!
| If you are using linux, syslog is great! The project I am working on right now uses syslog for most of our logging; everything goes to the same place (/var/log/messages) and you are able to log from many different tools all to the same log file. Apparently you can also use syslog to log to a remote server.
Otherwise if you are on windows you might consider writing to the event log.
|
2,548,510 | 2,548,858 | passing values between 2 different c++ files in same project | noob question right here. How do you pass values between 2 different cpp files in the same project? Do you make objects? if yes, how does the other cpp file see it?
some enlightment pls..
EDIT: some clarifications. I'm trying to interface direct input with a program (of which I have the plugins sdk). I'm trying to interface a joystick with it. It seems that there is no main function when I look through the code, but I might be wrong (like, I might not look in the right files). I know programming, and pointers and stuff, classes. Is there anything I should learn or get into in order to achieve what I want?
| In all but few cases it's a bad idea to share data among compilation units. A compilation unit, just to get you up to speed with the C++ terminology, usually effectively refers to an implementation file (with extension .cpp, or .cc etc.). The way we have the various compilation units "communicate" with each other is with header files and functions, rather than raw data.
Suppose we have an implementation file main.cc and a second implementation file human.cc. We want main.cc to communicate with human.cc. Here we go:
// main.cc
#include "human.hh"
int main()
{
make_the_human_dance(60);
return 0;
}
// human.hh
void make_the_human_dance(int duration);
// human.cc
#include "human.hh"
void make_the_human_dance(int duration)
{
// define how a human dances properly
// ...
}
Under the same principle you can use classes for communication. Declare the class in the header file and define the class' methods in the implementation file. Sometimes you must provide the implementation of functions in the header files, but that is already going offtopic.
|
2,548,555 | 2,548,586 | dot asterisk operator in c++ | is there, and if, what it does?
.*
| Yes, there is. It's the pointer-to-member operator for use with pointer-to-member types.
E.g.
struct A
{
int a;
int b;
};
int main()
{
A obj;
int A::* ptr_to_memb = &A::b;
obj.*ptr_to_memb = 5;
ptr_to_memb = &A::a;
obj.*ptr_to_memb = 7;
// Both members of obj are now assigned
}
Here, A is a struct and ptr_to_memb is a pointer to int member of A. The .* combines an A instance with a pointer to member to form an lvalue expression referring to the appropriate member of the given A instance obj.
Pointer to members can be pointers to data members or to function members and will even 'do the right thing' for virtual function members.
E.g. this program output f(d) = 1
struct Base
{
virtual int DoSomething()
{
return 0;
}
};
int f(Base& b)
{
int (Base::*f)() = &Base::DoSomething;
return (b.*f)();
}
struct Derived : Base
{
virtual int DoSomething()
{
return 1;
}
};
#include <iostream>
#include <ostream>
int main()
{
Derived d;
std::cout << "f(d) = " << f(d) << '\n';
return 0;
}
|
2,548,683 | 2,551,908 | C++ programming for clusters and HPC | I need to write a scientific application in C++ doing a lot of computations and using a lot of memory. I have part of the job but due to high requirements in terms of resources I was thinking to start moving to OpenMPI.
Before doing that I have a simple curiosity: If I understood the principle of OpenMPI correctly it is the developer that has the task of splitting the jobs over different nodes calling SEND and RECEIVE based on node available at that time.
Do you know if it does exist some library or OS or whatever that has this capability letting my code reamain as it is now? Basically something that connects all computers and let share as one their memory and CPU?
I am a bit confused because of the huge volume of material available on the topic.
Should I look at cloud computing? or Distributed Shared Memory?
| Currently there is no C++ library or utility that will allow you to automatically parallelize your code across a cluster of machines. Granted that there are a lot of ways to achieve distributed computing with other approaches, you really want to be optimizing your application to use message passing or distributed shared memory.
Your best bets would be to:
Convert your implementation into a task-based solution. There are a lot of ways to do this but this will most definitely done by hand.
Clearly identify where you can break the tasks up and how these tasks essentially communicate with each other.
Use a higher level library that builds on OpenMPI/Mpich -- Boost.MPI comes to mind.
Implementing a parallel distributed solution is one thing, making it work efficiently is another though. Read up on different topologies and different parallel computing patterns to make implementing solutions a little less painful than if you had to start from scratch.
|
2,548,887 | 2,549,144 | 0 not a valid FILE* when provided as a template argument | The following code
#include <stdio.h>
template <typename T, T v> class Tem
{
T t;
Tem()
{
t = v;
}
};
typedef Tem<FILE*,NULL> TemFile;
when compiled in a .mm file (Objective C++) by Xcode on MacOS X, throws the following error:
error: could not convert template argument '0' to 'FILE*'.
What's going on, please? The code in question compiled fine under MSVC. Since when is the 0 constant not a valid pointer to anything? Is this an artifact of Objective C++ (as opposed to vanilla C++)?
| According to the standard, you are out of luck. There is no way to initialize a pointer argument to anything besides the address-of a global. §14.3.2/1:
A template-argument for a non-type,
non-template template-parameter shall
be one of:
an integral constant-expression of integral or enumeration type; or
the name of a non-type template-parameter; or
the address of an object or function with external linkage, including
function templates and function
template-ids but excluding non-static
class members, expressed as &
id-expression where the & is optional
if the name refers to a function or
array, or if the corresponding
template-parameter is a reference; or
a pointer to member expressed as described in 5.3.1 .
§14.3.2/5:
for a non-type template-parameter of
type pointer to object, qualification
conversions (4.4) and the
array-to-pointer conversion (4.2) are
applied. [Note: In particular, neither
the null pointer conversion (4.10) nor
the derived-to-base conversion (4.10)
are applied. Although 0 is a valid
template-argument for a non-type
template-parameter of integral type,
it is not a valid template-argument
for a non-type template-parameter of
pointer type. ]
However, Comeau accepts this invalid workaround:
typedef Tem<FILE*, (FILE *) NULL > TemFile;
And this code has a slim chance of compliance: I can't find where the standard specifically says that a default expression is used verbatim in place of a a missing argument, and I can't find a matching known defect. Anyone have a reference?
#include <stdio.h>
template <typename T, T *v = (T*) 0> class Tem
{
T t;
Tem()
{
t = v;
}
};
typedef Tem<FILE> TemFile;
For more portability, you might consider creating a bogus FILE FILE_NULL;, pass &FILE_NULL, and test for pointer-equality with that instead of zero.
|
2,548,918 | 2,549,103 | Is there any Graph Builder for GStreamer? | Is there any Graph Builder for GStreamer? So to say you build graph you get code
| gst-editor seems to be something like what you are looking for. It doesn't appear to support generating C++ code, but what it does support is saving XML that can be loaded into your program in the same way that libglade allows you to load Glade GUIs. It looks very intuitive and low-nonsense, judging by the screen shots.
|
2,549,015 | 2,549,323 | Finding a MIME type for a file on windows | Is there a way to get a file's MIME type using some system call on Windows? I'm writing an IIS extension in C++, so it must be callable from C++, and I do have access to IIS if there is some functionality exposed. Obviously, IIS itself must be able to do this, but my googling has been unable to find out how. I did find this .net related question here on SO, but that doesn't give me much hope (as neither a good solution nor a C++ solution is mentioned there).
I need it so I can serve up dynamic files using the appropriate content type from my app. My plan is to first consult a list of MIME types within my app, then fall back to the system's MIME type listing (however that works; obviously it exists since it's how you associate files with programs). I only have a file extension to work with in some cases, but in other cases I may have an actual on-disk file to examine. Since these will not be user-uploaded files, I believe I can trust the extension and I'd prefer an extension-only lookup solution since it seems simpler and faster. Thanks!
| HKEY_CLASSES_ROOT\\.<ext>\Content Type (where "ext" is the file extension) will normally hold the MIME type.
|
2,549,019 | 8,125,118 | How to avoid namespace content indentation in vim? | How to set vim to not indent namespace content in C++?
namespace < identifier >
{
< statement_list > // Unwanted indentation
}
Surprisingly, 'cinoptions' doesn't provide a way to edit namespace content indentation.
| Not sure when it was introduced but my installed version of vim, v7.3.353 has a cino option that handles cpp namespace explicitly. I am currently using the example value:
cino=N-s
and as per :help cinoptions-values
NN Indent inside C++ namespace N characters extra compared to a
normal block. (default 0).
cino= cino=N-s
namespace { namespace {
void function(); void function();
} }
namespace my namespace my
{ {
void function(); void function();
} }
The link the OP posted is for v7.3.162
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.