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 |
|---|---|---|---|---|
3,206,229 | 3,206,369 | Change input locale (keyboard -- left shift+ alt + 1) key sequence PROGRAMMATICALLY | On XP, if you go to
control panel -> regional and language Options -> Languages Tab -> Details ->
If you have more than one keyboard in use, then, click Key Settings. Those are the settings I would like to change. I would like to set it up so that the DVORAK keyboard is Left Alt + Shift + 1. I can use C++, C# or... | By default all programs use the C local (Because we all program in C dialects I suppose)
You can imbue streams with an appropriate local.
Just remember that you must imbue the stream before opening/using it. An attempt to imbue a stream after it has been opened/used will be silently ignored.
This means that for std::ci... |
3,206,302 | 3,206,387 | C++ template determine function return type | How can I go about determining return type of a member generic function?
template<class E>
struct result<E> {
// E has member function data(), I need to know its return type
typedef typename &E::data type;
};
is it possible to do it in generic way?
I know there is boost:: result_of but for ... | GCC's nonstandard typeof operator can do this, as can Boost.TypeOf.
|
3,206,310 | 3,206,641 | How to filter characters from a string with C++/Boost | This seems like such a basic question, so I apologize if it's already been answered somewhere (my searching didn't turn up anything).
I just want to filter a string object so that it contains only alphanumeric and space characters.
Here's what I tried:
#include "boost/algorithm/string/erase.hpp"
#include "boost/algorit... | With the std algorithms and Boost.Bind:
std::wstring s = ...
std::wstring new_s;
std::locale loc;
std::remove_copy_if(s.begin(), s.end(), std::back_inserter(new_s),
!(boost::bind(&std::isalnum<wchar_t>, _1, loc)||
boost::bind(&std::isspace<wchar_t>, _1, loc)
));
|
3,206,347 | 3,206,386 | Small issue with creating a process ( CreateProcess or ShellExecuteEx) with parameters | Related question: CreateProcess doesn't pass command line arguments.
Is there a difference between passing an argument vs. passing a parameter to an EXE when using CreateProcess (and/or ShellExecuteEx)?
I'm trying to call something like:
myExe.exe /myparam
with the code like :
TCHAR Buffer[MAX_PATH];
DWORD dwRet;
d... | Try this in case there are spaces in the path:
CString sCmd;
sCmd.Format ( "\"%s\\%s\"", Buffer, command);
Or else pass the parameters via the parameters argument.
|
3,206,526 | 3,208,466 | Windows LDAP Authentication in C++ | I am currently trying to authenticate users in a c++ application in Windows. I need to display a dialog for username and password and verify that they are an authenticated user on the Windows machine. Are there any libraries that allow for this functionality or a good way to go about it?
| Probably CredUIPromptForWindowsCredentials (see http://msdn.microsoft.com/en-us/library/aa375178.aspx) or old CredUIPromptForCredentials (see http://msdn.microsoft.com/en-us/library/aa375177.aspx) could solve your problem?
UPDATED: Another the most old way to authenticate a user is using of SSPI. It will not help with ... |
3,206,578 | 3,206,635 | Exporting C++ classes from DLL | I came across this article on Code Project that talks about using an abstract interface as an alternative to exporting an entire class from a C++ DLL to avoid name mangling issues. The author has a Release() method in his interface definition that is supposed to be called by the user to free the class object's resource... | by doing this, you risk calling delete (in your process, within auto_ptr's destructor) on an object that is not created by the matching call to new() (that is done inside the factory function, hence inside the dll). Trouble guaranteed, for instance when your dll is compiled in release mode while the calling process in ... |
3,206,745 | 3,207,330 | connecting a function to a boost::signal runs, but doesn't call the function | I have a class Yarl in my code with a member function refresh that I want to bind to two boost::signals. One of these signals is a member of a class EventHandler defined like this:
class EventHandler {
public:
boost::signal<void()> sigRefresh;
};
The other is a free floating signal in another file declare... | I'm taking a guess that you are multiply defining signal_refresh. The static keyword before it's declaration suggests to me the code snippet is in a header file and you had to put the static there to get it to compile without redefined symbol errors. If you have done this then every source file including the header wil... |
3,206,846 | 3,207,181 | How to join in a WMI Query (WQL) | I want to get the serial number of the boot-harddisk via a WQL query.
The boot-partition can be retrieved using the following query:
SELECT * FROM Win32_DiskPartition where BootPartition=True
The serial number is in Win32_DiskDrive:
SELECT DeviceID, SerialNumber FROM Win32_DiskDrive
Win32_DiskDriveToDiskPartition has... | WQL doesn't support the JOIN clause. You need to use the ASSOCIATORS OF statement as you guessed. Here's an example in VBScript:
strComputer = "."
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colPartitions = oWMI.ExecQuery( _
"SELECT * FROM Win32_DiskPartition WHERE BootPartition=True") ... |
3,207,018 | 3,208,184 | Register keyword in C++ | What is difference between
int x=7;
and
register int x=7;
?
I am using C++.
| In C++ as it existed in 2010, any program which is valid that uses the keywords "auto" or "register" will be semantically identical to one with those keywords removed (unless they appear in stringized macros or other similar contexts). In that sense the keywords are useless for properly-compiling programs. On the oth... |
3,207,064 | 3,207,083 | Need Help Creating Multiple Directories in Makefile | I have the following block of code in a makefile:
param_test_dir:
@if test -d $(BUILD_DIR); then \
echo Build exists...; \
else \
echo Build directory does not exist, making build dir...; \
mkdir $(BUILD_DIR); \
fi
@if test -d $(TEST_DIR); then \
echo Tests exists...; \
else \
echo Tests di... | mkdir -p build/tests/param_test/bin
mkdir manual: -p, --parents,
no error if existing, make parent directories as needed
|
3,207,094 | 3,208,441 | Fastest factorial implementation with 64-bit result in assembly | This is not homework, just something I though of. So, straight computing factorial is not exactly fast; memoization can help, but if the result is to fit into 32 or 64 bits, then the factorial only can work for inputs 0 through 12 and 20 respectively. So ... we might as well use a lookup table:
n n!
0 1
1 ... | I have cleverly built a lookup table in assembly. Just in case you're rusty on your assembly,
The routine expects the parameter to be in the ecx register. I verify that it is in range then read the lookup table's values into the eax and edx registers. If the value is out of range, I just xor the eax and edx registers... |
3,207,098 | 3,212,546 | How to write programmatically some unicode text in RTF format? | In order to generate RTF programmatically I have decided to use rtflib v1.0 from codeproject.com. But I can't understand how to generate text in russian unicode. So I need to generate a unicode text. Could someone help me?
P.S. Honeslty, I could write in .rtf file some text in, only by opening it with MS Word. But afte... | Here are steps:
Create a file named .rtf
Open .rtf
Write there the following code in order to generate an RTF file which contains UTF-8 encoded content:
{\rtf1\adeflang1025\ansi
{\fonttbl
{\f26\fbidi \froman\fcharset204\fprq2{\*\panose 010a0502050306030303}Sylfaen;}
}
{\rtlch\fcs1 \af31507 \ltrch\fcs0 \f26 \u<unico... |
3,207,155 | 3,208,334 | Java vs. C++ for building a GUI which has a C++ backend | I currently have a C++ backend that I need to connect with a GUI, and since I've never built a GUI before, I was confused on where to start.
I'm comfortable writing code in C++ and Java, so I'd prefer my GUI to be in one of those languages. Also, the GUI has to be reasonably OS independent over Windows and Linux (and ... | You say you already know C++ and Java, and that you never did a GUI before. That means:
no matter if you go for a Java GUI or a C++ GUI, you will need to learn how to handle the GUI framework
if you chose Java, you also need to learn how to interface between the two languages
So staying in C++ saves you one thing to ... |
3,207,307 | 3,207,347 | Simple noob I/O question (C++) | sorry for the noob question, but I'm new to C++.
I need to read some information, line-by-line, from a file, and perform some calculations, and output into another file. For example, we read a unique ID for each line, a name, and 2 numbers. The last 2 numbers are multiplied, and in the output file, the ID, name and pro... | Use
while (!cin.eof()) {
|
3,207,399 | 3,207,431 | What is the most efficient way to convert STL string array to const char* array? | We have:
std::string string_array[2];
string_array[0] = "some data";
string_array[1] = "some more data";
char* cstring_array[2];
What is the most efficient way to copy data from string_array to cstring_array? Or pass string_array to the function, needed "const char* cstring_array[]"?
| A function that takes a char const * is only written to accept a single string at a time, not an array of strings. To pass an std::string to such a function, just call the function with your_string.c_str() as the parameter.
Edit: for a function that takes an array of strings, the obvious choice (at least to me) would b... |
3,207,461 | 3,207,556 | Best way to create windows applications | I have been learning windows API from online and PDF books but I hear of people using sdk and visual studio programs. What should i do? API I'd create but extremely complex. Would I benefit from learning the API or should I get a sdk or program that writes to code for me? I have msc++e but I don't think it comes with t... | In the case of windows, the SDK and the Win32 API refer to pretty much the same thing. The SDK is all the crap you need to target the API (this is always what an "SDK" is). When you're using a non-VC compiler on windows (or a cross-compiler) you have to download the SDK in order to write win32 programs.
There's very ... |
3,207,538 | 3,207,547 | Use fprintf to memory stream | I have a vc++ method that uses fprintf to write values to a file in the hard disc. I want to change this method so that instead of writing the values to disc, I want to return a pointer to the data.
I know in advance the size I have to allocate. Is there any way to pass a memory stream or unsigned char pointer to fpri... | You can use sprintf or better yet snprintf [_snprintf/snprintf_s for VC++] (as Michael Burr pointed out and as it's noted in the Remarks section of the sprintf link).
And, since it's tagged C++, better yet use std::stringstream.
|
3,207,662 | 3,208,562 | how do I insert a string datetime into mysql using c++ | I have a datetime field in the following format:
string date = "Jun 23 19:47:15 +0000 2010";
how do I insert it ito datetime field in mysql table? I am assuming I have to convert the date into unix timestamp before I insert it into the table.
| First, you've got an sql-injection attack waiting to happen. Had to be said.
Ok, that huge problem swept aside, you can either convert the date to a MySQL format (such as a UTC timestamp then converted again with FROM_UNIXTIME()), or tell MySQL how to convert it using STR_TO_DATE(). Both are documented in the MySQL man... |
3,207,679 | 3,207,722 | What are the shortcomings of std::reverse_iterator? | The documentation for boost's specialized iterator adaptors states that boost::reverse_iterator "Corrects many of the shortcomings of C++98's std::reverse_iterator."
What are these shortcomings? I can't seem to find a description of these shortcomings.
FOLLOW-UP QUESTION:
How does boost::reverse_iterator correct these ... | Well, the big problem is that they're not forward iterators, and there's stuff that pretty much expect forward iterators. So, you have to do some funny conversions to get things to work. To name some issues
Some versions of erase() and insert() require iterators rather than reverse iterators. That means that if you're... |
3,207,704 | 3,218,316 | How can I cin and cout some unicode text? | I ask a code snippet which cin a unicode text, concatenates another unicode one to the first unicode text and the cout the result.
P.S. This code will help me to solve another bigger problem with unicode. But before the key thing is to accomplish what I ask.
ADDED: BTW I can't write in the command line any unicode symb... | Here is an example that shows four different methods, of which only the third (C conio) and the fourth (native Windows API) work (but only if stdin/stdout aren't redirected). Note that you still need a font that contains the character you want to show (Lucida Console supports at least Greek and Cyrillic). Note that eve... |
3,207,712 | 3,207,773 | Including Templated C++ in Objective C | I am trying to include a C++ library with quite a few templates into an objective C application.
It seems to perpetually choke on a few inline statements inside a shared library:
template <class T>
inline T MIN(T a, T b) { return a > b ? b : a; }
template <class T>
inline T MAX(T a, T b) { return a > b ? a : b; }
yie... | There are already macros MIN and MAX defined in Foundation/NSObjCRuntime.h.
#if !defined(MIN)
#define MIN(A,B) ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __a : __b; })
#endif
#if !defined(MAX)
#define MAX(A,B) ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __b : _... |
3,207,917 | 3,207,988 | Fail to CoCreateInstance an EXE COM server | I have an EXE COM server (used to elevate our application to a higher integrity level) which is downloaded to %temp% and registered by an ActiveX control. This COM server works pretty well on Vista machines. On Window 7 machines I got something wired: the COM server can be downloaded and registered successfully, but I ... | Yes they do. Start a command prompt and use DIR /R. You'll see the alternate data stream in the file. The one that says: "don't trust this file, it came from an untrusted source".
You can delete them with the filename:streamname syntax. Check if that's okay with your customer first. I don't know many that are thri... |
3,208,657 | 3,208,745 | Is unsigned char('0') legal C++ | The following compiles in Visual Studio but fails to compile under g++.
int main()
{
int a = unsigned char('0');
return 0;
}
Is unsigned char() a valid way to cast in C++?
| No, it's not legal.
A function-style explicit type conversion requires a simple-type-specifier, followed by a parenthesized expression-list. (§5.2.3) unsigned char is not a simple-type-specifier; this is related to a question brought up by James.
Obviously, if unsigned char was a simple-type-specifier, it would be lega... |
3,208,927 | 3,209,893 | Large scale Machine Learning | I need to run various machine learning techniques on a big dataset (10-100 billions records)
The problems are mostly around text mining/information extraction and include various kernel techniques but are not restricted to them (we use some bayesian methods, bootstrapping, gradient boosting, regression trees -- many di... | Unless the classification state space you are attempting to learn is extremely large, I would expect that there is significant redundancy in a text-mining-focused dataset with 10-100 billion records or training samples. As a rough guess, I would doubt that one would need much more than a 1-2% random sample subset to l... |
3,208,958 | 3,210,155 | How to keep a list of instances of a class? | I'm writing a raytracer in C++ and need to be able to check intersections with every object in a scene (optimizations will come later), and to do this, I need to keep a running list of class instances. A list of pointers, updated when a new instance is created, won't work because as far as I know there is no way to inc... |
I'm writing a raytracer in C++ and need to be able to check intersections with every object in a scene [...]
The standard approach is a spatial graph. Most commonly, octrees are used, since they can express location in 3-dimensional space. Trivially, the spatial tree would look something like this:
struct SpatialNode... |
3,209,085 | 3,209,253 | Strange enable_if behaviour using nested classes (MSVC compiler bug or feature?) | After quite some time debugging my code, I tracked down the reason for my problems to some unexpected template specialization results using enable_if:
The following code fails the assertion in DoTest() in Visual Studio 2010 (and 2008), while it doesn't in g++ 3.4.5.
However, when i remove the template from SomeClass or... | Everything is fine with your code, it's just that VC is buggy. It's known to have problems with partial template specialization of template member classes.
|
3,209,205 | 3,209,509 | Is there a way to speed up C++ compilation times in Solaris Sun Studio 12? | Since I am compiling my C++ code on a very server box (32 or 64 cores in total), is there a way of tweaking compiler options to speed up the compilation times? E.g. to tell compiler to compile independent .cpp files using multiple threads.
| Sun Studio includes parallel build support in the included dmake version of make.
See the dmake manual for details.
|
3,209,225 | 3,210,485 | How to pass a method pointer as a template parameter | I am trying to write a code that calls a class method given as template parameter. To simplify, you can suppose the method has a single parameter (of an arbitrary type) and returns void. The goal is to avoid boilerplate in the calling site by not typing the parameter type. Here is a code sample:
template <class Method>... | If your compiler supports decltype, use decltype:
WrapMethod<decltype(&Foo::Bar)> foo_bar;
EDIT: or, if you really want to save typing and have a C++0x compliant compiler:
template <class T> WrapMethod<T> GetWrapMethod(T) { return WrapMethod<T>(); }
auto foo_bar= GetWrapMethod(&Foo::Bar);
EDIT2: Although, really, if ... |
3,209,611 | 3,209,628 | Why doesn't Direct3D have it's own vertex structure? | I've always wondered the reasoning behind why we must always define D3DVERTEX. Is it because Microsoft wants to allow the opportunity to put this in a class and overload operators, or is there another reason?
Thanks
| It's so you can use whatever is convenient for your application. If you need a normal as part of your vertex, you can have that. If you don't need a normal then you save 12 bytes per vertex. If you need colour information, texture coordinates, specular parameters and so on then you choose to define them or not dependin... |
3,209,643 | 3,209,727 | Launching external application and block current application till the launched application quit | I am not sure whether there is a way to
Launch an external application, and block current application till the launched application had quit.
Currently, I am using the following non-blocking method (MFC) to launch
std::string str = "Notepad2.exe";
// Non-blocking. Return immediately.
WinExec(str.c_str(), SW_SHOW);
| ShellExecuteEx with SEE_MASK_NOCLOSEPROCESS will (among other things) give you a handle to the new process. You can do a WaitForSingleObject on that handle, which will be signaled when it terminates. BTW, for a GUI program, this is almost always a bad idea -- making your GUI unresponsive until another program exits is ... |
3,209,646 | 3,209,653 | Does putting data into std::vector in C++ create a copy of the data? | I am interested if creating a new std::vector (or calling its assign method) creates a copy of the data?
For example,
void fun(char *input) {
std::vector<char> v(input, input+strlen(input));
// is it safe to assume that the data input points to was COPIED into v?
}
| Yes. Elements are always copied into or out of STL containers. (At least until move semantics are added in C++0x)
EDIT: Here's how you can test for copying yourself:
#include <vector>
#include <iostream>
class CopyChecker
{
public:
CopyChecker()
{
std::cout << "Hey, look! A new copy checker!" << std::e... |
3,210,178 | 3,210,244 | In Objective-C, How one can forward method to specific super class | All I knew is this: Objective-c allows us to forward method invocation to its super class by
[super method]
However I want forward the invocation to super.super; Skipping the immediately super class.
In c++ we can easily do these by typecasting ((GrandSuper*)object).method().
Is their any provision to do the sam... | It's probably a bad idea to do this, although it is possible. You probably want to think of a better way to achieve whatever you're trying to do.
Let's assume that you have three classes: Cat which inherits from Mammal which inherits from Animal.
If you are in the method -[Cat makeNoise], you can skip -[Mammal makeNois... |
3,210,343 | 3,210,457 | How to Add New Members to Struct | These are functions and Struct declarations I have, and I'm not allowed to change them.
DerivedA giveDerivedA ();
DerivedB giveDerivedB ();
struct Base{
QString elementId;
QString elementType;
};
struct DerivedA : Base {
int a;
int b;
};
struct DerivedB : Base {
int c;
int d;
};
But what I n... | This is similar to the problem people have extending standard library classes. If your base class doesn't have a virtual destructor, you can't safely inherit from it. In that case, you must either use free-functions (preferred anyway), or composition.
Otherwise, what you have there is good.
|
3,210,661 | 3,210,754 | how to get compile warning | I'm quite surprised when I compile the following code without any warning using g++ 4.1.2 with -Wall -Wextra -Wconversion enabled.
I want g++ to show me every warning to avoid potential harm. I have to stick to g++ 4.1.2.
#include <stdint.h>
#include <string>
using namespace std;
int main()
{
uint8_t u1=1;
ui... | I'm afraid GCC before 4.3 doesn't seem to support this. The description of -Wconversion changed between 4.2 and 4.3 to reflect the new warning behavior, and there is no indication that pre-4.3 GCC would check for this.
|
3,210,759 | 3,211,007 | Linux developers knowing C++? | I got into a discussion a while back. The company I work at develop under Linux and does so in ANSI C. A lot of benefits could come from moving to C++ as far as design goes I think. Our existing code would just have to get rid of all implicit type casts since C++ is a bit stricter about that and it would compile and ru... |
A lot of benefits could come from
moving to C++ as far as design goes I
think.
Probably (depends on who would decide on the design in C++).
Our existing code would just
have to get rid of all implicit type
casts since C++ is a bit stricter
about that and it would compile and
run as usual.
It's not that ... |
3,210,781 | 3,212,991 | std::vector<float> and double* - How safe is this? | Is it safe to do this?
double darray[10];
vector<float> fvector;
fvector.insert(fvector.begin(), darray, darray + 10); // double to float conversion
// now work with fvector
VS2008 gives me a warning about the double to float conversion. How do I get rid of this warning? I don't think it makes sense to cast darray ... | Use std::transform() this allows you to provide a conversion method.
Then you just need a conversion method that does not generate a warning:
#include <vector>
#include <algorithm>
#include <iterator>
struct CastToFloat
{
float operator()(double value) const { return static_cast<float>(value);}
};
int main()
{
... |
3,210,927 | 3,211,042 | Usage of namespaces in c++ | Can we use namespaces like in below snippet? The code compiles in both gcc and msvc, leaving me confused about namespace usage.
In f1.h:
namespace My
{
void foo();
}
In f1.cpp
`
void My::foo()
{
}
I thought that the function should be defined as:
namespace My {
void foo() {}
}
Can anyone kindly explain?
Thanks... | It's legal to define namespace members outside of their namespace as long as their name is prefixed with the name of their namespace, and the definition actually occurs in a namespace that encloses it. It can't happen in a namespace that's nested inside the member namespace.
namespace A { void f(); }
void A::f() { } /... |
3,210,958 | 3,211,096 | How is the code memory managed? | When talking about a process' memory, I heard about things like code memory and data memory.
And for the data memory, there are 2 major managing mechanisms, stack and heap.
I am now wondering how is the code memory managed? And who manages it?
Pardon me if my statement is not so clear.
Thanks.
| I recommend http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory (and the other memory related articles) if you're interested in finding out more about the details of process' memory management.
code memory = Text segment
Notice how the address space is 4GB. When the kernel creates a process it gives it... |
3,211,130 | 3,221,954 | lambda expression (MSVC++ vs g++) | I have the following code
#include <algorithm>
#include <iostream>
#include <vector>
#include <functional>
int main()
{
typedef std::vector<int> Vector;
int sum=0;
Vector v;
for(int i=1;i<=10;++i)
v.push_back(i);
std::tr1::function<double()> l=[&]()->double{
std::for_each(v.begin(),v.end(),[&](... | Have you actually tried compiling the code in the question? Visual C++ 2010 accepts the code, as is (with the comment removed, obviously), and successfully compiles the code without error.
The "error" you are seeing is not a compilation error, but an IntelliSense error. The IntelliSense error checking results in a l... |
3,211,214 | 3,212,012 | How to convert a unicode string to its unicode escapes? | Say I have a text "Բարև Hello Здравствуй". (I save this code in QString, but if you know other way to store this text in c++ code, you'r welcome.) How can I convert this text to Unicode escapes like this "\u1330\u1377\u1408\u1415 Hello \u1047\u1076\u1088\u1072\u1074\u1089\u1090\u1074\u1091\u1081" (see here)?
| I have solved the problem with this code:
EDITED TO A BETTER VERSION: (I just do not want to convert Latin symbols to Unicode, because it will consume additional space without and advantage for my problem (want to remind that I want to generate Unicode RTF)).
int main(int argc, char *argv[])
{
QApplication app(argc... |
3,211,269 | 3,211,319 | shared_from_this throws an exception | I am writing Qt-based app with Blender-like functionality. It consists of a 'framework' which is GUI + plugin system and plugins. Plugins are Qt dlls with objects (e.g. a Sphere, a Box, etc.) that can be basically created and displayed. All those objects, once created, are stored in the framework in some kind of a cont... | Perhaps it is this line:
boost::shared_ptr<INode> iNodePlugin = boost::shared_dynamic_cast<INode>(plugin);
Which should be replaced by:
boost::shared_ptr<INode> iNodePlugin = dynamic_cast<INode*>(loader.instance())->shared_from_this();
Maybe it has something to do with:
boost::shared_ptr<QObject> plugin(loader.insta... |
3,211,463 | 3,213,860 | What is the most efficient way to make this code thread safe? | Some C++ library I'm working on features a simple tracing mechanism which can be activated to generate log files showing which functions were called and what arguments were passed. It basically boils down to a TRACE macro being spilled all over the source of the library, and the macro expands to something like this:
ty... | You could implement a configuration file version variable. When your program starts it is set to 0. The macro can hold a static int that is the last config version it saw. Then a simple atomic comparison between the last seen and the current config version will tell you if you need to do a full lock and re-call upda... |
3,211,566 | 3,211,576 | Whats the significance of return by reference? | In C++,
function() = 10;
works if the function returns a variable by reference.
What are the use cases of it?
| The commonest case is to implement things like operator[].
struct A {
int data[10];
int & operator[]( int i ) {
return data[i];
}
};
Another is to return a big object from a class via an accesor function:
struct b {
SomeBigThing big;
const SomeBigThing & MyBig() const {
return big... |
3,211,614 | 3,282,687 | Using openMP in the cuda host code? | It it possible to use openMP pragmas in the CUDA-Files (not in the kernel code)?
I will combine gpu and cpu computation. But nvvc compiler fails with "cannot find Unknown option 'openmp' ", if i am linking the porgram with a openmp option (under linux)
A wayaround is to use openMP-statments only in c/c++ files.
| I've just found this
http://www.cse.buffalo.edu/faculty/miller/Courses/CSE710/heavner.pdf
Page 25 says:
With gcc:
-#include omp.h
Add the -fopenmp flag
With nvcc, this should be -Xcompiler -fopenmp as this needs to be passed directly to gcc
-Xcompiler passes flags directly to host compiler
Add -lgomp flag during the li... |
3,211,678 | 3,211,716 | string contains valid characters | I am writing a method whose signature is
bool isValidString(std::string value)
Inside this method I want to search all the characters in value are belongs to a set of characters which is a constant string
const std::string ValidCharacters("abcd")
To perform this search I take one character from value and search in... | Use find_first_not_of():
bool isValidString(const std::string& s) {
return std::string::npos == s.find_first_not_of("abcd");
}
|
3,211,691 | 3,211,747 | What portable data backends are there which have fast append and random access? | I'm working on a Qt GUI for visualizing 'live' data which is received via a TCP/IP connection. The issue is that the data is arriving rather quickly (a few dozen MB per second) - it's coming in faster than I'm able to visualize it even though I don't do any fancy visualization - I just show the data in a QTableView obj... | I think that sqlite might do the trick. It seems to be fast. Unfortunately, I have no data flow like yours, but it works well as a backend for a log recorder. I have a GUI where you can view the n, n+k logs.
You can also try SOCI as a C++ database access API, it seems to work fine with sqlite (I have not used it for n... |
3,211,761 | 3,211,795 | Situations where "old" C features might be better than newer C++ ones? | Recently i had a discussion with my boss (a long time C developer) who discouraged me in using C++ streams and stick to "good old" printf & friends. Now i can understand why he is saying this and believe me i did not follow his advice.
But still this is bugging me - are there things in C that are still better in some c... | C printf()-style output is typically faster than C++ ostream output. But of course it can't handle all the types that C++ output can. That's the only advantage I'm aware of - typically, because of aggressive inlining, C++ can be a lot faster than C.
|
3,211,771 | 3,211,784 | How to convert int to QString? | Is there a QString function which takes an int and outputs it as a QString?
| Use QString::number():
int i = 42;
QString s = QString::number(i);
|
3,211,794 | 3,211,820 | Unit tests for std::map | Does anyone know where I can find unit tests that will test std::map?
The reason I ask is because I have written a class that acts as a replacment for std::map and has virtually all the same functionality, so unit tests for std::map will be suitable for my class, too.
Of course, I can write my own, but if someone has a... | While i don't know how much is needed to use them stand-alone, you could take a look at libstdc++' testsuite.
|
3,212,058 | 3,212,106 | C++ How to create a heterogeneous container | I need to store a series of data-points in the form of (name, value), where the value could take different types.
I am trying to use a class template for each data-point. Then for each data-point I see, I want to create a new object and push it back into a vector. For each new type, I need to create a new class from t... | The boost library has probably what you're looking for (boost::any). You can roll your own using a wrapped pointer approach if you cannot use boost...
|
3,212,144 | 3,212,318 | Qt moving from LGPL to commercial halfway through | I've never understood this bit about licensing on the Qt website.
Qt Commercial Developer License The Qt
Commercial Developer License is the
correct license to use for the
development of proprietary and/or
commercial software with Qt where you
do not want to share any source code.
You must purchase a Qt Comm... | I believe that the text only refers to code that has already been distributed under LGPL, and therefore cannot be closed-sourced by switching Qt license.
I think you have nothing to worry about: nobody know/cares where the undistributed code you wrote came from (Commercial Qt or LGPL Qt). As long as it hasn't been rele... |
3,212,392 | 3,213,161 | QTreeView, QFileSystemModel, setRootPath and QSortFilterProxyModel with RegExp for filtering | I need to show a QTreeView of a specific directory and I want to give the user the possibility to filter the files with a RegExp.
As I understand the Qt Documentation I can achieve this with the classes mentioned in the title like this:
// Create the Models
QFileSystemModel *fileSystemModel = new QFileSystemModel(this)... | I got a response from the Qt mailing list which explained this issue:
What I think is happening, is that as
soon as you start filtering, the
index you use as your root does no
longer exist. The view then resets to
an invalid index as the root index.
The filtering works on the whole
model tree, not jus... |
3,212,394 | 3,212,413 | Cross-platform compatible directory creation in C++ | I need to dynamically create directory based on input filenames in C++ and it must be cross-platform compatible. I am also familiar with the boost library. The input to the directory creation function will be a string with the following prototype:
void createDirectory (std::string name)
Sample code would be much appr... | If Boost is fine, take a look at create_directory() from Boost.Filesystem.
|
3,212,571 | 3,212,635 | Usefulness of the "inline" feature | There's two things about inlining:
The inline keyword will be ignored if the compiler determines that the function cannot be inlined.
There is a compiler optimization (on Visual Studio, I don't know about GCC) that tells the compiler to inline all functions where possible.
From this I conclude that I never need to bo... | The inline keyword has two functions:
it serves as a hint to the compiler to perform the inlining optimization (this is basically useless on modern compilers, which inline aggressively with or without the keyword)
it tells the compiler/linker to ignore the One Definition Rule: that the inline'd symbol may be defined i... |
3,212,649 | 3,279,075 | How to fill memory fast with a `int32_t` value? | Is there a function (SSEx intrinsics is OK) which will fill the memory with a specified int32_t value? For instance, when this value is equal to 0xAABBCC00 the result memory should look like:
AABBCC00AABBCC00AABBCC00AABBCC00AABBCC00
AABBCC00AABBCC00AABBCC00AABBCC00AABBCC00
AABBCC00AABBCC00AABBCC00AABBCC00AABBCC00
AABBC... | Thanks to everyone for your answers. I've checked wj32's solution , but it shows very similar time as std::fill do. My current solution works 4 times faster (in Visual Studio 2008) than std::fill with help of the function memcpy:
// fill the first quarter by the usual way
std::fill(buffer.begin(), buffer.begin() + bu... |
3,212,704 | 3,212,735 | Will a boost smart pointer help me? | i am using Xerces to do some xml writing.
here's a couple of lines extracted from my code:
DOMLSSerializer *serializer = ((DOMImplementationLS*)implementation)->createLSSerializer();
serializer->release();
Is there a boost smart pointer that i can use, so i can avoid calling serializer->release(); as it's not exceptio... | Yes, smart pointers can call a custom "deleter" function object.
#include <iostream>
#include <tr1/memory>
struct Example {
void release() { std::cout << "Example::release() called\n"; }
};
struct ExampleDeleter {
void operator()(Example* e) { e->release(); }
};
int main()
{
{
std::tr1::shar... |
3,212,813 | 3,213,165 | Ambiguous Class Namespace Issue | I... feel really silly asking this, but I'm not sure how to resolve the problem.
This is a little snippit of my code (Objective-C++):
#include "eq/eq.h"
namespace eqOther
{
class Window : public eq::Window //<-- Error occurs here
{
public:
Window( eq::Pipe* parent ) : eq::Window( parent ) {}
... | Perhaps you have some using namespace eq; somewhere in your headers
|
3,212,925 | 3,213,415 | win32 DialogBox app: how to show text from callback on the DialogBox? | I'm working on a win32 DialogBox based app. This uses DialogBox() to create the dialog box, and has a dialog box procedure which does all the usual things.
The dialog box has some static text controls on it, and generally I'm showing text in these via SendDlgItemMessage() from within the dialog box procedure.
However ... | Well, your dialog HWND is a singleton so it isn't the end of the world. But yes, the standard way this is done is by passing an opaque pointer to the code that gets the job done. Compare with the lParam argument of EnumWindows() for example, the callback gets that pointer back.
Whether a control repaints itself immed... |
3,213,037 | 3,213,261 | Determine if Linux or Windows in C++ | I am writing a cross-platform compatible function in C++ that creates directories based on input filenames. I need to know if the machine is Linux or windows and use the appropriate forward or back slash. For the following code below, if the machine is Linux then isLinux = true. How do I determine the OS?
bool isLinu... | Use:
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
static const std::string slash="\\";
#else
static const std::string slash="/";
#endif
BTW, you can still safely use this slash "/" on Windows as windows understands this perfectly. So just sticking with "/" slash would solve problem... |
3,213,040 | 3,213,148 | Compare unsigned char = 0x00 and signed char = '00' | How do i compare the following:
unsigned char a = 0x00;
char b = '0'; // signed char
how do i write a comparison/conversion that matches a and b?
thanks!
| Like everyone said, they are not the same thing. But if you must compare them equal, you can do that with a lexical cast:
#include <iostream>
#include <boost/lexical_cast.hpp>
bool compare(unsigned char val, char c) // throws if c is not a digit!
{
return val == boost::lexical_cast<int>(c);
}
int main() {
... |
3,213,172 | 3,213,901 | How to do Gtk TextIter arithmetic | I am attempting to use Gtk TextIter objects to lift three-character slices out of a TextBuffer, but am having trouble with the arithmetic. I set up an iterator p to point to the start of the range and want q to point to three characters further on.
I have tried...
q = p + 3; // Doesn't compile
q = p; q += ... | If you read the documentation you'll see that TextIter doesn't have a + or += operator. It's a bidirectional iterator and not a random access iterator so this is as it should be.
You can use either:
q = p;
std::advance(q, 3);
or
q = p;
q.forward_chars(3);
|
3,213,445 | 3,213,458 | C++ double operator+ |
Possible Duplicates:
Incorrect floating point math?
Float compile-time calculation not happening?
Strange stuff going on today, I'm about to lose it...
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
cout << setprecision(14);
cout << (1/9+1/9+4/9) << endl;
}
This code outputs 0 on ... | 1/9 is zero, because 1 and 9 are integers and divided by integer division. The same applies to 4/9.
If you want to express floating-point division through arithmetic literals, you have to either use floating-point literals 1.0/9 + 1.0/9 + 4.0/9 (or 1/9. + 1/9. + 4/9. or 1.f/9 + 1.f/9 + 4.f/9) or explicitly cast one op... |
3,213,571 | 3,214,150 | g++ __FUNCTION__ replace time | Can anyone tell when g++ replaces the __FUNCTION__ 'macro' with the string containing the function name? It seems it can replace it not until it has check the syntactical correctness of the source code, i.e. the following will not work
#include <whatsneeded>
#define DBG_WHEREAMI __FUNCTION__ __FILE__ __LINE__
int main... |
Is there any way to force that replacement with a string to an earlier step so that the line is correct?
No. __FUNCTION__ (and its standardized counterpart, __func__) are compiler constructs. __FILE__ and __LINE__ on the other hand, are preprocessor constructs. There is no way to make __FUNCTION__ a preprocessor cons... |
3,213,591 | 3,213,820 | Rvalues vs temporaries | Somebody generalized the statement "Temporaries are rvalues". I said "no" and gave him the following example
double k=3;
double& foo()
{
return k;
}
int main()
{
foo()=3; //foo() creates a temporary which is an lvalue
}
Is my interpretation correct?
| Temporaries and rvalues are different (but related) concepts. Being temporary is a property of an object. Examples of objects that aren't tempory are local objects, global objects and dynamically created objects.
Being an rvalue is a property of an expression. The opposite of rvalues are lvalues such as names or derefe... |
3,213,738 | 3,213,979 | QThread blocking main application | I have a simple form UI that has a slot for a button, starting a thread:
void MainWindow::LoadImage()
{
aThread->run();
}
And the run() method looks like this:
void CameraThread::run()
{
qDebug("Staring Thread");
while(1)
{
qDebug("ping");
QThread::sleep(1);
}
}
When I click the bu... | Short answer: Start your thread by calling aThread->start(); not run(), and make sure you thread's run() method is protected (not public).
Explanation
Calling start() is the correct way to start the thread, as it provides priority scheduling and actually executes the run() method in its own thread context.
It looks lik... |
3,213,838 | 3,213,858 | C++ member function masking external function - how to call external function? | In a Qt application, I'm trying to call the networking function connect() (which is from sys/socket.h). The call's being made from a QObject object, which has its own connect() member function. The QObject's connect() method is preventing me from calling the networking connect() function.
Any way to use the networking ... |
C++ member function masking external function - how to call external function?
Use
::connect()
|
3,213,954 | 3,214,003 | How to get length of std::stringstream without copying | How can I get the length in bytes of a stringstream.
stringstream.str().length();
would copy the contents into std::string. I don't want to make a copy.
Or if anyone can suggest another iostream that works in memory, can be passed off for writing to another ostream, and can get the size of it easily I'll use that.
| Assuming you're talking about an ostringstream it looks like tellp might do what you want.
|
3,214,168 | 4,701,661 | Linking Statically with glibc and libstdc++ | I'm writing a cross-platform application which is not GNU GPL compatible. The major problem I'm currently facing is that the application is linked dynamically with glibc and libstdc++, and almost every new major update to the libraries are not backwards compatible. Hence, random crashes are seen in my application.
As a... | Specifying the option -static-libgcc to the linker would cause it to link against a static version of the C library, if available on the system. Otherwise it is ignored.
|
3,214,250 | 3,214,349 | Incomplete type as function parameter? | I have that template class that uses a policy for it's output and another template argument to determine the type for it's data members. Furthermore the constructor takes pointers to base classes which are stored in private pointers. Functions of this objects shall take a this pointer to the template class to give them... | If you want to use the ModelCreator with "free" template parameters, then you have to make ShapeGenerator a template too:
template <typename PointData, typename OutputPolicy>
class ShapeGenerator {
public:
void generateShape (ModelCreator<PointData,OutputPolicy>* m) = 0;
};
or
template <template <typename, typena... |
3,214,278 | 3,214,308 | Deriving a pointer type to the non-pointer class member | In book named "Using C++" by Rob McGregor there is following example of using pointer-to-member operator
class mycls
{
public:
int member;
int *ptr;
};
void main()
{
mycls MyClass;
// Derive a pointer type to the non-pointer class member
int mycls::*member = &mycls::member;
MyClass.ptr = new ... | Suppose you had a local variable:
int member;
You could make a pointer to it with:
int *ptr = &member;
To get the pointer to member syntax, we just append mycls:: in the appropriate places:
int mycls::*member = &mycls::member;
It might be clearer with an example that shows how the pointer can switch between any memb... |
3,214,297 | 3,214,332 | How can my C/C++ application determine if the root user is executing the command? | I am writing an application that requires root user privileges to execute. If executed by a non root user, it exits and terminates with a perror message such as:
pthread_getschedparam: Operation not permitted
I would like to make the application more user friendly. As part of its early initialization I would like ... | getuid or geteuid would be the obvious choices.
getuid checks the credentials of the actual user.
The added e in geteuid stands for effective. It checks the effective credentials.
Just for example, if you use sudo to run a program as root (superuser), your actual credentials are still your own account, but your effecti... |
3,214,340 | 3,214,602 | Explain boost::filesystem's portable generic path format in C++ | I am trying to understand portable generic path format and everything is not clicking. Can someone please explain this in terms of examples? I also have been told that I can use the forward slash in windows because windows understands both. Also is it considered good/safe style to use forward slash in windows?
| I think an example is just a/b/c—the portable path format follows POSIX conventions. If you use boost::basic_path, you don't have to care about the correct slashes, the library knows how to convert the portable format to the native format. However, you should always use boost::wpath instead of boost::path, otherwise (I... |
3,214,569 | 3,214,590 | “no match for 'operator<'” when trying to insert to a std::set | I'm using gcc 4.3.3 to try to compile the following code:
struct testStruct {
int x;
int y;
bool operator<(testStruct &other) { return x < other.x; }
testStruct(int x_, int y_) {
x = x_;
y = y_;
}
};
int main() {
multiset<testStruct> setti;
setti.insert(testStruct(10,10));
return 0;
}
... | The operator must be const and take a const reference:
bool operator<(const testStruct &other) const { return x < other.x; }
|
3,214,618 | 3,214,654 | Unresolved external symbol in c++ | #include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
using std::rand;
int man(){
int t=rand();
cout<<t<<endl;
return 0;
}
here is code for generate random number in c++ and i have mistake
1>c:\users\david\documents\visual studio 2010\Projects\random_function\Debug\random_functio... | Me, I think I'd change "man" to "main" and see what happens...
|
3,214,837 | 3,214,941 | C++: Why is the destructor being called here? | I guess I don't fully understand how destructors work in C++. Here is the sample program I wrote to recreate the issue:
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
struct Odp
{
int id;
Odp(int id)
{
this->id = id;
}
~Odp()
{
cout << "Destructi... | This line right here is probably what is tripping you up.
shpoutOdp.reset(iter->get());
What you're doing here is getting (through get()) the naked pointer from the smart pointer, which won't have any reference tracking information on it, then telling shpoutOdp to reset itself to point at the naked pointer. When shpou... |
3,214,880 | 3,214,916 | Non-Integer numbers in an String and using atoi | If there are non-number characters in a string and you call atoi [I'm assuming wtoi will do the same]. How will atoi treat the string?
Lets say for an example I have the following strings:
"20234543"
"232B"
"B"
I'm sure that 1 will return the integer 20234543. What I'm curious is if 2 will return "232." [Thats what ... | You can test this sort of thing yourself. I copied the code from the Cplusplus reference site. It looks like your intuition about the first two examples are correct, but the third example returns '0'. 'E' and 'e' are treated just like 'B' is in the second example also.
So the rules are
On success, the function returns... |
3,215,001 | 3,215,498 | How do I turn relational comparison of pointers into an error? | We've been bitten by the following bug many times:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print(int* pn) { cout << *pn << " "; }
int main() {
int* n1 = new int(1);
int* n2 = new int(2);
int* n3 = new int(3);
vector<int*> v;
v.push_back(n1);
v.pus... | For pointers in general you could do this:
#include <ctime>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <functional>
#include <type_traits>
namespace util {
struct sort_pointers {
bool operator() ( int *a, int *b ) {
return *a < *b;... |
3,215,015 | 3,215,121 | Is there a way to change the delete action on an existing instance of shared_ptr | I have a function where I want a cleanup action done 90% of the time, but in 10% I want some other action to be done.
Is there some way to use some standard scoped control likeshared_ptr<> so that initially it can have one delete action and then later in the function the delete action can be changed?
shared_ptr<T> ptr(... | I don't think you can change the deleter once the shared_ptr was created.
But why would you do that ? Usually, when you create an object, you know immediatly how it must be destroyed. This is not likely to change.
If you really must do some specific treatments, you still can provide a custom deleter which does special ... |
3,215,109 | 3,215,151 | referencing a vector::front works, but vector::begin doesn't | I have this bit of code:
cerr << client->inventory.getMisc().front()->getName() << endl;
vector<itemPtr>::iterator it;
it = client->inventory.getMisc().begin();
cerr << (*it)->getName() << endl;
Let me explain that a bit:
client is a tr1::shared_ptr that points to an object that has a member named inventory that has ... | Exactly what is the signature of getMisc?
If you're actually returning a std::vector<itemPtr> then you are returning a copy of the list. In that case, the first access pattern will work (slowly) because the temporary copy doesn't get destroyed until after front finishes executing, by which time the itemPtr itself is c... |
3,215,221 | 3,215,264 | xor all data in packet | I need a small program that can calculate the checksum from a user input.
Unfortunately, all I know about the checksum is that it's xor all data in packet.
I have tried to search the net for an example without any luck.
I know if I have a string: 41,4D,02,41,21,04,02,02,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,0... | If I understand "xor all data in packet" correctly, then you should do something like this:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
unsigned int data;
vector< unsigned int > alldata;
cout << "Enter a byte (in hex format, ie: 3A ) anything else print the checksum of previous inp... |
3,215,310 | 3,215,366 | Buffer too small when copying a string using wcsncpy_s | This C++ code is kind of lame, but I need to maintain it. I cannot seem to figure out a "buffer too small" problem. I am using Visual Studio 2010. I will come up with minimal code required to reproduce based on the values I see in the debugger. Sorry, I will not have tested the actual snippet itself. Also, since my sys... | The fourth argument to strncpy_s is the number of characters to copy from the source buffer, and it does not account for the terminating null - i.e., in practice, if the source buffer contains a string that has (nIndex - nLast) or more characters, then (nIndex - nLast) will be copied, and then also a null character wil... |
3,215,332 | 3,215,346 | Main only receiving first letters of arguments | int _tmain(int argc, char** argv)
{
FILE* file1=fopen(argv[1],"r");
FILE* file2=fopen(argv[2],"w");
}
It seems as if only the first letter of the arguments is received... I don't get why!
std::cout<<"Opening "<<strlen(argv[1])<<" and writing to "<<strlen(argv[2])<<std::endl;
outputs 1 an... | It's not char it's wchar_t when you are compiling with UNICODE set.
It is compiled as wmain. Linker just does not notice that there is a different signature, because it's "export C" function and it's name does not contain its argument types.
So it should be int _tmain(int argc, TCHAR** argv)
Converting to char is trick... |
3,215,362 | 3,215,387 | C++: Difficulty with partial application | I'm trying to use partial application of function arguments so I can use STL's find_if. Here is a sample program: (Class header and implementation is merged for brevity.)
#include <functional>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
struct Odp
{
int id;
... | bind_1st should be used with functors not member functions.
Functor is an object with overloaded operator().
You can use mem_fn to construct an adaptor around your member function.
In your case, since hasID makes no use of this you could have done with just using a static method. (Then you don't have to bind this as a ... |
3,215,618 | 3,216,005 | The Symbol file MyFile.pdb does not match the module | I've searched on this issue, and found many flavors and ideas but no real solutions. So, donning my asbestos suit and hoping for the best, I'm going to dare ask it again.
I have managed C# code that calls managed C++ code, which in turn calls unmanaged C++ code. The unmanaged C++ code is throwing an exception, and I'... | Might be worthwhile checking the path of the loaded dll - are you using the one you thought you where?
If you are using incremental builds, you might also need idb files
I had an issue where MSVC just didn't want to see any debug symbols at the time, didn't work out why, but instead worked around the issue using CrashF... |
3,215,646 | 3,215,745 | Getting coords from Goocanvas::Points | I'm attempting to get the coordinates from an instance of Goocanvas::Points in goocanvasmm. I have this:
double x = 0, y = 0;
int i;
Goocanvas::Points points;
Glib::RefPtr<Goocanvas::Item> root = canvaswidget.get_root_item();
Glib::RefPtr<Goocanvas::Polyline> line = Goocanvas::Polyline::create(100, 100, 110, 120);
root... | Have you tried this?
points.get_coordinate(i, x, y);
|
3,215,756 | 3,216,156 | operator= in subclass | I'm quite confused about how to solve the following problem (search both on SO and google didn't help much).
Say we have a class defining basic operators and a simple vector as only data and add only additional methods in inherited classes:
class Foo
{
public:
// this only copies the data
Foo& opera... | Martin told you what went wrong, here's what you should do instead:
Bar bar;
Foo& foo = bar; // this works now
Now foo is a reference to a an object, and you can have base class references (and pointers, BTW) refer to objects of derived classes.
However, this
bar = foo;
will never work (at least not implicitly) an... |
3,215,817 | 3,215,892 | Ballistic curve problem | Ok i know this is quite off-topic for programmers but still I need this for app, so here it is:
Ballistic curve (without wind or any other conditions) is specified by these 2 lines:
So, there is a problem that you got 3 unknown values: x,y and time t, but only 2 equations.
You can't really compute all 3 with just the... | You can compute the path of the projectile y(x) by solving one equation for t and substituting into the other. You get
Then finding the landing point is a matter of computing the intersections between that function and the function that defines the height of the terrain. One intersection will be the launch point and t... |
3,216,199 | 3,216,260 | C++: Partial template specialization | I'm not getting the partial template specialization.
My class looks like this:
template<typename tVector, int A>
class DaubechiesWavelet : public AbstractWavelet<tVector> { // line 14
public:
static inline const tVector waveletCoeff() {
tVector result( 2*A );
tVector sc = scalingCoeff();
for(int i = 0; i... | template<typename tVector>
inline const tVector& DaubechiesWavelet<tVector, 1>::scalingCoeff() { // line 30
return tVector({ 1, 1 });
}
That's a definition of a member of a partial specialization that would be defined as follows
template<typename tVector>
class DaubechiesWavelet<tVector, 1> {
/* ... */
const tVe... |
3,216,298 | 3,216,324 | Iterators and multi-dimensional vectors? | So, I am trying to build a two-dimensional vector that will hold indexes for selecting tiles from a tileset.
An iterator in one dimension is simple enough:
std::vector<int> vec;
std::vector<int>::iterator vec_it;
for(int i=5; i>0; --i){
vec.push_back(i); }
//prints "5 4 3 2 1 "
for(vec_it = vec.begin(); vec_it !=... | vec_it->begin() dereferences vec_it, giving you a reference to the vector<int> and then returns the result of calling begin() on that. You shouldn't dereference the result of that using * (doing so dereferences the iterator, yielding the element pointed at by that iterator, which is an int in this case; you want the i... |
3,216,309 | 3,216,396 | Using the "curiously recurring template pattern" in a multi-file program | I'm a pretty novice (C++) programmer and have just discovered the CRTP for keeping count of objects belonging to a particular class.
I implemented it like this:
template <typename T>
struct Counter
{
Counter();
virtual ~Counter();
static int count;
};
template <typename T> Counter<T>::Counter()
{
++co... | I noticed you specifically mentioned declarations and definitions.
Do you have them in separate files?
If so, templates are header only creatures. You'll need to put your definitions in the header file.
|
3,216,400 | 3,217,475 | Is any mainstream compiler likely to support C++0x unrestricted unions in the near future? | I keep looking, but it seems like there's zero interest from compiler developers in supporting these.
To me, it seems odd - basically, current C++ has restrictions on unions that were always an irritation and never appropriate. You'd think that basically removing a few error checks would be a relatively simple way to t... | Near future? I wouldn't count on it. As http://wiki.apache.org/stdcxx/C%2B%2B0xCompilerSupport lays out well, none of the current compilers support it even though many over C++0x features are being implemented.
However as N2544 explains:
The current work-around to the union limitations is to create a fake union using ... |
3,216,462 | 3,222,668 | initializing char arrays in a way similar to initializing string literals | Suppose I've following initialization of a char array:
char charArray[]={'h','e','l','l','o',' ','w','o','r','l','d'};
and I also have following initialization of a string literal:
char stringLiteral[]="hello world";
The only difference between contents of first array and second string is that second string's got... | I might have found a way to do what i want though it isn't directly what I wanted, but it likely has the same effect.
First consider two following classes:
template <size_t size>
class Cont{
public:
char charArray[size];
};
template <size_t size>
class ArrayToUse{
public:
Cont<size> container;
inline ArrayToU... |
3,216,494 | 3,216,755 | Fastest way to do many small, blind writes on a huge file (in C++)? | I have some very large (>4 GB) files containing (millions of) fixed-length binary records. I want to (efficiently) join them to records in other files by writing pointers (i.e. 64-bit record numbers) into those records at specific offsets.
To elaborate, I have a pair of lists of (key, record number) tuples sorted by ke... |
I've tried partially sorting the record numbers by putting the A->B and B->A mappings in a sparse array, and flushing the densest clusters of entries to disk whenever I run out of memory.
it seems that it will incur extremely high syscall overhead.
You can use memory mapped access to the file to avoid syscall overh... |
3,216,805 | 3,226,081 | Help me translate Python code which replaces an extension in file name to C++ | I apologize if you know nothing about Python, however, the following snippet should be very readable to anyone. The only trick to watch out for - indexing a list with [-1] gives you the last element if there is one, or raises an exception.
>>> fileName = 'TheFileName.Something.xMl'
>>> fileNameList = fileName.split('.'... | If you're using ATL why not just use CAtlString's methods?
CAtlString filename = _T("TheFileName.Something.xMl");
//search for '.' from the end
int dotIdx = filename.ReverseFind( _T('.') );
if( dotIdx != -1 ) {
//extract the file extension
CAtlString ext = filename.Right( filename.GetLength() - dotIdx );
if( e... |
3,216,935 | 3,226,644 | Can CMake generate build scripts which do *not* use cmake? | Question: Can CMake generate build scripts that do not, in any way, use CMake? If not, how hard is it to gut a CMake generated automake script to not make any checks against CMake?
I am a big fan of CMake to the point where I am championing the idea that we transition to it in my current work environment. One thing tha... | No, CMake cannot do this. It doesn't really make sense, either, since without any CMake-support at build-time, there would be no way to check or update the makefiles/project-files themselves when the CMakeLists.txt files have changed.
If you are moving from Visual Studio to CMake, you may want to take a look at vcproj2... |
3,216,948 | 3,216,969 | C++ Pass By Const Reference and Return By Const Reference | I'm trying to understand if there is any benefit to returning a const reference. I have a factorial function that normally looks like this:
unsigned long factorial(unsigned long n)
{
return (n == 0) ? 1 : n * factorial(n - 1);
}
I'm assuming that there will be a performance increase when we pass by const reference... | This is invalid. You can't return reference to a local variable.
MSVS C++ compiler even gives the following warning:
main.cc : warning C4172: returning address of local variable or temporary
Not quite sure about GCC, but probably the result would be the same.
|
3,217,004 | 3,242,958 | Shared pointers and building in SIP4 (was: Dynamic casting in SWIG/python?) | So I'm playing about with Python, C++0x, and SWIG 2.0. I've got a header that looks like this:
#include <string>
#include <iostream>
#include <memory>
using namespace std;
struct Base {
virtual string name();
int foo;
shared_ptr<Base> mine;
Base(int);
virtual ~Base() {}
virtual void doit(shared_ptr<Base>... | To (partially) answer my own question, SIP appears to do the right thing, both for the C++ "Derived" class as well as for a Python-level subclass — at least, when I use raw pointers.
Looks like I'll need to figure out how to get it to work with shared_ptrs (looks not quite as easy as %include <std_shared_ptr.i> in SWI... |
3,217,056 | 3,217,069 | ReadFile() Output to WinAPI edit Dialog | Ok, let's see if this all makes sense. Today, as I began working on a small project, I ran into an error I can't seem to get over. The function of the program I am working on is to read data from a pipe (which is the output of another program) and update an HWND ("edit") control dialog using WinAPI. Now, I've been succ... | Check the "Bytes Read" output argument of ReadFile so you know how long the string is, then put a terminating NUL (`'\0') character at that offset.
|
3,217,202 | 3,217,293 | How to look at the data stored in a QMap? | How to look at the data stored in QMap without iterating through it? I am trying to debug an application using QMap with many keys, do you know a way to look at the data in QMap without iterating through each value?
| This will dump the content of a QMap (and other Qt types) to stderr:
qDebug() << yourQMap;
|
3,217,390 | 3,217,430 | clean C++ granular friend equivalent? (Answer: Attorney-Client Idiom) | Why does C++ have public members that anyone can call and friend declarations that expose all private members to given foreign classes or methods but offer no syntax to expose particular members to given callers?
I want to express interfaces with some routines to be invoked only by known callers without having to give ... | The Attorney-Client idiom may be what you're looking for. The mechanics are not too different from your member proxy class solution, but this way is more idiomatic.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.