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 |
|---|---|---|---|---|
6,734,375 | 6,734,434 | Get current time in milliseconds using C++ and Boost | In my thread (using boost::thread) I need to retrieve the current time in ms or less and to convert into ms:
Actually, reading here I've found this:
tick = boost::posix_time::second_clock::local_time();
now = boost::posix_time::second_clock::local_time();
And seems to work, but after I need to have a long value of th... | You can use boost::posix_time::time_duration to get the time range. E.g like this
boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();
And to get a higher resolution you can change the clock you are using. For example to the boost::posix_time::microsec_clock, though this can be OS dependent. ... |
6,734,413 | 6,735,307 | Committing a TLB file to repository | I'm importing a TLB file into my project since I'm using a COM DLL. A TLB file is a binary file, which I need to compile my source code and so I was wondering if it's good programming practice to commit it to the repository.
| Yes, it's ok to put binary files in a source repository. The rule sometimes called 'do not put binary files in a source repository' should better be called 'do not put temporary files or files that are a compilation result in a source repository'. Basically anything that can't be produced from other files and is releva... |
6,734,492 | 6,735,302 | C-callback to function template: explicitly instantiate template | Premise
I’m using a C library (from C++) which provides the following interface:
void register_callback(void* f, void* data);
void invoke_callback();
Problem
Now, I need to register a function template as a callback and this is causing me problems. Consider the following code:
template <typename T> void my_callback(vo... | POSIX recommends the following way to cast between function pointer types and object pointer types (which is undefined in C99):
typedef void function_type(void*);
function_type *p_to_function = &my_callback<T>;
void* p_to_data = *(void**)&p_to_function;
// Undefined:
// void* p_to_data = (void*)p_to_function;
Notice ... |
6,734,518 | 6,742,478 | Active Directory: Searching Users/Group in LDAP via C++ | Currently we started to migrate our existing authentication to Active Directory authetication,
but now i am facing lot of issues in searching users and group.
let me explain you we have an application/server who will autheticate and authorize user. so we will change our server to autheticate from LDAP server configured... | LDAP: Programming Directory-Enabled Apps by Mark Smith, Timothy A. Howes
This book contains lot of code samples using C. I have not looked at other books though. This was sufficient for me to get started.
|
6,734,699 | 6,734,993 | Can't create C# COM object (Class not registred) | My global objective is to create a COM-based application, where client part is C++ code and server part - C#. It looks simple.
I try to use the sample from MSDN:
http://msdn.microsoft.com/en-us/library/aa645738(v=vs.71).aspx
I make a solution with two projects (using VisualStudio2008) and compile. well.
I register comp... |
In the registry a see my class, but "default value" of InprocServer is mscore.dll
No, that's not a mistake. Mscoree.dll is the bootstrapper for the CLR, it ensures the CLR is properly loaded and initialized to allow managed code to run in a native application without CLR support. And it provides the DllGetClassObje... |
6,735,123 | 6,735,301 | c++ boost calculate time spent in function | Hi again with a boost question: I need to calculate the time spent in my function in my boost thread: here is the code:
boost::posix_time::microseconds tes( 12 );
int i = 0;
while( true )
{
boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time( );
myFunction( );
boost::this_thread... | According to boost documentation, local_time might not achieve microsecond level resolution on Win32 system:
ptime microsec_clock::local_time()
Get the local time using a sub second resolution clock. On Unix systems this is implemented using GetTimeOfDay. On most Win32 platforms it is implemented using ftime. Win32 sy... |
6,735,168 | 6,735,245 | How to determine what file called a c++ program? | I'm writing a C++ program for a Windows 7 user which will be the default program called when she double-clicks certain files (.ora files) and I need to know how I can essentially pass in to the program the file name [including path] that she is trying to open. Since the program won't be running at the time of file sel... | When double-clicking a file results in opening an executable, the path and name of the file are passed as the first command line argument.
int main(int argc, char *argv[]) {
if(argc<2) return 1;
std::ifstream file(argv[1]);
// ...
}
Since the first entry in argv is the path to the executable, you are inter... |
6,735,187 | 6,735,279 | Can I use a FILE* to initialize a C++ ostream object? | Can I use an elsewhere opened
FILE* f = ...
thing to initialize some std::ostream instance? Like this (pseudocode):
FILE *f = ...;
std::ostream os;
os./*bind_to_f*/( f ); // HOW?
os << "Hello world" << std::endl;
| With GCC you can just pass the existing file descriptor to the constructor (ref):
FILE *f = ...;
std::ofstream os(fileno(f));
Constructor: ofstream::ofstream (int fd)
Make an ofstream for writing to a file that was already open, using file descriptor fd.
|
6,735,207 | 6,735,630 | How to get data from Syslog-NG / Syslog | I am looking to create a C++ socket app that will listen on a port, and receive data from Syslog and Syslog-NG. Is there documentation anywhere about how it will come through the socket?
| Yes, there is. The syslog protocol is described in RFC 5424. According to IANA, it uses UDP 514.
|
6,735,277 | 6,735,311 | Any difference in linking with gcc vs. g++? | Are there any differences in the linking process between gcc and g++?
I have a big C project and I just switched part of the code to C++. The code isn't using std C++ library yet, so -llibstdc++ isn't needed for now.
| The main difference is that (assuming the files are detected as C++) g++ sets up the flags needed for linking with the C++ standard library. It may also set up exception handling. I wouldn't rely on the fact that just because your application doesn't use the standard library that it isn't needed when compiled as C++ (f... |
6,735,393 | 6,735,741 | get the value of a c constant | I have a .h file in which hundreds of constants are defined as macros:
#define C_CONST_NAME Value
What I need is a function that can dynamically get the value of one of these constants.
needed function header :
int getConstValue(char * constName);
Is that even possible in the C langage?
---- EDIT
Thanks for the help... | Here you go. You will need to add a line for each new constant, but it should give you an idea about how macros work:
#include <stdio.h>
#define C_TEN 10
#define C_TWENTY 20
#define C_THIRTY 30
#define IFCONST(charstar, define) if(strcmp((charstar), #define) == 0) { \
return (define); \
}
int getConstValue(const... |
6,735,720 | 6,735,859 | What are the rules around instantiation of template types (class/function) when taking an address? | In answering this question, I came across this difference in behaviour with respect to template instantiation.
Initially there is a function template
template <typename T> void my_callback(void* data) { … }
Now something requires the address of this - specifically a void*, so the obvious approach is
bar(reinterpret_ca... | From n3290, 14.7.1 Implicit instantiation [temp.inst]
2 Unless a function template specialization has been explicitly
instantiated or explicitly specialized, the function template
specialization is implicitly instantiated when the specialization is
referenced in a context that requires a function definition to e... |
6,735,721 | 6,737,428 | gcc report unreferenced symbol for version based library | One of my shared library my.so use version based symbol as symbol@@test_1.2.3 from library test.so. When I link my.so shared library with my executable, it says 'unreferenced symbol symbol@@test_1.2.3'. This happens when link line is as follows -
g++ -o myexecutable myexecutable.o -L/path-to-my.so -lmy -L/path-to-test... | I suspect that there's another libtest somewhere (maybe as libtest.a) that ld is finding first which doesn't have the symbol your program is looking for.
Use the -Wl,--verbose option to have the linker provide verbose output about what files it's opening or trying to open. That should tell you why one run is behaving ... |
6,736,015 | 6,736,310 | Problem using bind1st and bind2nd with transform | I think C++0x bind is much better, but I'd like to understand the old bind1st and 2st before I use C++0x's bind:
struct AAA
{
int i;
};
struct BBB
{
int j;
};
// an adaptable functor.
struct ConvertFunctor : std::binary_function<const AAA&, int, BBB>
{
BBB operator()(const AAA& aaa, int x)
{
B... | Change
struct ConvertFunctor : std::binary_function<const AAA&, int, BBB>
{
BBB operator()(const AAA& aaa, int x)
{
to:
struct ConvertFunctor : std::binary_function<AAA, int, BBB>
{
BBB operator()(const AAA& aaa, int x) const
{
Don't ask me why, I only read the compilation error messages.
|
6,736,340 | 6,736,373 | Right way to instantiate instance-variables in C++ | I want to ask where in C++ is the right place to instantiate a instance-variables? I think it should not be in the class declaration, but otherwise I don`t see any disadvantages apart from poor object-oriented design:
class A{ member m; };
I think it should better be like:
class A{ extern member m; };
But I don`t know... | You can use the constructor initialization list to construct all your member variables as you need.
A::A(const member& memberArg)
: m(memberArg)
{ }
Look at this for more info.
|
6,736,386 | 6,736,761 | Frustrated with my Program Hanging on Return with Waiting Channel of futex_wait_queue_me | I'm working on a server-based project. Basically, when the server starts, it needs to bind a socket port (say 1935).
My problem is, if another instance of my program is running, that is, the socket port 1935 is being used, then a new instance of my program will hang on my main() return.
The Error info:
Error starting ... | I suspect you need to signal a condition or add an item to an event queue to wake up the sub-thread so it can exit before you do the pthread_join call.
|
6,736,429 | 6,737,592 | C++ idiom for dynamically populating objects and destroying at return | I'm using C++0x.
I have a function call_third_party, that receives a list of A*, converts it to a list of B*, then passes that list of B* into function third_party. After third_party is called, the list of B* is no longer needed.
As the name suggests, I have no control over third_party.
Currently I have something like ... | void call_third_party(const vector<A*>& as)
{
std::vector<B> b(as.begin(), as.end());
std::vector<B*> bp(b.size());
std::transform(b.begin(), b.end(), bp.begin(), [](B& b) { return &b; });
third_party(bp);
}
|
6,736,467 | 6,736,537 | c++ overload operator resolution | I'm learning c++ and using C++ Primer. Consider the following exercise 14.46:
class Complex {
Complex(double);
// ...
};
class LongDouble {
friend LongDouble operator+(LongDouble&, int); // (1)
public:
LongDouble(int);
operator double();
LongDouble operator+(const Complex &); //... | You have the following competing user defined functions (candidates)
operator+(LongDouble&, int); // friend
operator+(LongDouble&, Complex const&); // member
operator+(LongDouble const&, double); // global
You are invoking this with arguments:
(LongDouble&, double)
For the first argument, the first two candidates are... |
6,736,498 | 6,736,566 | combining separate audio and video files into one file C++ | I am working on a C++ project with openCV. It is a simple web cam application with basic features like capturing pictures and videos. I have already been able to save video (w/o audio). Since openCV doesnot support audio processing, I was wondering if there is any way I can record audio separately in a different file a... | As you said, opencv doesn't by itself deal with audio. However once you get a separate audio and video file, you can combine them using a technique called muxing. There are many many ways to do this. I use VirtualDub for most of my muxing needs, although it is windows only (not sure if that's a problem). I know ffmpeg ... |
6,736,938 | 6,736,972 | C++ - returning a const vector of const vectors of const objects | I'm parsing a file and creating a vector of a vector of Foo objects.
vector< vector<Foo*> > mFooVectors;
I have to allow access with the following getFoos function.
const vector<const Foo*>& getFoos(int index);
So I created a const declaration of my vector:
const vector< const vector<const Foo*> > mConstFoo... | vector's copy constructor should be able to handle it, but you'll have to do it in the initializer list of your class's constructor since it's a const member.
Edit: That was wrong... Vector's copy constructor can't handle it. See David Rodriguez' post for an explanation (vector and vector are unrelated types).
|
6,737,197 | 6,737,290 | Do boost::lambda::bind expressions prevent in-lining / is there an alternate form that doesn't? | As a matter of academic interest, does using bind templates (esp in boost::lambda) prevent in-lining? And if so, other than using declared functors, is there a boost::lambda form that does not prevent in-lining? (And especially in the latest gcc)
namespace bll = boost::lambda;
class MyItem
{
public:
float ... | No. Nothing prevents inlining except for how advanced compiler* technology is. Unless Boost.Lambda resorts to type erasure, which it has no reason of using, everything it does can be inspected statically as easy as hand-written code. A relevant snippet in the Boost.Lambda documentation suggests that the library deliver... |
6,737,260 | 6,738,909 | Creating a thread for a database in Qt: a reasonnable design or nonsense? | the application I'm trying to design with Qt is quite data intensive; it is essentially a database. I'm looking for a design that would allow me to keep the UI reactive. My guess is I should keep only the UI in the main thread and create a thread for the database.
However:
- creating a database object inheriting from Q... | You might consider using QtConcurrent::run(). You'll pass in the function you want. It'll spool off a thread to run the function and give you a QFuture that you can use to get the eventual result. You could poll the QFuture to see if it isFinished(). Better, however, may be to use QFutureWatcher which watches the Q... |
6,737,374 | 6,737,505 | C++ template non-type parameter type deduction | I'am trying to do this work:
template < typename T, T VALUE >
void f()
{
/* ... */
}
int main()
{
f<10>(); // implicit deduction of [ T = int ] ??
return (0);
}
The purpose is to simplify a much more complex template.
After many searches, I don't find any way to do that on C++0x,... | C++0x introduces decltype(), which does exactly what you want.
int main()
{
f<decltype(10), 10>(); // will become f<int, 10>();
return 0;
}
|
6,737,544 | 6,737,573 | Why passing an object pointer to a method, where it is deleted, is different from deleting the object directly? | The code causing a leak of one block is as follows:
in = new RandomAccessFile(fileName, "r");
in->close();
Mem::delObject(in);
where RandomAccessFile is the class with the string field, and delObject() is a static method as follows:
void Mem::delObject(Object* object) {
delete object;
... | I can only guess but it seems you forgot a virtual destructor in Object class. Thus the RandomAccessFile destructor won't be called causing a leak of its properties.
|
6,737,724 | 6,737,803 | How to calculate a probability with given data? | this is mathematical question for programming needs...
whats the way to calculate probability if you have some data like this
40000
32423432
3423423
4543535
354545
the lowest number is lets say 40000 and the biggest is 32423432
those numbers are given in some txt file like a input parameter and i need to generate a x... | If you want a linear scaling (mapping) then this will work (using doubles):
double newsmallno = (number - smallest)/(largest - smallest)
Note this gives a value of 0.0097 for a number of 354545, so maybe you don't want it to be linear, in which case you need to give more details.
|
6,738,006 | 6,738,049 | How do I debug a native code project from inside a managed code project? C++/C# | How do I debug a native code project from inside a managed code project? I am using C# to call C++ code and need to debug the C++ code. Otherwise, I must exit out of the project, open the C++ project, create a tester and then debug the code. This is horrible.
| Add your c++ project to the solution containing your C# code
In the C# project properties pages, under the debug tab
Check "Enable unmanaged code debugging"
If that doesn't work you also need to open the Options dialog from either the Debug or the Tools menu (in VS2017) and go to Debugging->General. Check the option
"S... |
6,738,125 | 6,738,188 | Testing C code with googletest (Google C++ Testing Framework) | I'm trying to test C code with googletest but I'm having some problems when my C header files are included in the C++ test file because the g++ compiler handle them as C++ headers.
I've tried to include these headers inside extern "C" {} with no success.
Is there a way g++ compiler can handle these headers as C ones?
| extern "C" only changes link stage name mangling. If you are using C features that aren't shared by C++ then you are SOL
|
6,738,472 | 6,738,592 | Removing msvcp90d.dll dependancy from Windows binary | I have a dll that I distribute that will not run on some windows OS. Using dependancy walker I discover msvcp90d.dll missing on these systems. I DO NOT want any run time dependancies that require the C++ redistributable, and since the application that calls the DLL is not written in C++, it does not have any dependancy... | MSVCP90 is nothing to do with debug (that'd be msvcp90d). You can remove your dependency by switching the compiler to /MT (instead of /MD). You also need to ensure that every static library you link to was also compiled /MT.
I recommend against building apps /MT because it has a significant negative effect on system p... |
6,738,651 | 6,738,862 | visual studio c++ library files broken/corrupted. help! | i was replacing variable names in a large project using the replace all function.
next time i go to compile, i have 1600+ errors. they're all in library files like xlocnum, string, xdebug, stdexcept. how do I get rid of these? can these files be replaced??
Error 18 error C2039: 'c_str' : is not a member of 'std::_D... | From the output you provided it looks like applied the find/replace files in "VC++ Include Directories". Go into the include directories and check the modified dates - if some of them are recent then you will need to restore them either from a backup or reinstall/repair the SDK and quite possibly Visual Studio itself.
|
6,738,829 | 6,738,971 | Compile only specific library from Qt | I want to compile one of Qt's default libraries (QDeclarative) on OSX.
Which argument do I need to pass to ./configure to achieve this?
| This is not a standalone component as far as I know it is dependent on QtXML and some other parts of QT within QtCore. Just compile QT for Mac using the cross platform options in the link Evan Teran posted here.
If you only want to link against QtCore add QT -= gui to your .pro file in QtCreator or otherwise specify re... |
6,739,157 | 6,739,220 | LNK1004: Cannot open file 'Jsfwbase12D.lib' | So, I'm a bit confused on this error that I'm getting while compiling/linking a C++ project.
In the Input section of the Linker configuration, we have a additional dependency with the file name Jsfwbase12D.lib. This file was recently changed to Jsfwbase12.lib without the capital D. I changed the references within th... | Your code likely contains #pragma comment(lib, "Jsfwbase12D.lib") somewhere. This informs the linker of a dependency which gets included during link time.
|
6,739,186 | 6,744,074 | force g++ to zero initialize memory | I want to write some unit tests of a library I'm writing
I have a class which looks like this one :
class A
{
public:
A(B* pB)
// construction details, involves my library
// but ultimately there is a new being done ,)
B* m_pB;
};
I'd like to check that the pointer m_pB is actually initialized, so I... | Thanks for your answers, but I'd like a less invasive technique, as the classes are part of the test, and their constructor is right in the midle of the subject which is dependency injection.
I was just hopping for something similar to visual studio which sets the memory to some specific value in debug mode (I think?),... |
6,739,271 | 6,739,431 | Finite State Machine With Function Pointers | I am learning to use finite-state machines for some tasks but I am having problems navigating my state table and executing the functions to make it a useful system.
Consider my state machine:
(source: wikimedia.org)
Explanation:
* = Print char to stdout
N = '\n'
S = ' '
A = aA-zZ
The code I started with from Automata... | Using functions as states is very powerful, but using transition tables is very error prone and painful compared to using recursive functions (function states that return functions). A fantastic implementation for you to consider is the quantum hierarchical statem machine. Although it is only about 1000 lines of code... |
6,739,785 | 6,739,884 | Inevitable variadic templates in GCC (used with CUDA)? | I was trying out some CUDA/Thrust code on Linux/GCC and wanted to use some TR1 libraries, when I noticed something peculiar: Most libraries will invariably pull in tr1_impl/type_traits (4.4) or just type_traits (4.6), and that header will always contain variadic templates, like so:
template<typename _Res, typename...... | Welp, an implementation is not required to provide headers. It's required that an #include <stuff> does The Right Thing. So that means that if an implementation decides to use headers for this functionality, it's not required that those headers be conforming C++. And in fact GCC has supported variadic templates as an e... |
6,740,353 | 7,167,606 | Access 'Arguments' in JavaScript V8 Callback | I'd like to be able to access the Arguments& args of a callback. Right now when I set the C++ function to be called from the JavaScript side it looks like this:
global->Set(String::New("login"), FunctionTemplate::New(Login));
And the prototype of the C++ function is:
Handle<Value> MyClass::Login(const Arguments& args)... | v8::Arguments::Length() will return the number of arguments passed from JavaScript. The v8::Arguments& variable is accessed using an array subscript.
for (int32_t index = 0; index < arguments->Length(); ++index) {
if (arguments[index]->IsString()) {
::printf("%s\n", *v8::String::Utf8Value(arguments[index]->ToStri... |
6,740,425 | 6,740,479 | Can't write the last part of a txt file to cout using ifstream | The code below will print all of the text from the sample text file I'm using except for the last little snippet of it. I think this has something to do with the eof or the byte size I'm using not working as I expect.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]){
int l... | As you already know, you have a wrong size of buffer. The other thing is the read of less than 1024 characters (going to happen at the end if your file doesn't have exactly n*1024 bytes). Take the advantage of istream::gcount which gives you number of characters extracted by last read:
char buffer[1024];
while(stream)
... |
6,740,671 | 6,740,843 | C++0x error with constexpr and returning template function | I tried to find a solution for the problem of the question C++ template non-type parameter type deduction, which does not involve a template parameter to call f, but implicitly chooses the correct type for the template parameter.
Since constexpr should guarantee that a function only contains compile time constants, and... |
Since constexpr should guarantee that a function only contains compile
time constants, and is evaluated at compile time (at least thats what
i think it does), i thought it might be the solution for this issue.
A constexpr function can be used in a constant expression context, but is not restricted to one. In this... |
6,740,723 | 6,740,831 | Low-level keyboard hook: callback not reached | I'm trying to create a quick piece of code to capture the key sequence sent by one of the "hotkey" buttons on my tablet and reprogram its function. The button sends a LWin+LCtrl+Tab when pressed.
After searching around for a while I decided to try using a WH_KEYBOARD_LL hook, but after a few hours I still can't get the... | The issue is that your console application doesn't have a message loop to process the hook messages.
Replace your while(1) loop with the following and see if that works:
MSG msg;
while( GetMessage( &msg, NULL, 0, 0 ) != 0 )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
if(gotKey)
... |
6,741,050 | 6,741,140 | Lua: getting global function failing after loading file | I'm attempting to call a function inside of a lua file called test2.lua
This is the contents of test2.lua:
function abc(path)
t = {}
table.insert(t, "a")
return t
end
As you can see it takes a single input and returns a string.
Here is my C code. It's pretty simple. However my call getglobal in order to call that f... | The function luaL_loadfile() reads, parses, and compiles the named Lua file. It does not execute any of its content. This is important in your case because the statement function abc(path)...end has no visible effect until it is executed. The function keyword as you've used it is equivalent to writing
abc = function(p... |
6,741,059 | 6,741,406 | enum [tag] [: type] {enum-list} [declarator] in C++ - is this legal? | I am working with a custom enumerated type in C++, but it does not have many values. I want to try to reduce the size that they take up, and I've heard that enum types are always integers by default. I then came across the MSDN entry on C++ enumerations, and found the following syntax very interesting:
enum [: type] ... | As 0A0D's said, the notation you're using is non-Standard in C++03, but has been adopted by C++11 under the term "scoped enums".
If that's not soon enough for you, then you can consider explicitly specifying the bit field width used for the enum fields in the size-critical structures in which they're embedded. This ap... |
6,741,422 | 6,741,871 | What is the recommended way to define a GUID for a driver? | I would like to define/generate a GUID (interface class) for my test driver. What is the best way to do that 'programatically using C/C++' so it won't conflict with other devices/drivers in the system?
Also, are there any standard guidelines to follow or other things to keep in mind while creating a new GUID?
Please su... | CoCreateGuid is the Win32 API that does this using randomness sources including your network adapter.
Martyn
|
6,741,691 | 6,741,756 | template specialization for a const pointer to a const type | I was reading http://bartoszmilewski.wordpress.com/2009/10/21/what-does-haskell-have-to-do-with-c/ and came across this code to check if a type is a pointer or not:
template<class T> struct
isPtr {
static const bool value = false;
};
template<class U> struct
isPtr<U*> {
static const bool value = true;
};
template<c... | The result is coming correct only; your third specialization is invoked when you call isPtr <int const * const>; which you are setting to true.
You can choose enum over bool in this case as you have 3 states:
enum TYPE
{
NOT_POINTER,
IS_POINTER,
IS_CONST_POINTER
};
template<class T> struct
isPtr {
static const ... |
6,741,718 | 6,742,278 | size_t, ptrdiff_t and std::vector::size() | I thought that the correct type to use to store the difference between pointers was ptrdiff_t.
As such, I'm confused by the way that my STL (msvc 2010) implements it's std::vector::size() function. The return type is size_t (this is mandated by the standard, as far as I understand it) and yet it's computed as the diffe... | Generally speaking, ptrdiff_t is a signed integral type of the same size as size_t. It must be signed so that it can represent both p1 - p2 and p2 - p1.
In the specific case of the internals of std::vector, the implementor is effectively deriving size() from end() - begin(). Because of the guarantees of std::vector (... |
6,741,819 | 6,741,889 | Assigning rows of a static 2D array to another's rows | Here's what I have so far:
typedef const float Chord[6];
static Chord progressionOne[] = {
{5.0f / 6.0f, 1.0, 1.25, 5.0f / 3.0f, 2.0, 2.5}, // i
{5.0f / 6.0f, 2.0f / 3.0f, 1.0, 4.0f / 3.0f, 5.0f / 3.0f, 2.0}, // VI
{0.75, 1.0, 1.25, 1.5, 2.0, 2.5}, // III
... | If you really want these to be simple arrays, you could simply create #define macros (pre-processor definitions) for the chords, and make the progressions reference those chords:
typedef const float Chord[6];
#define CHORD_I { 5.0f / 6.0f, 1.0, 1.25, 5.0f / 3.0f, 2.0, 2.5 }
#define CHORD_VI { 5.0f / 6.0f, 2.0f / 3.0f,... |
6,741,839 | 6,764,222 | Avg thinks my program is a hack tool when I include windows.h | I have a blank c++ project and when I include windows.h and try to run it, avg pops up and says it's a hack tool. (I've tested it, just including the header file sets it off.)
I've added my programming folder as an exception so I can run it but I wouldn't want to distribute a program like that is there something I can... | Building in release mode fixes the problem.
|
6,741,922 | 6,741,950 | Doubt on scope in loops | just have a question to ask regarding loops.
r=1000000.0;
for (i=0;i<laser_count;i++)
{
if(this->laser_ranges[i][0] !=-1)
{
r= this->laser_ranges[i][0];
}
else
{
this->laser_ranges[i][0]=r;
}
}
My question here is if laser_ranges[i][0] = -1 then it is always equal to 1000000.0. Am i right to say this? or... | If typeof r and laser_ranges[][] are same then --> yes, you are correct to say this only first time (Edit: which is a very special case). Usually r might change based on the values of laser_ranges[i][0].
|
6,741,982 | 6,741,993 | How to idiomatically define assignment operator for immutable classes? | In C++ what is the idiomatic way to define operator= on a class that should be immutable. For example all its member variables are const.
typedef unsigned char byte;
class Binary
{
protected:
const unsigned long size;
const byte* bytes;
public:
Binary(const unsigned long size);
Binary(const Binary &b... | Assuming that you are not going to reassign your members (using const_cast etc.), I would suggest to explicitly mention in your code that you are not using operator =.
In Current C++ standard, make it private and unimplemented:
class Binary
{
//...
private:
Binary& operator = (const Binary&);
};
In upcoming C++0x ... |
6,742,008 | 6,742,025 | What are the typical use cases of an iterator_trait | I am new to C++ so please bear with me. I am trying to understand STL iterator_traits. In the book "The C++ Standard Library" the structure iterator_traits is defined as follows:
template <class T>
struct iterator_traits {
typedef typename T::value_type value_type;
typedef typename T::difference_type difference_typ... | Pointers into an array can be used as random access iterators.
There needs to be some consistent way to get these types both for pointers (which obviously can't have the types declared as nested types, since only classes can have nested types) and for class-type iterators. The traits class template provides this consi... |
6,742,143 | 6,742,163 | Map in Map Map.Clear() error | void destroy()
{
AList::const_iterator a;
for(a = AList.begin(); a != AList.end();)
{
if(!a->second.BList.empty())
a->second.BList.clear();//will give error if not mutable
}
}
typedef std::map<unsigned int,int> bmap;
typedef std::map<unsigned int,someStruct> Alist;
typedef struct som... | You should use iterator instead of const_iterator, if your intent is to call clear. const_iterator is for cases where you are calling only const member functions.
Using mutable is not appropriate for this situation. Only mark member variables mutable if they are not part of the object's visible state, e.g., cached data... |
6,742,277 | 6,742,288 | How to delete the object that is create inside the local function in c++? | I will explain the scenario using example.
void func()
{
CLine* pObj = new CLine();
}
void func2()
{
}
How to delete the CLine object in func2()?
Is it possible?
Thanks
| It's not possible. As soon as func finishes you've lost all reference to pObj and leaked its memory.
|
6,742,316 | 6,742,375 | Efficient way to find the max number in an array | This is an interview question
There is an array of integers. The elements in the array can follow the following patterns.
numbers are in ascending order
numbers are in descending order
numbers increases in the beginning and decreases in the end
numbers decreases in the beginning and increases in the end
What is the e... | In that case, all you need to do is to determine whether it's (3). If not, the answer is max(first, last).
In the case that all elements are equal, you'll need to exhaustively search the array to show that there's not one high number somewhere in the middle. So I think it's O(n) to determine whether you're in (3).
|
6,742,386 | 6,742,421 | template arguments inside a compile time unrolled for loop? | wikipedia (here) gives a compile time unrolling of for loop.......
i was wondering can we use a similar for loop with template statements inside...
for example...
is the following loop valid
template<int max_subdomain>
void Device<max_sudomain>::createSubDomains()
{
for(int i=0; i< max_subdomain; ++i)
{
... | Re-Edit:
My previous answer was correct. I have tried your code, it's giving compiler error. You cannot declare objects like that, as i cannot remain a compile time constant (as you are intending to do i++). template parameter must always be compile time constants. Here is the demo.
Also note that, loop unrolling is do... |
6,742,399 | 6,742,874 | c++ what is the fastest way of storing comma separated int in std::vector | I have a comma separated integers and I want to store them in std::vector<int>. Currently I am manually doing it. Is there any built-in function which did the above functionality?
Edit:
I was in hurry and forget to put full details
Actually i have string (to be exact Unicode string) containing CSvs e.g. "1,2,3,4,5"
Now... | You can do this using purely in STL for simplicity (easy to reading, no complex libs needed), which will be fast for coding, but not the fastest in terms of execution speed (though you can probably tweak it a little, like pre-reserving space in the vector:
std::vector<int> GetValues(std::wstring s, wchar_t delim)
{
... |
6,742,639 | 6,742,675 | C++ "catch (...)" parameter | I recently saw something interesting in some c++ code:
try {
//doStuff
} catch ( ... ) {
//doStuff
}
The "..." is what I'm referring to.
Now, at first glance one might think that this is nothing more than a filler, like a comment similar to the "doStuff" we see. The weird thing is that typing this in the Eclipse ... | As others have mentioned, it catches everything. From what I've seen, this is mostly used when you can't identify the actual exception that is thrown. And this could happen if that exception is a Structured Exception, which is not a C++ one. For instance, if you try to access some invalid memory location. It is usually... |
6,742,648 | 6,746,052 | Compiling c++ Visual C++ 7.1 solution without Visual C++ | I need to build a visual c++ solution (.dsp VC++ 7.1) which was written by someone else back in 2005. I'm attempting to compile the solution in VS2010 trial but it is giving me some errors as outlined below:
error C3867: 'CServerSocket::SelfDestruct': function call missing argument list; use '&CServerSocket::SelfDestru... | For the first issue, use the & to explicitly take a pointer to member. There is no other way to get this to compile with VS9 or 10. This is a mechanical thing that is easy to add, very little C++ knowledge needed.
The second issue is, I think, that you're missing a 'typename' qualifier somewhere. This is harder, if you... |
6,742,699 | 6,742,851 | Can't access function from header file | //head.h//
extern int sum(int,int);
//head.cpp//
#include "head.h"
#include "stdafx.h"
int sum(int x, int y)
{
return (x+y);
}
//mainfn.cpp//
#include "head.h"
#include "stdafx.h"
#include string
#include iostream
#include stdio.h
using std::string;
using std::cout;
using namespace System;
int main()
{
int x=10,y=... | You need to place the inclusion of head.h after stdafx.h. When precompiled headers are enabled the compiler will ignore the contents of all includes that occur prior to (in this case) the inclusion of stdafx.h .
|
6,742,861 | 6,745,376 | Problem running c++ project in eclipse, Red Hat Linux | I am trying to run a c++ project in Red Hat Linux using eclipse. I am getting the following error:
Description Resource Path Location Type
make: *** [Makefile] Error 3 C/C++ Problem
can anybody help me solving this?
| set environment variable QMAKESPEC as us want like 'linux-g++' or whatever you want
use export QMAKESPEC=linux-g++ to set the variable
|
6,742,895 | 6,743,272 | Add member to existing struct without breaking legacy code | There is the following definition in some legacy code that I am working with.
struct VlanData
{
uint16_t mEtherType;
uint16_t mVlanId;
};
I want to add a new member to this struct:
struct VlanData
{
uint16_t mEtherType;
uint16_t mVlanId;
uint8_t mVlanPriority; // New member
};
However, use of Vlan... | struct VlanData {
struct P
{
uint8_t operator=(uint8_t v) { mVlanPriority = v; }
uint8_t mVlanPriority; P() { mVlanPriority = 0; };
};
uint16_t mEtherType;
uint16_t mVlanId;
P mVlanPriority;
};
Define other kinds of operators and add type conversion functions as you need.
eg:
i... |
6,742,921 | 6,742,962 | Constructor behaviour in runtime polymorphism | We know the need for a virtual destructor.
Base *bptr = new Derived();
delete bptr;
If a derived class object is pointed by a base class pointer and when the object goes out of scope, only the Base class destructor gets called unless the destructor is virtual.
I am wondering how does the constructor work properly in t... | While creating the object with new we have the complete information of the object;
new Derived(); // static type is same as dynamic type
LHS part where you assign pointer is irrelevant. That's why you don't need such virtual mechanism for constructor. See Bjarne Stroustrup's page for more info.
Other note, virtual des... |
6,743,003 | 6,743,039 | How calculate sum of values in std::vector<int> |
Possible Duplicate:
sum of elements in a std::vector
I have std::vector<int> and I want to calculate the sum of all the values in that vector.
Is there any built in function or I need to write my custom code?
| Use the STL algorithm std::accumulate, in the numeric header.
#include <numeric>
// ...
std::vector<int> v;
// ...
int sum = std::accumulate(v.begin(), v.end(), 0);
|
6,743,093 | 66,585,762 | Composability of STL algorithms | The STL algorithms are a pretty useful thing in C++. But one thing that kind of irks me is that they seem to lack composability.
For example, let's say I have a vector<pair<int, int>> and want to transform that to a vector<int> containing only the second member of the pair. That's simple enough:
std::vector<std::pair<i... | Since C++20 you can use std::ranges::copy together with the range adaptors std::views::filter and std::views::values from the Ranges library as follows:
int main() {
std::vector<std::pair<int, int>> values = { {1,2}, {4,5}, {6,7}, {9,10} };
std::vector<int> result;
auto even = [](const auto& p) { return (p... |
6,743,438 | 6,743,494 | Increment IP address | In that program I want to increment IP address. And I see output like that:
125.23.45.67
126.23.45.67
127.23.45.67
128.23.45.67
129.23.45.67
130.23.45.67
131.23.45.67
132.23.45.67
133.23.45.67
134.23.45.67
But I want to see output like this:
124.23.45.67
124.23.45.68
124.23.45.68
124.23.45.70
124.23.45.71
124.23.45.... | Big endian and little endian gets another one! Use htonl and ntohl to convert back and forth.
for (i=0;i<10;i++)
{
adr1.s_addr = htonl(ntohl(adr1.s_addr) + 1);
cout << inet_ntoa(adr1) << endl;
}
|
6,743,970 | 6,744,537 | QT Menu how to create a new window? | I am working in QT Creator.
I would like to mention that I am beginner in this software. I succeeded to create a menu that has: Edit and Open. I would like to create a new window when " Open " from menu bar is clicked. Till now I succeeded to print a message in QMessageBox when I press Open. What is the code for linki... | Most of the question is already answered by this previous question. It leaves one part open, namely how that slot is called.
Well, you answered that: the menu entry "Open" is a QAction. You can connect that action to the slot which you just created.
|
6,744,176 | 6,744,215 | How do I extract string from pattern to pattern? | I am trying to extract a string between two patterns from another string in C++.
Example of input: "C++ is not that easy"
Pattern1: "C++"
Pattern2: "that"
Result: " is not "
I would like to loop this operation to extract all matching strings from binary file later.
| The best way for this is to use regular expressions.
You can read more about it here
|
6,744,453 | 6,744,923 | How to track down a SIGFPE/Arithmetic exception | I have a C++ application cross-compiled for Linux running on an ARM CortexA9 processor which is crashing with a SIGFPE/Arithmetic exception. Initially I thought that it's because of some optimizations introduced by the -O3 flag of gcc but then I built it in debug mode and it still crashes.
I debugged the application w... | My first suggestion would be to open a memory window looking at the region around your stack pointer, and go digging through it to see if you can find uncorrupted stack frames nearby that might give you a clue as to where the crash was. Usually stack-trashes only burn a couple of the stack frames, so if you look upward... |
6,744,540 | 6,744,822 | How to optimize a simple numeric type wrapper class in C++? | I am trying to implement a fixed-point class in C++, but I face problems with performance. I have reduced the problem to a simple wrapper of the float type and it is still slow. My question is - why is the compiler unable optimize it fully?
The 'float' version is 50% faster than 'Float'. Why?!
(I use Visual C++ 2008, a... | IMO, It has to do with optimization flags. I checked your program in g++ linux-64 machine. Without any optimization, it give the same result as you told which 50% less.
With keeping the maximum optimization turned ON (i.e. -O4). Both versions are same. Turn on the optimization and check.
|
6,744,745 | 6,745,175 | Using ETAGS/CTAGS in emacs with C++ Project | Im using emacs and etags to navigate my way round a project, is it possible to get to a header file easily by searching for a function. I have been using VisualStudio and I can view it by clicking goto declaration is there a similar way using etags in emacs?
e.g.
ArchiveDialog::onKeyPress()
search for the declaration... | Semantic from CEDET should provide corresponding functionality... Please, look onto this section and into "Semantic User's Guide" for more details...
|
6,744,950 | 6,745,068 | C++: Any reason why function returning pointer shouldn't be const? | I wanted to know whether there's any reason a function returning a pointer shouldn't be const. I'm working on some code that seems to be const-correct in most places, but for some reason doesn't declare functions returning pointers as const. For example, it writes
virtual Joint* getJointByID(unsigned int id);
instea... | This actually makes sense. If the function was to be declared with const it means it could be used on a constant instance (constvar.getJointByID...). But if it returns a pointer to an internal structure that could then be modified, it will allow the user to bypass the instance's const limit.
When not declared with cons... |
6,745,044 | 6,763,572 | Multithreaded Logging Help | I am working on a multithreaded logging for my engine. But I ma having troubles making it MT. The problem is, even if I am deep copying my logger object into a local variable I am going to have problems with the files. Because two threads are going to write to the same file at the same time which will build a mess. Her... | once I've written this article about minimalist logger. it's a single header file simple logger that can be used in MT environment. it satisfied my logging needs in lots of projects
If you want to use your logger, you can just check the approach
in short: it just locks access to the file by boost::mutex
|
6,745,282 | 6,745,378 | To big endian or to little endian? | let's say that we ignore the target and source hardware for a moment. So, what's the better endian style to go with -- big or small?
I'm just trying to go with consensus / convention on this one. The best guidance I've received so far is "it depends" so always specify. That's fine. I'll do that.
However, in this ... | Actually the answer is it depends
If you just want a choice then Since in Big Endian high order byte comes first ,you can always check positive or negative from the first byte.
|
6,745,480 | 6,745,610 | Sequential new & delete | In continuation to my previous question, I would like to ask the following :
Given a C++ function having a new statement in it but not returning anything explicitly (i.e. with a return statement), should it also always have a delete?
If no, could you please give me an example.
| It doesn't have to explicitly return the newly-created object, but it should pass it to something else in some way. Possible scenarios include:
In a member function, create an object and assign it to a field of the containing object.
Example:
class Foo {
private:
Baz* baz;
public:
Foo() : baz... |
6,745,547 | 6,745,773 | Why disable incremental linking in debug? | In MS Visual C++ 2008 is there any reason to disable incremental linking in debug builds?
From my limited reading enabling incremental builds gives me faster linking and edit & continue.
I'm at a loss to find any reason why you'd disable this great feature. What are disadvantages? Is it flakey?
EDIT:
I'm working with a... | Where does the question come from? You just saw the option and decided to ask?
Generally it should work pretty well, and unless it doesn't - no reason to disable it. But sometimes the dependencies don't work properly and you need to rebuild all manually. If this happens often in your project - then you should disable i... |
6,745,855 | 6,745,983 | Why do compilers give a warning about returning a reference to a local stack variable if it is undefined behaviour? | The C++ standard states that returning reference to a local variable (on the stack) is undefined behaviour, so why do many (if not all) of the current compilers only give a warning for doing so?
struct A{
};
A& foo()
{
A a;
return a; //gcc and VS2008 both give this a warning, but not a compiler error
}
Would ... | It is almost impossible to verify from a compiler point of view whether you are returning a reference to a temporary. If the standard dictated that to be diagnosed as an error, writing a compiler would be almost impossible. Consider:
bool not_so_random() { return true; }
int& foo( int x ) {
static int s = 10;
int... |
6,745,968 | 6,746,141 | Linker problems in Visual Studio 2010 | Alright, so this is getting very very annoying. I have an unmanaged VC 2010 ++ solution with 9 projects in it, from which two of them are projects that output static libraries for remaining 7 test projects to use. In 6 of those 7 I don't get a single linker error, while in the 7th that is configured exactly the same li... | Hard to guess. But I see a source file named "cppwrapper". Which makes it likely that you are wrapping something that's written in C. Which makes it likely that you have to tell the compiler explicitly that this is C code and not C++ code. Like this:
extern "C" {
#include "foo.h"
}
|
6,746,010 | 6,746,315 | Convert decimal (SQL) to double C++ | I have a SQL query which return records with only one column of type decimal (18,18).
In the C++ code I need to convert each value to double to add it to an array.
What's the best way of doing it?
Thank you
| I would suggest converting it to a Real before taking it from the database they are roughly the same datatype. http://msdn.microsoft.com/en-us/library/ms173773.aspx
|
6,746,285 | 6,746,307 | How cast from char* to T*? |
Possible Duplicate:
C++ When should we prefer to use a two chained static_cast over reinterpret_cast
Which is better?
static_cast<T *>(static_cast<void *>(buffer));
or
reinterpret_cast<T *>(buffer);
Where buffer is char * (memory chunk which contains values of type T).
| The chain of two static_casts is better - it is less implementation dependent.
|
6,746,294 | 6,746,349 | QTCreator how to enable password filled option when using Line edit? | I am new to QT Creator. I have a form that has a line edit and a push button. The line edit has the role to fill in a password. Can anyone please tell me how to enable the property for password to the line edit i have? I would like to see some circles instead of a word when filling in the password.
I am working in c++ ... | You have to set the echoMode to Password
|
6,746,412 | 6,746,431 | c++ private member declared in header vs static variable declared in cpp file | i have a variable that i prefer to declare in a cpp file instead of the header file. It should be accessible to objects of that class only. This variable should have a separate copy for every object of that class. Inheritance is not necessary.
Normally, I'd just declare it in the class definition.
A.h:
class A {
... | No, if you take the second approach, you're making it a static variable, which means you won't have a different copy for each object of that class (they'll all share that variable).
Either way, if it should only be accessed by that class, it should go in the class declaration, and should not be a global variable. By m... |
6,746,538 | 6,746,782 | How do I replace data of some range of std::vector | std::vector<char> v;
v.push_back('a');
v.push_back('b');
v.push_back('c');
v.push_back('d');
v.push_back('e');
v.push_back('f');
char c[3] = { 'z', 'x', 'y' };
// Want to make abzxyf
//v.insert(v.begin() + 2, c, c + 3); // it doesn't work as I wanted.
// Yes it works. but if c is more bigger, it will be crash.
std::... | If the sizeof(c) is bigger, resize() before the copy() that should do the trick.
e.g.
if (sizeof(c) + 2 > v.size())
v.resize(sizeof(c) + 2);
// now copy
std::copy(c, c + sizeof(c), v.begin() + 2);
|
6,746,778 | 6,746,907 | Why i am getting error while executing with the following code? | Technique 1 -> Results in error
I have three files MyType.h, MyType.cpp & main.cpp
MyType.h
#ifndef MYTYPE_H
#define MYTYPE_H
#include<iostream>
using namespace std;
template <class T,int iMax>
class A{
T iData;
public:
void vSetData(T iPar1);
void vDisplayData();
};
#endif
MyType.cpp
#include"MyType.h"... | Each method definition needs the full class name decoration above it:
template <typename T>
void A<T>::vSetData(T iPar1){
if(iPar1 <= iMax)
iData = iPar1;
}
template <typename T>
void A<T>::vDisplayData(){
cout<<"\nData is: "<<iData<<endl;
}
When you do this however you'll get other compile errors, fo... |
6,746,838 | 6,746,912 | Simple C++ code to generate Armstrong numbers | The following is my simple attempt at generating Armstrong numbers. But it only outputs "1". What might be wrong?
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
int main()
{
clrscr();
int r;
long int num = 0, i, sum = 0, temp;
cout << "Enter the maximum limit to generate Armstrong numb... | You need to always set sum = 0 inside the for-i-loop.
|
6,747,089 | 6,747,136 | Programmatically getting the name of a derived class | I am attempting to do something like:
class Base {
public:
Base() {
cout << typeid(*this).name() << endl;
}
...
};
class Derived : public Base { ... }
class MoreDerived : public Derived { ... }
Derived d;
MoreDerived m;
Problem is, I always get Base printed to the screen, when I need to see Derived an... | In the constructor Base(), the object is still a "Base" instance. It will become a Derived instance after the Base() constructor. Try to do it after the construction and it will work.
See for example :
Avoiding virtual methods in constructor
Never Call Virtual Functions during Construction or Destruction
|
6,747,165 | 6,747,239 | Integrating a C# app with an existing website | I have some backend functionality which need to be written in C# (for political, not technical reasons).
The C# 'module' is to provide functionality for a website, which is written in PHP.
The hosting environment for the completed solution will be as follows:
Operating system: Linux
Web server: Apache
Backend db: myS... |
Yes. My guess is you would want it to be an executable communicating with WCF or a Web Service hosted with IIS communicating with WCF.
Depending on your requirements, I would investigate the HTTP Long Polling technique.
C# can use PInvoke through DllImport to use any available C++ library calls.
|
6,747,296 | 6,749,116 | QT Creator Main window - how to change the interface for each element from the menu? | I am new to QT Creator. I did create a menu: Login || Open. When login is clicked I would like to see a line edit and a press button. When Open is clicked I would like to see a picture in the window. Can I change the interface of the same window depending on what I click in the menu bar? How can I do that?
| I did something similar to this - an app with several major areas, toggled by an icon bar at the top.
I used a QStackWidget to stack the different application areas on top of each other, a set of QActions that I created using the designer, and a QActionGroup to implement the toggling.
When the actions are marked as "ch... |
6,747,400 | 6,747,898 | Can auto using parens mean a function prototype? | This question arose from being unable to use uniform-initialisation syntax with the auto keyword because it treats it as a std::initializer_list<T> (explanation in the comments here).
Take the following code example:
class X { };
int x( X() ); // function prototype (1)
auto x( X() ); // copy/move construction of an X,... | I get
error: 'x' function uses 'auto' type specifier without late return type
The compiler is expecting something like
auto x( X() ) -> int;
which would be equivalent to line 2.
|
6,747,507 | 6,747,670 | Very Quick Globals.h Question (with it included, some of the items still come up undefined) | using globals.h im hoping to store a vector of rectangles and also a collision box and a few global bools
globals.h
extern SDL_Rect winRect;
extern std::vector<SDL_Rect> platform;
extern bool paused;
extern bool exit;
i can set the bool to false as so in the globals.cpp.
bool paused = false;
bool exit = false;
howe... | You need to define winRect and platform in globals.cpp:
SDL_Rect winRect;
std::vector<SDL_Rect> platform;
bool paused = false;
bool exit = false;
Extern only tells the compiler that the variable and/or the function is defined in another place and if you do not define it, the linker will give you an error because it ... |
6,747,874 | 6,748,805 | STL Vector, deque or containers equivalent for Android? | Simple question: I know that the STL library is not provided inside the Android NDK. Otherwise, I would like to use containers like vector, deque and so on.
Does anyone know if equivalent objects exist for Android NDK or should I develop mine ?
Thanks!
| You can use STLPort (http://www.stlport.org/), which contains all the STL classes and has been ported to Android. Please have a look at answer of another question at uSTL or STLPort for Android?
|
6,747,959 | 6,748,137 | questions about memory pool | I need some clarifications for the concept & implementation on memory pool.
By memory pool on wiki, it says that
also called fixed-size-blocks allocation, ... ,
as those implementations suffer from fragmentation because of variable
block sizes, it can be impossible to use them in a real time system
due to perf... | In a scenario where you always allocate fixed-size blocks, you either have enough space for one more block, or you don't. If you have, the block fits in the available space, because all free or used spaces are of the same size. Fragmentation is not a problem.
In a scenario with variable-size blocks, you can end up with... |
6,747,968 | 6,761,041 | boost library can not be found | I have compiled boost version 1.47 using MinGW on winXP SP3.
I included the path to the libraries (C:\boost\boost_1_47_0) in a linker variable in my make file. When run "make" in the command prompt window i get the following error message:
"c:/mingw/bin/../lib/gcc/mingw32/4.5.2/../../../../mingw32/bin/ld.exe: cannot f... | I have worked out solution. Probably the problem was mine and note "make". Below is the make file that is now working.
# global variables
CC = g++
SRC = main.cpp
BOOST = C:\boost\boost_1_47_0
BOOSTLIB = C:\boost\boost_1_47_0\stage\lib\libboost_regex-mgw45-1_47.a
# linking
main : main.o
$(CC) main.o $(BOOSTLIB) -o ... |
6,747,987 | 6,748,710 | Writing an iterator that makes several containers look as one | Consider the following simplified example and desired output:
class A
{
class combined_iterator
{
????
}
typedef ??? t_combined_it;
t_combined_it begin();
t_combined_it end();
std::vector<int> m_Vec1, m_Vect2;
}
A a;
a.m_Vec1.push_back(1);
a.m_Vec2.push_back(2);
for (A::t_combined... | boost::join is what you're looking for. You can also study the implementation, especially how to derive the lowest common denominator for container traversal, reference and return value types. To quote:
The intention of the join function is to join two ranges into one longer range.
The resultant range will have the lo... |
6,748,079 | 6,748,945 | reading signals sent between 2 radios, serial comms | I am currently reading from a reciever via the com port on my pc, reading the signals sent between 2 other radios. The problem I am having is how it is displaying to the listbox properly, as it doesnt start at the top, it puts lots of blank lines above the output, forcing me to scroll down to see it, and also that my l... | The Pos > 0 branch in your listing is a dead branch, but this is a problem because your else only gets executed if "TX" is at the very beginning, or not found at all. If ever you read your buffer, and "TX" does not appear, you have a buffer read error, where you start at index -1 of buffer.
Basically, say you have a s... |
6,748,095 | 7,276,382 | CATIA: How to call CATCoPlyExplodeCmd | Is it possible to call from C++ catia command? How can I get any info about signature for this command?
Thanks,
Danil.
| Yes it should be possible from C++ with the CAA API and environment installed:
CATCommand* pCmd = NULL;
hr = ::CATAfrStartCommand("CATCoPlyExplodeCmd", pCmd);
I don't know if that command takes any arguments though.
|
6,748,308 | 7,737,762 | How to initialise std::istringstream from const unsigned char* without cast or copy? | I have binary data in a byte sequence described by const unsigned char *p and size_t len. I want to be able to pass this data to a function that expects a std::istream *.
I think I should be able to do this without copying the data, unsafe casts or writing a new stream class. But so far I'm failing. Can anyone help?... | Your answer is still copying.
Have you considered something like this?
const unsigned char *p;
size_t len;
std::istringstream str;
str.rdbuf()->pubsetbuf(
reinterpret_cast<char*>(const_cast<unsigned char*>(p)), len);
|
6,748,412 | 6,748,739 | Check if boost::asio buffer data is present before read() | I'm trying to port a piece of software I wrote with Unix sockets to a version with TCP sockets, using boost::asio. The program is intended to run on a Linux machine.
In the earlier version of the code (using Unix sockets) I used a simple check to see if there was new data on the socket buffer, and then proceeding with ... | Use bytes_readable, this implements what you want.
Implements the FIONREAD IO control command.
boost::asio::ip::tcp::socket socket(io_service);
...
boost::asio::socket_base::bytes_readable command(true);
socket.io_control(command);
std::size_t bytes_readable = command.get();
|
6,748,569 | 6,748,653 | c++ compiler error "was not declared in this scope" | I'm getting a bizarre compiler error when trying to compile a c++ UDP client program.
g++ -o client Udp.cpp ClientMain.c -I. -lpthread
In file included from ClientMain.c:1:0:
Udp.h: In destructor ‘CUdpMsg::~CUdpMsg()’:
Udp.h:103:43: error: ‘free’ was not declared in this scope
Udp.h: In member function ‘void CUdpMsg::... | If you have multiple files, then you need the appropriate includes in each file. Also maybe its not within namespace?
|
6,748,688 | 6,748,795 | Behaviour of container std::set during Insertion? | While inserting in a set, does the set internally delete some of the objects multiple times? I tried to insert two objects of type MyClass as in following program but to my surprise it calls the destructor of class with initially inserted value 2 times! I am not able to understand any logic behind this. Can anyone give... | The comparator
int
comp(MyClass a, MyClass b)
{
return a.num-b.num;
}
takes its parameters by value. This will create extra copies that are then destroyed.
Passing by reference will work better.
|
6,748,928 | 6,750,656 | Change pure virtual to virtual and stay binary compatible | Can I change a pure-virtual function (in a base class) to become non-pure without running into any binary compatibility issues? (Linux, GCC 4.1)
thanks
| What does it mean to maintain binary compatibility to you?
The object layout will be the same, but you will be breaking the One Definition Rule unless you recompile all code, at which point binary compatibility is basically useless. Without recompiling, then the ODR is broken, and while it might be the case that it wor... |
6,749,269 | 6,749,770 | Overloading the new operator | Is it possible to overload the new operator so that an object isn't created, but instead return an existing object.
If that is possible, how could you create the objects in the first place :D
This sounds weird I know. I'm trying to hide some details from the client. I am making a game on PS2, I'd like to have the New F... | You can overload operator new, but that overloaded operator doesn't return an object. It returns the memory for an object, and the implementation arranges for the constructor to be called.
So you can't do quite what you want.
Instead, if the cost you're trying to avoid is that of memory allocation, then your overload c... |
6,749,297 | 6,749,378 | C preproccessor problem | I have a program to find the reciprocal of a number but the main program is written in C and the reciprocal function is written in c++.Next I have a header file reciprocal.hpp that has some of the conditional compilation code that makes the reciprocal function an extern function.Can someone please explain me what is th... | If you're referring to the ifdefs, they simply allow the function to be exported to C if the header is compiled as C++. The extern line simply defines a function prototype for reciprocal.
|
6,749,345 | 6,750,028 | how to wrap, return and get the object of vector<map<string, string> > in C++ version of xmlrpc-c library? | I am using xmlrpc-c library (http://xmlrpc-c.sourceforge.net) and I am writing both the server and client side code. I know that xmlrpc provides lots of builtin structures like xmlrpc_c::value_struct, but the docs cannot help me figure out how to achieve my object.
In the server I am attempting to return a structure ve... | You'll have to do marshalling on server side and un-marshalling on client side. Also known as serialize and de-serialise.
You are asking us for a lot of code. Try googling for marshalling code samples.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.