question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,666,224 | 1,666,232 | What is the size of void? | What would this statement yield?
void *p = malloc(sizeof(void));
Edit: An extension to the question.
If sizeof(void) yields 1 in GCC compiler, then 1 byte of memory is allocated and the pointer p points to that byte and would p++ be incremented to 0x2346? Suppose p was 0x2345. I am talking about p and not *p.
| The type void has no size; that would be a compilation error. For the same reason you can't do something like:
void n;
EDIT.
To my surprise, doing sizeof(void) actually does compile in GNU C:
$ echo 'int main() { printf("%d", sizeof(void)); }' | gcc -xc -w - && ./a.out
1
However, in C++ it does not:
$ echo 'int main... |
1,666,492 | 1,666,562 | Multiple threads and memory | I read in the Visual C++ documentation that it is safe for multiple threads to read from the same object.
My question is: how does a X86-64 CPU with multiple cores handle this?
Say you have a 1 MB block of memory. Are different threads literally able to read the exact same data at the same time or do cores read one wor... | Not only are different cores allowed to read from the same block of memory, they're allowed to write at the same time too. If it's "safe" or not, that's an entirely different story. You need to implement some sort of a guard in your code (usually done with semaphores or derivates of them) to guard against multiple core... |
1,666,537 | 1,666,713 | Any issues with large numbers of critical sections? | I have a large array of structures, like this:
typedef struct
{
int a;
int b;
int c;
etc...
}
data_type;
data_type data[100000];
I have a bunch of separate threads, each of which will want to make alterations to elements within data[]. I need to make sure that no to threads attempt to access the same ... | With this many objects, most of their critical sections will be unlocked, and there will be almost no contention. As you already know (other comment), critical sections don't require a kernel-mode transition if they're unowned. That makes critical sections efficient for this situation.
The only other consideration woul... |
1,666,580 | 1,666,617 | What does the colon mean in struct declarations in C? | Reading the code of TeXmacs, I saw this:
struct texmacs_input_rep : concrete_struct {
...
};
What does that mean?
This syntax is defined in the C standard, p113, but I didn't find the meaning of it, but that's because I don't know how to read grammar rules.
Because concrete_struct is another struct, that contains func... | It is C++ syntax and equivalent to this:
class texmacs_input_rep : public concrete_struct {
public:
...
};
This is the normal syntax for inheritance of classes, here texmacs_input_rep is inherited from concrete_struct.
About that syntax in C:
The C-Standard you linked to defines (6.7.2.1):
struct-or-union-specifier:
... |
1,666,581 | 1,666,610 | How to use extended precision cmath functions by preference | My question is this: is there a way to always use the extended precision versions of mathematical functions - such as sqrt, exp, &c - without using an explicit cast when providing a single or double precision argument?
For example I want this functionality, without the hassle of the casting:
float x=15.0;
float answer... | In C
If you #include <math.h>, which declares such function as returning a double and accepting double arguments, the compiler will do the cast for you implicitily.
#include <math.h>
/* ... */
int x = sqrtl(sqrt(sqrtf(42)));
/* 1 ^^ implicit cast of int to float */
/* 2 ^... |
1,666,662 | 1,667,219 | Call a JavaScript function from C++ | I have a CDHTMLDialog, with which I have 2 HTML pages and a .js file with a few fairly simple functions.
I would like to be able to call one of the JS functions from my program with a simple data type passed with it. e.g. MyFunc(int). Nothing needs to be returned.
I would appreciate any guidance on how I go about thi... | Easiest approach would be to use the execScript() method in the IHTMLWindow2 interface.
So you could get the IHTMLDocument2 interface from your CDHTMLDialog by calling GetDHtmlDocument, then get the parentWindow from IHTMLDocument2. The parent window will have the IHTMLWindow2 interface that supports execScript().
The... |
1,666,802 | 1,666,811 | Is there a __CLASS__ macro in C++? | Is there a __CLASS__ macro in C++ which gives the class name similar to __FUNCTION__ macro which gives the function name
| The closest thing there's is to call typeid(your_class).name() - but this produces compiler specific mangled name.
To use it inside class just typeid(*this).name()
|
1,666,927 | 1,667,040 | CWnd::CreateDlgIndirect leaves m_hWnd==NULL | A dialog I'm working on isn't displaying, using:
CWnd::CreateDlgIndirect(LPCDLGTEMPLATE lpDialogTemplate,CWnd* pParentWnd, HINSTANCE hInst)
The call to CreateDlgIndirect is in a lon-used base-class, which effectively takes the IDD of the dialog template in the resource file - it works fine for many other dialogs but I... | One of the more obscure ways for CreateDialogXXX to fail is for a child control on the dialog to fail creation. Usually because the application has not initialized the common controls library before attempting to effect the dialog creation. See InitCommonControlsEx
One way to check this is to open the dialog in the res... |
1,666,963 | 1,667,084 | debugging templates with GDB | My gdb is GNU gdb Red Hat Linux (6.3.0.0-1.162.el4rh) and I can't debug templates. How can I debug templates with this debugger?
| if your problem is just about placing breakpoint in your code. Here is a little snippet
ex: main.cpp
#include <iostream>
template <typename T>
void coin(T v)
{
std::cout << v << std::endl;
}
template<typename T>
class Foo
{
public:
T bar(T c)
{
return c * 2;
}
};
int main(int argc, char** ar... |
1,667,049 | 1,667,070 | C++ array list or vector? | I'm trying to rewrite code I've written in matlab in C++ instead.
I have a long cell in matlab containing 256 terms where every term is a 2x2 matrix. In matlab i wrote it like this.
xA = cell(1,256);
xA{1}=[0 0;3 1];
xA{2}=[0 0;13 1];
xA{3}=[0 0;3 2];
and so on...
What would be the easiest thing to use in c++?
Can I... | You can certainly initialize them all at once, although it sounds like a lot of tedious typing:
float terms[256][4] = {
{ 0, 0, 3, 1 },
{ 0, 0, 13, 1 },
{ 0, 0, 3, 2}
...
};
I simplified it down to an array of 256 4-element arrays, for simplicity. If you wanted to really express the intended nesting, which of cou... |
1,667,386 | 1,669,404 | UBLAS Matrix Finding Surrounding Values of a Cell? | I am looking for an elegant way to implement this. Basically i have a m x n matrix. Where each cell represents the pixel value, and the rows and columns represent the pixel rows and pixel columns of the image.
Since i basically mapped points from a HDF file, along with their corresponding pixel values. We basically ha... | There's a well-known optimization to this filtering problem.
Integrate the cells in one direction (say horizontally)
Integrate the cells in the other direction (say vertically)
Take the difference between each cell and it's N'th neighbor to the left.
Take the difference between each cell and it's N'th lower neighbor
... |
1,667,420 | 1,667,477 | How can I tell reliably if a boost thread has exited its run method? | I assumed joinable would indicate this, however, it does not seem to be the case.
In a worker class, I was trying to indicate that it was still processing through a predicate:
bool isRunning(){return thread_->joinable();}
Wouldn't a thread that has exited not be joinable? What am I missing... what is the meaning of b... | Since you can join a thread even after it has terminated, joinable() will still return true until you call join() or detach(). If you want to know if a thread is still running, you should be able to call timed_join with a wait time of 0. Note that this can result in a race condition since the thread may terminate right... |
1,667,591 | 4,140,600 | Rotating a bitmap 90 degrees | I have a one 64-bit integer, which I need to rotate 90 degrees in 8 x 8 area (preferably with straight bit-manipulation). I cannot figure out any handy algorithm for that. For instance, this:
// 0xD000000000000000 = 1101000000000000000000000000000000000000000000000000000000000000
1 1 0 1 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 ... |
v = (v & 0x000000000f0f0f0fUL) << 004 | (v & 0x00000000f0f0f0f0UL) << 040 |
(v & 0xf0f0f0f000000000UL) >> 004 | (v & 0x0f0f0f0f00000000UL) >> 040;
v = (v & 0x0000333300003333UL) << 002 | (v & 0x0000cccc0000ccccUL) << 020 |
(v & 0xcccc0000cccc0000UL) >> 002 | (v & 0x3333000033330000UL) >> 020;
v = (v & 0x00550... |
1,667,625 | 1,667,738 | c++ vector random shuffle part of it | Whats the best way to shuffle a certain percentage of elements in a vector.
Say I want 10% or 90% of the vector shuffled.
Not necessarily the first 10% but just 10% across the board.
TIA
| Modify a Fisher-Yates shuffle to do nothing on 10% of the indices in the array.
This is java code that I'm posting (from Wikipedia) and modifying, but I think you can make the translation to C++, because this is more of an algorithms problem than a language problem.
public static void shuffleNinetyPercent(int[] array)... |
1,667,963 | 1,668,004 | How portable is casting -1 to an unsigned type? | The other day, I came across this construct:
static_cast<size_type>(-1)
in some example C++ code, which is likely (depending on the details of where size_type is from) to be equivalent to the following C:
(size_t)(-1)
As I understand it, it works based on the fact that the representation of -1 in twos complement arit... | The requirements on unsigned arithmetic guarantee that casting -1 to an unsigned type will produce the largest number possible for the target type. C99, §6.2.5/9: "...a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that c... |
1,667,999 | 1,668,026 | What is the most painless approach to insert an element in the middle of the std::vector | I want to be able to insert an element in the middle (or another location) in the vector without overwriting existing element.
Say my vector has 3 6 9 10 and I want to insert 7 right after 6. How should it be done without causing issues? It's very infrequent operation so efficiency is not a problem here. Also, at thi... | There is vector::insert for this operation.
iterator insert(
iterator _Where,
const Type& _Val
);
void insert(
iterator _Where,
size_type _Count,
const Type& _Val
);
|
1,668,023 | 1,668,734 | Producing the fastest possible executable | I have a very large program which I have been compiling under visual studio (v6 then migrated to 2008). I need the executable to run as fast as possible. The program spends most of its time processing integers of various sizes and does very little IO.
Obviously I will select maximum optimization, but it seems that ther... | 1) Reduce aliasing by using __restrict.
2) Help the compiler in common subexpression elimination / dead code elimination by using __pure.
3) An introduction to SSE/SIMD can be found here and here. The internet isn't exactly overflowing with articles about the topic, but there's enough. For a reference list of intrinsic... |
1,668,088 | 1,668,111 | Advance iterator for the std::vector std::advance VS operator +? | I found myself writing the following a lot:
int location =2;
vector<int> vec;
vector<int>::iterator it=vec.begin();
/..../
std::advance(it, location);
instead of
it= it + 5;
what is the Preferred/Recommended way ?
| Adding will only work with random access iterators. std::advance will work with all sorts of iterators. As long as you're only dealing with iterators into vectors, it makes no real difference, but std::advance keeps your code more generic (e.g. you could substitute a list for the vector, and that part would still work)... |
1,668,259 | 1,668,549 | STL or Qt containers? | What are the pros and cons of using Qt containers (QMap, QVector, etc.) over their STL equivalent?
I can see one reason to prefer Qt:
Qt containers can be passed along to other parts of Qt. For example, they can be used to populate a QVariant and then a QSettings (with some limitation though, only QList and QMap/QHash... | I started by using std::(w)string and the STL containers exclusively and converting to/from the Qt equivalents, but I have already switched to QString and I find that I'm using Qt's containers more and more.
When it comes to strings, QString offers much more complete functionality compared to std::basic_string and it i... |
1,668,655 | 1,668,675 | String Undeclared In C++ | I'm sure this is a really simple thing, but I haven't worked in C++ forever.
14 C:\Dev-Cpp\mainCurl.cpp `string'
undeclared (first use this function)
> #include <stdio.h>
> #include <curl/curl.h>
> #include <string>
> #include <iostream>
>
> int main(void) {
> string url("http://www.google.com"); //
> ... | You haven't declared your namespace. You need to either declare:
using namespace std;
Or tell the compiler that "string" is in the standard namespace:
std::string url("...");
Or you can announce that you are specifically using std::string and only std::string from std by saying:
using std::string;
|
1,669,017 | 1,670,008 | How to create a MFC dialog with a progress bar in a separate thread? | My application may take a while to connect to a database. This connection is made with a single library function call, i.e. I cannot put progress updates in there and make callbacks or something similar.
My idea was to create a dialog with a progress bar in a separate thread before connecting to the DB. This dialog w... | It would still be safer to move the DB connection logic to the separate thread. With DB on the dialog thread, you will be able to repaint the progress bar but not other controls in the dialog.
|
1,669,204 | 1,669,258 | Need a vector that derives from a vector | Consider this simple code:
class A {
};
class V1: vector<A *>{
// my nice functions
};
if I have a instance of V1, then any object derived from A can be inserted into the vector, ok here.
Now, lets say I have two simple classes called B and C both derives from A;
if I have a instance of V1, then both pointers of ... | It's not clear from your example if inheritance is needed. You may also not realize it is dangerous, because std::vector does not have a virtual destructor. That means V1's destructor will not be called upon deletion of a pointer to the base class and you may end up leaking memory/resources. See here for more info.
cla... |
1,669,390 | 1,669,434 | Comparing variables in two instances of a class | i have what i hope is a quick question about some code i am building out.. basically i want to compare the variables amongst two instances of a class (goldfish) to see if one is inside the territory of another. they both have territory clases which in turn use a point clase made up of an x and y data-point.
now i was c... | What do you mean by "doesnt work"? I does not compile?
If contain_check is written as shown in your post, a problem is that you are using the arrow operator on non-pointers. Use dot instead:
if ((a.x_ne <= b.x_ne && a.y_ne <= b.ne) //etc.
|
1,669,448 | 1,669,467 | Unknown meta-character in C/C++ string literal? | I created a new project with the following code segment:
char* strange = "(Strange??)";
cout << strange << endl;
resulting in the following output:
(Strange]
Thus translating '??)' -> ']'
Debugging it shows that my char* string literal is actually that value and it's not a stream translation. This is obviously not a... | What you're seeing is called a trigraph.
In written language by grown-ups, one question mark is sufficient for any situation. Don't use more than one at a time and you'll never see this again.
GCC ignores trigraphs by default because hardly anyone uses them intentionally. Enable them with the -trigraph option, or tell ... |
1,669,501 | 1,669,565 | code for subtracting 1 from a digit stored in an array using c | can any one help me with code that subtract 1 from a digit stored in an array using c++ (elementary mathematics)
eg..
100-1=99
and
98-1=97
| If you have stored the digits in an array, you'll need to follow your elementary-school math on the array from right to left. "Borrow" from the next place to the left as needed.
|
1,669,514 | 1,669,550 | Should I inherit from std::exception? | I've seen at least one reliable source (a C++ class I took) recommend that application-specific exception classes in C++ should inherit from std::exception. I'm not clear on the benefits of this approach.
In C# the reasons for inheriting from ApplicationException are clear: you get a handful of useful methods, properti... | The main benefit is that code using your classes doesn't have to know exact type of what you throw at it, but can just catch the std::exception.
Edit: as Martin and others noted, you actually want to derive from one of the sub-classes of std::exception declared in <stdexcept> header.
|
1,669,788 | 1,670,045 | How do I make tab control take over entire window in Qt Creator? | I want a tab control to "dock" to the entire window panel, in Qt Creator. Now in Winforms and WPF this is super easy but in Qt its not working.
I've tried all the layouts, grid layouts, etc etc. it's just shrinking the tabs not making them grow to fill. So please test a solution before telling me what the SHOULD BE O... | I'm unsure what you are trying to achieve here - do you want the control to fill the client area? Are you creating a QMainWindow-derived class or a QDialog-derived one? If using QMainWindow then you'd make the tab control the central widget by calling setCentralWidget. The tab control will then fill the main window'... |
1,670,226 | 1,670,375 | How do I stop automake from adding -I. to my compile line? | How do I stop automake from adding -I. to my compile line?
It seems automake or libtool objects always have a compile command similar to:
g++ -DHAVE_CONFIG_H -I. -I./proj/otherdir -o myprog.o myprog.c
The problem is that I have two header files with the same name....
./proj/otherdir/Header.h
./proj/thisdir/Header.h
E... | all you have to do is set in the Makefile.am
DEFAULT_INCLUDES =
and then all is good in the world.
Chenz
|
1,670,276 | 1,675,291 | Tutorials for creating an ActiveX Control in Code::Blocks | I need to write an ActiveX control and have never written one before.
I'd appreciate being pointed to some useful tutorials.
I'm also wanting to implement it under Code::Blocks. Has anyone done this before? how easy is it?
Note: I've found a number of tutorials, but they are either for visual basic, or visual c++ ba... | VLC has an ActiveX control made without the use of Visual C++ libraries. You can have a look at the git repository here
|
1,670,891 | 1,670,907 | How can I print a string to the console at specific coordinates in C++? | I'm trying to print characters in the console at specified coordinates. Up to now I have been using the very ugly printf("\033[%d;%dH%s\n", 2, 2, "str"); But I just had to ask whether C++ had any other way of doing this. The problem is not even that it's ugly, the problem comes up when I try to make myself a prettier f... | What you are doing is using some very terminal specific magic characters in an otherwise pure C++ application. While this works, you will probably have a far easier time using a library which abstracts you from having to deal with terminal specific implementation details and provides functions that do what you need.
In... |
1,671,062 | 1,704,439 | No thumbnails showing in Aero flip/thumbnail for full screen direct3d 9 application | I'm sure this is on the web somewhere, but I'm having trouble with the search terms (getting lots of non-relevant stuff.) Anyway, I've got a Direct3D9 application. When it runs in full screen, on Vista and Windows 7, and you hit Alt-Tab or Win-Tab, my application just shows up blank in the thumbnail/preview/live view (... | When running a full-screen Direct3D application window compositing (of which the thumbnails are a part) is disabled. This is typically a good thing, since it can increase performance of the full-screen app. As a default this behavior is reasonable since most full-screen apps (especially those developed against XP or ea... |
1,671,297 | 1,674,359 | How do I invoke a non-default constructor for each inherited type from a type list? | I'm using a boost typelist to implement the policy pattern in the following manner.
using namespace boost::mpl;
template <typename PolicyTypeList = boost::mpl::vector<> >
class Host : public inherit_linearly<PolicyTypeList, inherit<_1, _2> >::type
{
public:
Host() : m_expensiveType(/* ... */) { }
private:
con... | I could not resist the temptation to see how it could be done with inherit_linearly.
Turns out to be not that bad, IMHO:
template<class Base, class Self>
struct PolicyWrapper : Base, Self
{
PolicyWrapper(const ExpensiveType& E)
: Base(E), Self(E)
{}
};
struct EmptyWrapper
{
EmptyWrapper(const Expen... |
1,671,469 | 1,671,581 | Confusing Valgrind output: indirectly lost blocks but no errors? | I'm running valgrind 3.5.0 to try and squash memory leaks in my program.
I invoke it as so:
valgrind --tool=memcheck --leak-check=yes --show-reachable=yes
After my program finishes valgrind reports that
==22926==
==22926== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 17 from 1)
==22926== malloc/free: in use ... | The commenters to the OP were spot on; The Solution object being created in the constructor was never being deleted. I've fixed the egregious oversight and gotten rid of the ugly code creating new objects outside of the constructor of the object which is responsible for them.
Thank you Artelius, Nikolai and Jonathan!
|
1,671,533 | 1,671,577 | How to integrate an external process which is invoked repeatedly into a Java webapp? | I am trying to integrate a non-Java executable into a Java webapp on the server-side (Linux).
Some details about the executable:
Written in C++. The executable takes some input either from stdin or file and generates an output file. The executable is not designed to be a long running process i.e it generates an output... | if you:
a) Can modify the source code.
I would recommend you yo create a long running process and expose it as a webservice. This way the process will only be sitting there waiting to be invoked.
b) Have the source code/headers but you can't modify it.
Probably a good idea would be to integrate it as library and inv... |
1,671,586 | 1,671,703 | How to create a Boost.Asio socket from a native socket? | I am merely trying to create a boost ip::tcp::socket from an existing native socket. In the assign function, the first parameter must be a "protocol_type" and the second must be a "native_type", but it never explains what these are or gives an example of its use.
I'm guessing the second should be the socket descriptor,... | "Native type" is just the socket handle, in this case the int stored in "socket".
"Protocol type" is the the protocol. For a TCP over standard IP using stream socket, this would be the return value from boost::asio::ip::tcp::v4(). Substitute as appropriate for datagram sockets, IPv6, etc.
So:
s.assign(boost::asio::ip... |
1,671,641 | 1,672,723 | Qt: New student to Qt questions | I've got a class I've written, and I'm trying to connect it to Qt. I've got some "best practices" questions I hope you all can help me with.
When creating a mainWindow to contain data, I inherit the header file into my custom class specified above, so I can make use of the elements created within Qt Creator. Is this... |
When creating a mainWindow to contain data, I inherit the header file into my custom class specified above, so I can make use of the elements created within Qt Creator. Is this the proper way of doing things?
I assume that you mean "include the header file": when creating a widget with an associated .ui you should in... |
1,671,682 | 1,672,355 | The reading list for scientific programmer | I am working to become a scientific programmer. I have enough background in Math and Stat but rather lacking on programming background. I found it very hard to learn how to use a language for scientific programming because most of the reference for SP are close to trivial.
My work involves statistical/financial model... | At some stage you're going to need floating point arithmetic. It's hard to do it well, less hard to do it competently, and easy to do it badly. This paper is a must read:
What Every Computer Scientist Should Know About Floating-Point Arithmetic
|
1,671,728 | 1,671,731 | C++ : cannot convert from 'char *' to 'char []' problem | im not a c/c+ programmer ( i do know delphi), anyway im trying to compile a program written in c++, i'v changed it to accept some arguments( a path to a file, which is hardcoded in the original code) from command line,
the orignial line was
char Filepath[50] = "F:\\mylib\\*.mp3";
and i changed it to
char Filepath[... | Use:
char *Filepath = argv[1];
There's no need to allocate space for 50 characters when argv[1] already contains the string you want. Also, you don't have to decide what will be the maximum number of characters in the command line argument; that space is already allocated for you.
Note, however, that the above will no... |
1,671,986 | 1,672,082 | Which is faster, writing raw data to a drive, or writing to a file? | I need to write data into drive. I have two options:
write raw sectors.(_write(handle, pBuffer, size);)
write into a file (fwrite(pBuffer, size, count, pFile);)
Which way is faster?
I expected the raw sector writing function, _write, to be more efficient. However, my test result failed! fwrite is faster. _write costs... | In the _write() case, the value of SSD_SECTOR_SIZE matters. In the fwrite case, the size of each write will actually be BUFSIZ. To get a better comparison, make sure the underlying buffer sizes are the same.
However, this is probably only part of the difference.
In the fwrite case, you are measuring how fast you can g... |
1,672,172 | 1,672,300 | Cannot set OdbcConnection to OdbcCommand.Connection | On the class level, I have created reference:
System::Data::Odbc::OdbcConnection Connection;
in some method I want to set it to odbcCommand.Connection like this:
::System::Data::Odbc::OdbcCommand Command;
Command.Connection=this->Connection;
It reports "cannot convert parameter 1 from 'System::Data::Odbc::OdbcConnectio... | Command.Connection wants a handle (^) to a System::Data::Common::DbConnection
public:
property OdbcConnection^ Connection {
OdbcConnection^ get ();
void set (OdbcConnection^ value);
}
Instead try to do this:
System::Data::Odbc::OdbcCommand Command;
Command.Connection = %Connection;
The unary % operator (Trac... |
1,672,419 | 1,672,896 | Reading float value from string upto 6 precision | i have to read a flot value from string up to 6 precision , Current code is reading first 6 digits only. Thanks in Advance
template <class T>
bool from_string(T& t, const std::string& s,
std::ios_base& (*f)(std::ios_base&))
{
std::istringstream iss(s);
return !(iss >> f >> t).fail();
}
int ma... | I'm quite certain it's reading all digits. The problem appears to be in what you expect. Let's put it a bit stronger: What would you expect to happen if you read 1456.90900000000000000000000000000 in a float?
|
1,672,550 | 1,672,654 | How to implement server-sided applications that can process user's inputs? | There are some web-based services such as converting .flv files into .mp3 files, .doc files into .pdf files, etc. These are the servers that take files from the user and apply respected applications (such as conversion). After that, the converted file may be available to the requested user.
I understand a little bit ab... | Well for PDFs this can be done using entirely PHP. See http://www.php.net/manual/en/book.pdf.php for the PDF functions and http://uk.php.net/manual/en/pdf.examples-basic.php for some examples of usage.
|
1,672,561 | 1,672,613 | Getting a file path relative to a particular directory | Is there a nice way in the WinAPI to get a path relative to another path? For example:
Have a list of paths relative to:
a\b\c\d
And I'd like to change them all to paths relative to
a\b\c
Is there a neat way to do this or should I get path parsing?
| As far as i know there is no such functionality in the windows API, but there is e.g. an article on CodeGuru that provides that functionality.
edit:
I stand corrected, there is PathRelativePathTo() in the shell api as mentioned in this answer.
|
1,672,677 | 1,672,698 | Print a GUID variable | I have a GUID variable and I want to write inside a text file its value.
GUID definition is:
typedef struct _GUID { // size is 16
DWORD Data1;
WORD Data2;
WORD Data3;
BYTE Data4[8];
} GUID;
But I want to write its value like:
CA04046D-0000-0000-0000-504944564944
I observed that:
Data1... | Use the StringFromCLSID function to convert it to a string
e.g.:
GUID guid;
CoCreateGuid(&guid);
OLECHAR* guidString;
StringFromCLSID(guid, &guidString);
// use guidString...
// ensure memory is freed
::CoTaskMemFree(guidString);
Also see the MSDN definition of a GUID for a description of data4, which is an array c... |
1,672,730 | 1,672,738 | How to get the value of a value passed by reference in C++ | I have a function with the following declaration:
void cleanValid(int valid[][4], int &size, int index);
In implementation of this function I need to set another counter equal to the integer size passed by reference. I tried doing something like:
int count;
count = size;
If I'm not mistaken, when I change the value o... | No, you've got it wrong. When you read from the reference into a non-reference variable, you're not setting up any kind of linkage between the two. You will have an independent copy of the value of size at that time, nothing else.
If you wanted to affect the value of size, you would have to use a reference to it:
int& ... |
1,673,183 | 1,673,234 | C++ Unicode Encryption Library Required (Or is it?) | I need to encryption several pieces of text in a file along side unencrypted text in the same file. All the data is Unicode text.
In all the encryption libraries I have looked at Crypto++ Botan Etc... None of them "appear" to provide Unicode aware methods for encrypting / decrypting data E.G. data can be passed in/ou... | Encryption libraries will use your data as a binary blob, not as characters. So it doesn't matter in what encoding the data is.
Encoding only affects interpretation of the data, not the data itself.
In other words: It doesn't matter
|
1,673,329 | 1,673,362 | c++: pass function as parameter to another function | i am currently implementing a binary tree in c++ and i want to traverse it with a function called in_order().
is there any way to pass a function as an argument, so that i can do things like below (without having to write the code to traverse the list more than once)?
struct tree_node; // and so on
class tree; //... | Yes, you can do this in a number of ways. Here are two common possibilities.
Old-style function pointers
class mytree
{
// typedef for a function pointer to act
typedef void (*node_fn_ptr)(tree_node&);
void in_order(node_fn_ptr)
{
tree_node* pNode;
while (/* ... */)
{
/... |
1,673,445 | 1,673,536 | How to Convert unsigned char* to std::string in C++? | I have unsigned char*, want to convert it to std::string. Can you please tell me the safest way to do this?
| You just needed to cast the unsigned char into a char as the string class doesn't have a constructor that accepts unsigned char:
unsigned char* uc;
std::string s( reinterpret_cast< char const* >(uc) ) ;
However, you will need to use the length argument in the constructor if your byte array contains nulls, as if you do... |
1,673,764 | 1,673,879 | freopen: reverting back to original stream | I needed to forward stdout to different files to separate some prints produced and the reverting back to normal stdout.
I used freopen to switch to the file in this way:
char name[80];
memset(name, 0, 80);
strcpy(name, "./scripts/asm/");
strcat(name, m_func->m_name->m_value);
strcat(name, ".shasm");
freopen(name, "w", ... | This can be achieved using fileno, dup and dup2 calls. I have tried this on linux not sure whether this will work on mac but I am sure you will get some equivalent functions for your setup. See if this sample code works for you. Sorry for lack of error-handling in the code. :)
#include <stdio.h>
main()
{
... |
1,673,844 | 1,674,297 | C/C++ compiler feedback optimization | Has anyone seen any real world numbers for different programs which are using the feedback optimization that C/C++ compilers offer to support the branch prediction, cache preloading functions etc.
I searched for it and amazingly not even the popular interpreter development groups seem to have checked the effect. And ... | 10% is a good ballpark figure. That said, ...
You have to REALLY care about the performance to go this route. The product I work on (DB2) uses PGO and other invasive and agressive optimizations. Among the costs are significant build time (triple on some platforms) and development and support nightmares.
When somethi... |
1,673,931 | 1,674,007 | How to enumerate network adapters and get their MAC addresses in Win32 API C++? | How do I enumerate network adapters and get their MAC addresses in Win32 API C++?
| This code should work:
{
ULONG outBufLen = 0;
DWORD dwRetVal = 0;
IP_ADAPTER_INFO* pAdapterInfos = (IP_ADAPTER_INFO*) malloc(sizeof(IP_ADAPTER_INFO));
// retry up to 5 times, to get the adapter infos needed
for( int i = 0; i < 5 && (dwRetVal == ERROR_BUFFER_OVERFLOW || dwRetVal == NO_ERROR); ++i )
... |
1,674,150 | 1,674,368 | NULL definition problem on 64 bit system | I'm running on RHEL 5.1 64 bit platfrom using gcc 4.1.2.
I have a utility function:
void str_concat(char *buff, int buffSize, ...);
which concats char * passed in variadic list(...), while last argument should be NULL, to designate end of the arguments. On 64 bit system NULL is 8 bytes.
Now to the problem. My applicat... | There's no "NULL definiton problem" in this case. There's a problem with how you are trying to use NULL in your code.
NULL cannot be portably passed to variadic functions in C/C++ by itself. You have to explicitly cast it before passing, i.e. in your case you have to pass (const char*) NULL as the terminator of the arg... |
1,674,162 | 1,674,348 | How to handle EINTR (interrupted System Call) | My user-space application sometimes blocks after receiving an EINTR-Signal, somehow.
What I recorded with strace:
time(NULL) = 1257343042
time(NULL) = 1257343042
rt_sigreturn(0xbff07be4) = -1 EINTR (Interrupted system call)
--- SIGALRM (Alarm cl... | The code which calls write (or other blocking operations) has to be aware of EINTR. If a signal occurs during a blocking operation, then the operation will either (a) return partial completion, or (b) return failure, do nothing, and set errno to EINTR.
So, for an all-or-fail write operation which retries after interrup... |
1,674,284 | 1,674,442 | How to produce hex output with boost::format? | Consider the following :
#include <vector>
#include <string>
#include <iostream>
#include <boost/format.hpp>
#include <boost/assign.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/assign/std/vector.hpp>
using namespace std;
typedef unsigned char byte;
typedef vector<byte> byte_array;
const byte_array bytes... | Compiled and tested:
#include <boost/format.hpp>
#include <iostream>
using namespace std;
using namespace boost;
int main()
{
unsigned int arr[5] = { 0x05, 0x04, 0xAA, 0x0F, 0x0D };
cout << format("%02X-%02X-%02X-%02X-%02X")
% arr[0]
% arr[1]
% arr[2]
... |
1,674,445 | 1,674,456 | Adding elements to an STL Map in a constructors Initialization List? | I was wondering if this was possible, and if so how I'd go about doing so. If it's not possible I'll just have to add the elements during the constructor body.
Ideally I would like the map immutable after construction.
What I'm trying to achieve is adding two pairs to the map that are created from constructor paramete... | It's possible, by copy construction: invoke a function which build the map!
std::map<int,int> myFunc(int a, int b);
class MyObject
{
public:
MyObject(int a, int b): m_map(myFunc(a,b)) {}
private:
std::map<int,int> m_map;
};
|
1,674,634 | 1,674,984 | URI Escape C++ wstring | I am looking for a good way to do a URI Escape in C++ that would be reasonable for a cross platform project.
I would like a function that would take a string like this:
L"jiayou加油"
And return:
L"jiayou%E5%8A%A0%E6%B2%B9"
I looked at using some thing like this, with minor modifacations to use wchar_t. However that wou... | No matter what you do you're in some sort of character encoding hell (that's just the way it is with character encodings).
From http://labs.apache.org/webarch/uri/rfc/rfc3986.html#characters:
The URI syntax provides a method of encoding data, presumably for the sake of identifying a resource, as a sequence of characte... |
1,674,864 | 1,674,876 | How to synchronize and combine results from multiple threads in C++? | I have a data feed continuously feeding data packet in. There are 5 threads(A, B, C, D, E) processing the data packages. Note the 5 threads have totally different speed and they generate 5 different features(each thread generate 1 feature) for every incoming data package.
The 5 threads are at different pace: when A has... | Have yourself an "aggregator" thread: this thread would get its input from the worker threads (through non-blocking thread-safe queues I suggest) and once a "batch" is ready, push it to your "analyzer" thread.
Queues offer the advantage of not blocking any of the workers: the "aggregator" just has to poll the worker qu... |
1,674,980 | 1,675,033 | Who deletes the memory allocated during a "new" operation which has exception in constructor? | I really can't believe I couldn't find a clear answer to this...
How do you free the memory allocated after a C++ class constructor throws an exception, in the case where it's initialised using the new operator. E.g.:
class Blah
{
public:
Blah()
{
throw "oops";
}
};
void main()
{
Blah* b = NULL;
try
{
... | You should refer to the similar questions here and here.
Basically if the constructor throws an exception you're safe that the memory of the object itself is freed again. Although, if other memory has been claimed during the constructor, you're on your own to have it freed before leaving the constructor with the except... |
1,675,021 | 1,675,045 | Out of four std::vector objects select the one with the most elements | I have four std::vector containers that all might (or might not) contain elements. I want to determine which of them has the most elements and use it subsequently.
I tried to create a std::map with their respective sizes as keys and references to those containers as values. Then I applied std::max on the size() of each... | You're severely overthinking this. You've only got four vectors. You can determine the largest vector using 3 comparisons. Just do that:
std::vector<blah>& max = vector1;
if (max.size() < vector2.size()) max = vector2;
if (max.size() < vector3.size()) max = vector3;
if (max.size() < vector4.size()) max = vector4;
... |
1,675,193 | 1,685,988 | How to use array optimization in boost serialization | I have to serialize an object that contains a std::vector<unsigned char> that can contain thousand of members, with that vector sizes the serialization doesn't scale well.
According with the documentation, Boost provides a wrapper class array that wraps the vector for optimizations but it generates the same xml output.... | Finally, I used the BOOST_SERIALIZATION_SPLIT_MEMBER() macro and coded two functions for loading and saving. The Save function looks like:
template<class Archive>
void save(Archive & ar, const unsigned int version) const
{
using boost::serialization::make_nvp;
std::string sdata;
Vector2String(vData, sdata);
ar ... |
1,675,508 | 1,675,538 | Reading an std::ifstream to a vector of lines | How would I go about reading in a file where each line is a single number, then outputing that number into a vector of lines?
eg: file.txt contains:
314
159
265
123
456
I have tried this implementation:
vector<int> ifstream_lines(ifstream& fs) {
vector<int> out;
int temp;
getline(fs,temp);
while (!fs.e... | I suspect you want something like this:
#include <vector>
#include <fstream>
#include <iterator>
std::vector<int> out;
std::ifstream fs("file.txt");
std::copy(
std::istream_iterator<int>(fs),
std::istream_iterator<int>(),
std::back_inserter(out));
|
1,675,735 | 1,718,322 | High-performance Math library for .NET /C# and Java | We currently have a high-performance scientific application written in C++ that makes use of Intel Math Kernel Library.
We are considering writing a benchmark application written in Java and .NET/C# to compare the performance difference. To do that, we also need a good (commercial is preferred) math library for both. D... | Lol..why didnt I think of this before?
Just use Intel MKL Math library in Java and .NET!
See the following links:
Using MKL in Java app
How to use MKL with Java
Using MKL in C#
MKL 10.2 update
MKL in depth
|
1,675,992 | 1,678,807 | How do I set a background color for the whole window of a Qt application? | Does anyone know how one would be able to set a background color for the whole window of a Qt application?
So far I am using stylesheets but can only figure out how to assign a background color to a widget such as QGroupBox or QPushButton. Basically, if I want a black background how would I make it seamless without any... | I would simply use a Style Sheet for the whole window.
For instance, if your window is inheriting from QWidget, here is what I'm doing :
MainWindow::MainWindow(QWidget *parent) : QWidget(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setStyleSheet("background-color: black;");
}
On my Mac, my whole ... |
1,676,385 | 1,676,414 | C++ Data Member Alignment and Array Packing | During a code review I've come across some code that defines a simple structure as follows:
class foo {
unsigned char a;
unsigned char b;
unsigned char c;
}
Elsewhere, an array of these objects is defined:
foo listOfFoos[SOME_NUM];
Later, the structures are raw-copied into a buffer:
memcpy(pBuff,listOfFoos,3... | An array of objects is required to be contiguous, so there's never padding between the objects, though padding can be added to the end of an object (producing nearly the same effect).
Given that you're working with char's, the assumptions are probably right more often than not, but the C++ standard certainly doesn't gu... |
1,677,070 | 1,677,193 | Cross-Platform equivalent to windows events | I'm trying to port some Windows code to Linux, ideally through platform-independent libraries (eg boost), however I'm not sure how to port this bit of event code.
The bit of code involves two threads (lets call them A and B). A wants to do something that only B can, so it sends B a message, then waits for B to say its ... | I think a good, cross-platform equivalent to win32 events is boost::condition, so your code could look something like this:
void foo()
{
boost::mutex mtxWait;
boost::condition cndSignal;
bCall(boost::bind(&bar, mtxWait, cndSignal));
boost::mutex::scoped_lock mtxWaitLock(mtxWait);
cndSignal.wait(m... |
1,677,211 | 1,677,302 | sort using boost::bind | bool pred(int k, int l, int num1, int num2)
{
return (num1 < num2);
}
int main()
{
vector <int> nums;
for (int i=50; i > 0; --i)
{
nums.push_back(i);
}
std::sort (nums.begin(), nums.end(), boost::bind(&pred, 5, 45));
}
I am a boost newbie.
I was learning to use boost::bind and I wanted to sort ... | You can't do that from sort.
Remove the elements before or after sort.
bool outOfRange(int low, int high, int num) {
return low > num || num > high;
}
...
nums.erase(
std::remove_if(nums.begin(), nums.end(),
boost::bind(&outOfRange, 5, 45, _1)),
nums.end()
)... |
1,677,345 | 1,683,136 | How can I tell that a directory is the Recycling bin in VB6? | I am attempting to port the code in this article to VB6, but I'm experiencing crashing. I'm pretty sure my error is in my call to SHBindToParent (MSDN entry) since SHParseDisplayName is returning 0 (S_OK) and ppidl is being set. I admit my mechanism of setting the riid (I used an equivalent type, a UUID) is pretty ug... | I believe your call to SHBindToParent is crashing because you need to pass longs, then use the returned pointers to copy the memory into your types. I found several posts when I googled the SHBindToParent function that mentioned OS support, mostly 95 and 98. When I tried it on XP SP3 I got an error "No such interface s... |
1,677,585 | 1,907,366 | Pruning a static library in c++ | I am trying to expose a single well defined class by building a static library and then shipping the built library with a few header files that define that class and the interfaces needed to use it. I have that working but the problem I am running into is the library is gigantic. It has every single object file from th... | Make a shared library. It behaves like an executable from the point of view of linking etc. It should do the discarding you mentioned you saw on the executable.
|
1,677,635 | 1,677,648 | Getting back into Windows programming | I've been out of the Microsoft stack for a while now, been focused on Linux, open source stuff and web development in PHP. I used to do some desktop app development and some DirectX stuff on Windows in Dev Studio (all C and C++).
I'd like to brush up on the MS stuff just to keep up on what's going on. I've installed MS... | I've been developing on Microsoft stack since 1997, starting with C/C++/MFC/ATL, but all of the recent projects were on .NET platform (C#), so I would recommend learning .NET/C#. C/C++ still has its place, but it loses relevance rather rapidly. If not for legacy projects, we would not even bother with C/C++. Just my 2 ... |
1,677,693 | 1,682,233 | Crash in msvcp90d.dll when retrieving an iterator from a boost::tokenizer | When I retrieve the begin() iterator of a boost::tokenizer, I get a crash in msvcp90d.dll, that says "ITERATOR LIST CORRUPTED", which looks suspiciously like issues I have run into before with the _HAS_ITERATOR_DEBUGGING compiler flag, however I have verified that my program is being compiled with this flag turned off.... | There is a bug in Visual C++ with std::ostringstream when _HAS_ITERATOR_DEBUGGING is disabled.
If I recall correctly, the std::string copy constructor copies iterators. You can get around this by using the std::string conversion constructor taking a char* instead.
If you change
std::string mystr(input.str());
to
std:... |
1,677,725 | 1,677,819 | Class design ideas for state machine like object | I'm writing a state machine like object. Looks like
Class A:
vector<Actions> m_enter_actions;
vector<Actions> m_exit_actions;
public:
ClassA....
~ClassA
SetEnterActions(vector<Actions> vector)
SetExitActions(vector<Actions> vector)
Is this the best way to handle this? I wonder if I should have like
Class... | The signatures of the SetEnterActions and SetExitActions functions should be designed to prevent the caller from knowing how ClassA stores the Actions. Users of ClassA don't want to know whether ClassA stores them in a vector, or a deque, or a list, or in an EnterActions class, or whatever. They certainly don't want to... |
1,677,914 | 1,677,921 | C++ Object, Member's Memory Position Offset | Is there a better method to establish the positional offset of an object's data member than the following?
class object
{
int a;
char b;
int c;
};
object * o = new object();
int offset = (unsigned char *)&(object->c) - (unsigned char *)o;
delete o;
| In this case, your class is POD, so you can use the offsetof macro from <cstddef>.
In practice, in most implementations, for most classes, you can use the same trick which offsetof typically uses:
int offset = &(((object *)0)->c) - (object *)0;
No need to actually create an object, although you may have to fight off s... |
1,678,044 | 1,678,080 | Datastructure alignment | So, I'm coding some packet structures (Ethernet, IP, etc) and noticed that some of them are followed by attribute((packed)) which prevents the gcc compiler from attempting to add padding to them. This makes sense, because these structures are supposed to go onto the wire.
But then, I counted the words:
struct ether_he... | If your structure is already a multiple of the right size, then no, the __attribute__((packed)) isn't strictly necessary, but it's still a good idea, in case your structure size ever changes for any reason. If you add/delete fields, or change ETH_ALEN, you'll still want __attribute__((packed)).
I believe the double pa... |
1,678,347 | 1,678,392 | How to read a word into a string ignoring a certain character | I am reading a text file which contains a word with a punctuation mark on it and I would like to read this word into a string without the punctuation marks.
For example, a word may be " Hello, "
I would like the string to get " Hello " (without the comma). How can I do that in C++ using ifstream libraries only.
Can I ... | If you only want to ignore , then you can use getline.
const int MAX_LEN = 128;
ifstream file("data.txt");
char buffer[MAX_LEN];
while(file.getline(buffer,MAX_LEN,','))
{
cout<<buffer;
}
EDIT: This uses std::string and does away with MAX_LEN
ifstream file("data.txt");
string string_buffer;
while(getline(f... |
1,678,394 | 1,678,403 | debugging a thread process using gdb/dbx | This might be genuine question but i am asking here since i was out of any clue when i was asked this question in an interview.
how could we debug a thread which was created by another thread?
let's say there is a main process and it calles the function pthread_create to create a thread process which is not joinable an... | You can attach gdb to the whole process, then use gdb's thread ops to navigate between threads. It might help to print the thread id when pthread_create'ing the thread you want to debug.
|
1,678,653 | 1,679,836 | Boost spirit and forward declarations issues | Could someone please give me some advice/ideas about how to deal with the situations when it's needed to have a look at further declarations to be able to make correct semantic actions on current moment? For example, it is a well-known occurrence when someone writes an interpreter/compiler of some programming language ... | [2nd answer, on semantics]
This particular example happens to be simple. What you can do is record function calls made to yet undeclared functions, and the actual argument types. When you do encounter a function declaration later, you check if there are preceding function calls that are (better) matched to this new fun... |
1,678,830 | 1,682,392 | How can I autoexpand an item in a QTreeView when it is filtered by QSortFilterProxyModel? | I have a normal QTreeView, a custom QAbstractItemModel and a custom QSortFilterProxyModel.
I've reimplemented QSortFilterProxyModel::filterAcceptsRow to filter items from my model in the way I want, however now I want those filtered items to be expanded in the treeview.
The obvious solution was to emit a signal from Q... | QTreeView has a "expandAll" slot, which could be called after you set the model. I would think that this should do what you want.
|
1,678,857 | 1,678,986 | C++ STL for_each should take pointer to member function taking one argument | I have to pass the address of a member fn taking one argument to the std::for_each. how do i do this?
class A{
void load()
{
vector<int> vt(10,20);
std::for_each(vt.begin(), vt.end(), &A::print);
//It didnt work when i tried mem_fun1(&A::print)
}
void print(int a)
{
cout<<a;
}
};
Thanks
| When using std::mem_fun, you have to pass pointer to class as first argument. You can bind it in this case with std::bind1st.
class A
{
public:
void print(int v) {std::cout << v;}
void load()
{
std::vector<int> vt(10, 20);
std::for_each(vt.begin(), vt.end(), std::bind1st(std::mem_fun(&A... |
1,678,924 | 1,678,997 | PopFront Delimma C++ | Strange programming problems as of now..As you can see below i have assigned intFrontPtr to point to the first cell in the array. And intBackPtr to point to the last cell in the array...:
bool quack::popFront( int &popFront )
{
//items[count-1].n = { 9,4,3,2,1,0 };
nPopFront = items[0].n;
if ( count >= m... | My suggestion are :
1). Put statement --count where it keeps object's state valid on exceptional condition.
2). clear your concepts of pointers which will help you a lot.
|
1,679,515 | 1,679,586 | libxml2 error handling | I'm writing a small wrapper around libxml2 in C++, and I'm trying to work out how to handle errors. For now, let's say I just want to print them out. Here's what I've got at present:
My error handling function:
void foo(void *ctx, const char *msg, ...) {
cout << msg << endl;
return;
}
Initialised like this:
xmlGen... | The three dots at the end of the argument list for you function foo() means it takes a variable amount of arguments. To be able to print those you could do something like this (not tested):
#include <stdarg.h>
#define TMP_BUF_SIZE 256
void foo(void *ctx, const char *msg, ...) {
char string[TMP_BUF_SIZE];
va_list... |
1,679,669 | 1,679,708 | Data-structure that stores unique elements but answers queries for another ordering in C++ | is there a data structure, which stores its elements uniquely (for a given compare-Functor) but answers queries for the highest element in that data structure with respect to another compare-Function ?
For Example: I have a class with two properties :
1) the size
2) the value
I'd like to have a data structure which sto... | Boost::MultiIndex comes to mind.
|
1,679,768 | 1,679,969 | Finding neighbor positions in matrix | I'v been bored so I created a small console minesweeper game and while writting it I had to find the neighbor positions of an element in a size*size matrix which is represented as an vector of elements and one variable which holds the size value. I didn't want to return the actual values of the neighbor elements but th... | Yeah, your code is awful. Here's a better attempt (fixed, sorry):
for (int dx=-1; dx<=1; dx++)
for (int dy=-1; dy<=1; dy++)
if (dx || dy){
int x = row+dx, y=col+dy;
if (x >= 0 && x < size && y >= 0 && y < size)
result.push_back(calcField(x, y, size));
}
|
1,679,770 | 1,679,901 | C++ Virtual function implementation? | If I have in C++:
class A {
private: virtual int myfunction(void) {return 1;}
}
class B: public A {
private: virtual int myfunction(void) {return 2;}
}
Then if I remove virtual from the myfunction definition in class B, does that mean that if I had a class C based on class B, that I couldn't override the myfu... | The first definition with 'virtual' is the one that matters. That function from base is from then on virtual when derived from, which means you don't need 'virtual' for reimplemented virtual function calls. If a function signature in a base class is not virtual, but virtual in the derived classes, then the base class d... |
1,679,858 | 1,679,972 | Do interfaces solve DDD with code duplication? | AccountController can't extend BaseAccount and BaseController at the same time. If I make all BaseAccount or BaseController methods empty, I can have an interface, but if I implement that interface in two different places, that is, I make a contract to implement a method in two different places, I will have duplicated ... | Little bit confused with your last sentance, but if you want multiple inheritance then you need to do this:
AccountController extends BaseAccount, and BaseAccount extends BaseController
BaseController
|
BaseAccount
|
AccountController
Using this method will enable you to access all member functions of BaseAccount ... |
1,679,974 | 1,680,905 | Converting an FFT to a spectogram | I have an audio file and I am iterating through the file and taking 512 samples at each step and then passing them through an FFT.
I have the data out as a block 514 floats long (Using IPP's ippsFFTFwd_RToCCS_32f_I) with real and imaginary components interleaved.
My problem is what do I do with these complex numbers on... | The usual thing to do to get all of an FFT visible is to take the logarithm of the magnitude.
So, the position of the output buffer tells you what frequency was detected. The magnitude (L2 norm) of the complex number tells you how strong the detected frequency was, and the phase (arctangent) gives you information th... |
1,680,100 | 1,700,184 | MFC without document/view architecture | I'd like some help on using MFC without the document/view architecture.
I created a project without doc/view support, Visual C++ created a CFrameWnd and a view that inherits from CWnd. I replaced the view inheriting from CWnd with a new view that inherits from CFormView.
However, when I run my program, after I close th... | The problem is MFC's lifecycle management. The view declaration (created by Visual C++ wizard) is:
CChildView m_wndView;
I replaced the above code with:
CChildFormView m_wndView;
CChildView inherits from CWnd, CChildFormView inherits from CFormView. Both views were created by the wizard, but only CChildForm... |
1,680,161 | 1,682,356 | how can I fix xcode compiling everything all the time? | I've started to use XCode and it seems to work, well, most of it.
The annoying thing is it compiles all the source files, even those that didn't change, each and every time.
I'm getting the grips with openframeworks and I waste time compiling the openframeworks source files every time although they don't change.
Here a... | Many (most?) build systems use the last-modified date and time of the files to determine whether a recompilation needs to be performed. I would first verify that the file dates are behaving as expected; if the files are on a network drive, for example, there could be different time settings or clock discrepancies that... |
1,680,249 | 1,681,171 | How to use SQLite in a multi-threaded application? | I'm developing an application with SQLite as the database, and am having a little trouble understanding how to go about using it in multiple threads (none of the other Stack Overflow questions really helped me, unfortunately).
My use case: The database has one table, let's call it "A", which has different groups of row... | Check out this link. The easiest way is to do the locking yourself, and to avoid sharing the connection between threads. Another good resource can be found here, and it concludes with:
Make sure you're compiling SQLite with -DTHREADSAFE=1.
Make sure that each thread opens the database file and keeps its own sqlite str... |
1,680,411 | 1,680,490 | Atomic Operation C++ | In C++, Windows platform, I want to execute a set of function calls as atomic so that execution doesn't switches to other threads in my process. How do I go about doing that? Any ideas, hints?
EDIT: I have a piece of code like:
someObject->Restart();
WaitForSingleObject(handle, INFINITE);
Now the Restart() function d... | This is generally not possible. You can't force the OS to not switch to other threads.
What you can do is one of the following:
Use locks, mutexes, criticals sections or semaphores to synchronize a handful of threads that touch the same data.
Use basic operations that are atomic such as compare-and-exchange or atomic-... |
1,680,538 | 1,680,599 | C++ Separate Compilers for classes (vtables)? | I was wondering what the consequences are for compiling a class A with one compiler that doesn't allow multiple inheritance, and compiling a class B that does support it (and class B derived from class A).
I don't really understand the linking process...would it be possible to use both together? What disadvantages exis... | As a general rule, don't ever compile parts of your C++ program with different compilers.
Different compilers may use, and often do, different mangling schemas for the symbol mangling stage, so it's very unlikely that the linking between separately compiled stuff will work.
See doc about mangling name_mangling
|
1,680,880 | 1,680,976 | C++ array with value semantics and no allocator shenanigans? | I'm looking for a C++ container that's a cross between boost::array, boost::scoped_array and std::vector.
I want an array that's dynamically allocated via new[] (no custom allocators), contained in a type that has a meaningful copy-constructor.
boost::array is fixed-size, and although I don't need to resize anything, I... | Inherit privately from std::vector, and then adjust appropriately. For example remove resize(), and perhaps add setsize() and a bool flag to determine if the size has been set.
Your copy constructor can invoke the std::vector copy constructor, and set the flag automatically to prevent further changes.
|
1,680,920 | 1,727,559 | Setting the version number in an NCBI c++ toolkit app | How can I set the version number in a NCBI C++ Toolkit Application?
I mean the version number which is displayed when I start my program with the parameter -version.
I read through the docs, but have not found it yet.
(I know this is a highly specific question, but I figured it was worth a try)
| Give it a void Init(void) method containing code along the following lines:
// the last two parameters are optional
CVersionInfo version_info(1, 2, 3, "My App");
SetVersion(version_info);
However, this is currently broken (bug already submitted), so the workaround is to give the application class a constructor and cal... |
1,680,971 | 1,681,127 | Patterns for making c++ code easy to test | Should you design your code to make testing easier? And if so how to design c++ code so that it is easy to test.
How do you apply dependency-injection in c++?
Should I implement the classes using a pure interface class as the base in order to simplify the creation of fake test objects?
That would force me into maki... |
Should I implement the classes using a pure interface class as the base in order to simplify the creation of fake test objects?
That would force me into making a lot of virtual methods. Will that affect performance?
A workaround I often use is to templatize the class instead of hiding it behind an interface. Then I... |
1,680,980 | 1,681,471 | istream get method behavior | I read istream::get and a doubt still hangs. Let's say my delimiter is actually the NULL '\0' character, what happens in this case? From what I read:
If the delimiting character is found, it is not extracted from the input sequence and remains as the next character to be extracted. Use getline if you want this charac... | If you have something like this, then delimiter will not get stuck in the input stream:
std::string read_str(std::istream & in)
{
const int size = 1024;
char pBuffer[size];
in.getline(pBuffer, size, '\0');
return std::string(pBuffer);
}
just an example if you have '\0' as delimiter and... |
1,681,145 | 1,681,186 | How to initialize a shared library on Linux | I am developing a shared library using C++ under Linux, and I would like this library to use log4cxx for logging purposes. However, I'm not sure how to set this up. For log4cxx to work, I need to create a logger object. How can I make sure this object is created when my library is loaded?
I suspect that it will be easi... | In C++ under Linux, global variables will get constructed automatically as soon as the library is loaded. So that's probably the easiest way to go.
If you need an arbitrary function to be called when the library is loaded, use the constructor attribute for GCC:
__attribute__((constructor)) void foo(void) {
printf("... |
1,681,264 | 1,681,268 | How do I create a native application using Visual C++ 2008? | I am getting started in C++. How can I setup Visual Studio 2008 to create native (not managed) code?
| Choose a Win32 Project.
|
1,681,327 | 1,691,703 | is DISPID_VALUE reliable for invokes on IDispatchs from scripts? | Continuing from this question, i am confused whether DISPID_VALUE on IDispatch::Invoke() for script functions and properties (JavaScript in my case) can be considered standard and reliable for invoking the actual function that is represented by the IDispatch?
If yes, is that mentioned anywhere in MSDN?
Please note tha... | It should be reliable for invokes on objects from scripts if the script defines it consistently. This should be the case for JScript/Javascript in MSHTML, but unfortunately there is really sparse documentation on the subject, I don't have any solid proof in-hand.
In my own experience, a Javascript function passed to at... |
1,681,337 | 1,681,433 | Inheriting friendship in C++? | Since class friendship is not inherited in C++, what's the best way to "fake" it?
I was thinking about exposing the friend class's private interface through protected methods in the to-be-inherited base-class, but that results in having to write (and maintain) the same interface twice.
Are there any other ways?
| The use of a key is a possible solution.
The idea is that you can unlock the operations only if you have a key... but an example is worth thousands on word so let's dive:
// Step 1: The key
class NeedAccess;
namespace details { class Key { friend NeedAccess; Key() {} }; }
// Step 2: NeedAccess
class NeedAccess
{
prot... |
1,681,429 | 1,682,183 | How to stop a running thread safely on user request? | I'm in a scenario when I have to terminate a thread while the thread is running according to user action on GUI. I'm using Qt 4.5.2 on Windows. One way to do that is the following:
class MyThread : public QThread
{
QMutex mutex;
bool stop;
public:
MyThread() : stop(false) {}
void requestSt... | Firstly it doesn't look like you need a mutex around your entire inner loop, just around the if (stop) expression as the others say, but I may be missing some of your app context to definitively say that. Maybe you need requestStop() to block until the thread exits.
If the reduced mutex scope is adequate for you, then ... |
1,681,459 | 1,682,393 | Boost::typeof compiler problem: mangling typeof, use decltype instead | short example:
#include <boost/typeof/typeof.hpp>
#include <boost/proto/core.hpp>
using namespace boost;
template<class T, class U>
BOOST_TYPEOF_TPL(T() + U()) add2(const T& t, const U& u)
{
return t + u;
};
int main(){
typedef BOOST_TYPEOF(add2(2.5, 1.5)) type; // get type -> works
BOOST_STATIC_ASS... | The example in the typeof documentation first wraps the result of the BOOST_TYPEOF_TPL macro in a templated struct, then uses that when declaring the function. Does that work any better for you?
template<class T, class U>
struct result_of_add2
{
typedef BOOST_TYPEOF_TPL(T() + U()) type;
};
template<class T, class ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.