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 |
|---|---|---|---|---|
5,414,004 | 5,414,166 | OpenSSL Static Library too big, any alternative or way to reduce its size? | I have used pre-build static libs of OpenSSL 1.0, but it makes my binary too big, (increase its size by about 800Kb in release mode).
I do not need most of the feature of OpenSSL such as BIO, I use my own sockets, therefore in the code I am only using a couple of SSL_XXXXXXXXX calls(SSL_accept(3) or SSL_connect(3), SSL... | I think you want this page, particular the section on code size:
https://en.wikipedia.org/w/index.php?title=Comparison_of_TLS_implementations&oldid=585386367#Code_size_and_dependencies
(dated December 2013)
update: Alas no longer a part of the updated page.
|
5,414,063 | 5,414,082 | Is there any default function in C++ to search for a word in a string? | Is there any default function in C++ to search for a word in a string?
| Check out string::find()
|
5,414,115 | 5,414,135 | how my program attaches a running program? like gdb does. in linux | I'm wondering how gdb attaches a running program in linux(*nix)?
I have windows "hook" programming experience.
On windows, I can register a "Hook" to some events of a program(or any program), and when the event occurs(such as mouse click), OS injects my hook-dll into that program's process space and invokes my callbac... | Looks to be through the ptrace() function. Although, I've never played around with it.
|
5,414,186 | 5,414,228 | Error:incompatible types in assignment of 'const char[5]' to 'char[10]' | I have defined c as
char c[][10]
in function definition and used it like c[i]="gray";
Whats wrong? I searched on net, it shows the same syntax.
Thanks.
| You cannot use assignment (=) on an array. If you change c to an array of pointers, that might work, depending on what you need to do with it.
const char *c[20];
c[i] = "gray";
Or if the declared type must be array of arrays, you could use strncpy:
char c[20][10];
strncpy(c[i], "gray", sizeof(c[i]));
|
5,414,210 | 5,414,255 | Class definition within namespace goes out to lunch, never returns | I have the following:
namespace A {
/* Class prototype */
class B {
private:
type member_1;
public:
return_type member_2( arguments );
};
}
Later on (in another file that includes the file with the above block), I do the following:
namespace A {
/* Function prototype */
B function_name( arguments ); /* ... | It'd be really helpful if you showed us the actual code that doesn't work.
From the code you have provided and the error I have a couple guesses:
You reused A as a class or variable.
There's broken code before the namespace A in "later".
You're passing parameters that you aren't showing and they're declared with unkno... |
5,414,313 | 5,414,363 | C/C++ Hook to access the window's elements of a program | I'm trying to access window's elements of a program, of which I have only the binaries and installed stuff.
For example, I want to click on a certain item of a certain listbox in an automated way.
I'm only interested in accessing one listbox of one window of the program, but this would help me create a very good macro... | You may be able to use Spy++ to find the specific class and/or caption for the window (the listbox control) and then target it via FindWindow().
If not, you'll have to find the app's main window, and traverse its children, looking for the children of the children until you find the listbox window.
Once you finally have... |
5,414,511 | 5,414,529 | Why does the standard C++ library use all lower case? | Just curious why the C++ standard library uses all lower case and underscores instead of camelCase or PascalCase naming convention.
Personally, I find the latter much easier to deal with when typing out code, but is there some kind of legitimate reason to use the former?
| Main reason : To keep compatibility with the existing code, since they have done it with C also.
Also have a look at these C++ Coding standards, which presents some generic reasoning regarding the importance of convention.
These links discusses about the naming conventions of C/C++ Standard Library.
Naming Convention... |
5,414,546 | 5,414,571 | MSVC++ handling unsigned long long int | I'm having an issue with the way MSVC handles unsigned long long integers. Here's code to reproduce:
// test.cpp (note extension)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
unsigned long long int address = 0x0A0B0C0D0E0F;
printf("Address=%llu\n", address);
printf("%02X:%02X:%... | The %X format specifier expects a 32-bit argument. You are passing 64-bits, throwing off the stack. You can use %llX. The CRT is the same for C and C++ code.
|
5,414,619 | 5,414,644 | Boost C++ macro argument count error | In the following piece of code:
BOOST_FOREACH(std::pair<PID, bool> &itval, completedEs_) {
allCompleted &= it->second;
}
I'm getting this error:
error: macro "BOOST_FOREACH" passed 3
arguments, but takes just 2
I'm only passing 2 arguments, what's going on?
| The first type is being parsed as two arguments since it contains a comma.
As a workaround you could typedef the type:
typedef std::pair<PID, bool> PID_bool_pair;
BOOST_FOREACH( PID_bool_pair &itval, completedEs_) {
...
}
|
5,414,741 | 5,414,781 | 'CObject::CObject' : cannot access private member declared in class 'CObject'd:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxcoll.h | This error happens while trying to send the instance of CTypedPointerList in the function parameter from one class to another class.
How to solve this issue?
Here is my code
ObjectList.h
#pragma once
#include "LogData.h"
typedef CTypedPtrArray<CPtrList , CLog *> CLogData;
class CObjectList
{
public:
CLogData m_l... | I'd need to see your code to be sure, but it looks like you're trying to pass the CTypedPointerList by value. This means a copy of the instance needs to be created, thus the implicit call to the copy constructor. The authors of CTypedPointerList have marked the copy constructor private in order to indicate that copie... |
5,414,775 | 5,415,982 | Time Complexity of the following code..? | I am confused with the time complexity of the following piece of code....
i = 0
//first row
if(board[i][0] == win && board[i][1] == win && board[i][2] == win)
return win;
//second row
if(board[i+1][0] == win && board[i+1][1] == win && board[i+1][2] == win)
return win;
//third row
if(boa... | This is obviously a trap question to see if you understood the concept of time complexity.
Time complexity measures the order of magnitude that an algorithm needs if applied to larger and larger input. Your example does depend only on a constant number of inputs, this why the others correctly said O(1). In essence this... |
5,414,782 | 5,414,830 | What is the name of the linux API that hints sequential or random access read? | There is an API call under linux that I forgot the name of.
You can essentially hint to the system how you'll be mostly accessing the file and it'll tune performance accordingly.
Can anyone recall the api function?
| Are you looking for posix_fadvise()?
|
5,414,849 | 5,421,472 | Initializing static const in a class that extends a template | Consider this pseudocode:
class Foo {
public:
virtual int getID() const = 0;
}
template<typename T>
class Blah : public Foo {
public:
T data;
static const int ID; //static ID
int getID() const { return Blah<T>::ID; } //instance returns the ID
}
class Dude : public Blah<int> {
}
int Dude::ID = 10; /... | I found this answer that does exactly what I'm after...sorry if my question was confusing.
in C++, how to use a singleton to ensure that each class has a unique integral ID?
|
5,414,969 | 5,414,998 | Shortest path program | I want to write a shortest path program. I know how the algorithm works, but I don't know where to start
Initially, I thought of using an adjacency matrix but then decided against it because of space. Now I think adjacency list would be better.
Can anyone suggest me a websites or tutorials how to start writing adjacen... | You might start with Boost::Graph, which will provide you both mechanisms for storing graph data and a structure for writing an algorithm that consumes that data.
|
5,415,064 | 5,415,403 | Error : 'CPtrList::AddTail' : 2 overloads have no legal conversion for 'this' pointer | How to overcome this?
Here is my code
Here is my code
ObjectList.h
#pragma once
#include "LogData.h"
typedef CTypedPtrArray<CPtrList , CLog *> CLogData;
class CObjectList
{
public:
CLogData m_logData;
public:
CObjectList();
CLogData GetLog();
};
ObjectList.cpp
#include "stdafx.h"
#include "LogData.h"
... | It is very hard to tell, seeing as your post is very disjointed.
The error message sounds like one you get when you try to violate const-ness.
e.g.
class C
{
public:
void a();
void b() const;
};
void func()
{
C c0;
c0.a(); // OK
c0.b(); // OK
const C c1;
c1.a(); // violates const-ne... |
5,415,115 | 5,415,170 | How to make C++ pointers null | While declaring all c++ pointer, all should by default be initilized to ZERO or NULL to avoid any random unwanted values. So that we can check if pointer is null that means not initilized.
thanks
| In C++03, prefer ptr = 0 over ptr = NULL (Bjarne S. says that. Read the excerpt below quoted from his site)
In C++0x, ptr = nullptr (see this)
Bjarne Stroustrup says that,
Should I use NULL or 0?
In C++, the definition of NULL is 0,
so there is only an aesthetic
difference. I prefer to avoid macros,
so I use 0. Anoth... |
5,415,302 | 5,415,350 | Initialize C++ pointers to ZERO after we delete? | In C++ we use delete operator to delete objects most of the time.
The delete doesn't make pointer value NULL. Is there any way this can be achieved automatically?
e.g.
int *p = new int;
delete p; // this should deallocate object pointed by p
// and also initialized value of p = NULL
| It is simple to write one like this:
template<class T>
void safe_delete(T*& p)
{
delete p;
p = NULL;
}
int main()
{
int* p = new int;
safe_delete(p);
double* p1 = new double;
safe_delete(p1);
}
Be careful not to use this with arrays though :)
|
5,415,436 | 5,415,914 | need single header file for boost::shared_ptr | Boost::shared_ptr is really great. But using it you need lots of header file. Is thare any single header file available that will provide shared_ptr functionality?
somewhat urgent.
| gcc -E boost/shared_ptr.hpp -o my_shared_ptr.hpp
Using the preprocessor, you generate a single header containing everything you need.
|
5,415,726 | 5,416,283 | How I can create for my application one's own instance excel and use it? | How I can create for my application one's own instance excel and use it ? Now I have com error when i call CreateInstance and there is a excel instance in process. I want to use for my application the global handler of excel instance and kill it when my application will be close
| Excel allows multiple instances. The following code works with multiple instances (XL, XL1). And it works even if you previously start Excel manually. Would you show a code sample to clarify your question.
#import "C:\Program Files (x86)\Common Files\microsoft shared\OFFICE12\mso.dll"
#import "C:\Program Files (x86)\Co... |
5,415,736 | 5,415,802 | How does delete work? |
Possible Duplicate:
C programming : How does free know how much to free?
How does delete know how many bytes it has to free?
I read that there is some block before the actual pointer address that is returned by new which contains block address details.
Anyone here who knows how many bytes this block has or how the... | In general, this is implementation-dependent.
The way this is usually implemented is that new/malloc will allocate slightly more bytes than you asked for, and will use the extra bytes for some book-keeping: many times the allocated blocks will also be maintained in a linked-list, and so the extra bytes will be used to... |
5,415,752 | 5,415,810 | How to save string (username password) in encrypted form in database, and decrypt when, login by user | Good morning all,
I am using c++ and also using wxWidget, In backend i m using MySql, i want to save user name and password in encrypted form inside the database,
when user will try to login,I will decrypt the data for authentication,
Is there any headerfiles in c++ who can handle encryption or decryption?
| Don't encrypt the password, you don't want people's passwords to be recoverable. If they forget them then reset the password to something else. Don't ever store passwords or encrypted passwords which can be used to get the original password.
What you should do is:
Generate random salt.
Append or prepend the salt value... |
5,415,801 | 5,415,856 | C++ abstract class problem | I have an abstract class defined as follows:
class AnimatedDraw
{
public:
virtual void Draw(sf::RenderWindow &window) = 0;
virtual void Draw(sf::RenderWindow &window, sf::Shader shader) = 0;
virtual void Update(sf::Clock &time) = 0;
};
I'm trying to inherit from it into another class defined as follows:
cl... | Apparently it doesn't support explicit. It's fine because it probably won't go to the standard.
|
5,415,818 | 5,415,892 | Does this snippet of code(a macro for container traverse) works? if yes, why? | Following Dmitry Korolev tutorial on TopCoder i encountered this generic-container-traverse macro:
#define tr(c,i) for(typeof((c).begin() i = (c).begin(); i != (c).end(); i++)
It confuses me because it appears to be missing a parenthesis. And in the explanation he says that typeof(...) is replaced by the type of the ... | #define tr(container, it) \
for(typeof(container.begin()) it = container.begin(); \
it != container.end(); \
it++
)
This is what he has written which is syntactically correct. BTW typeof is a gcc extension and won't work in other compilers.
If your ... |
5,415,996 | 5,416,015 | GetModuleFileName returns path in 8.3 format | I call this function to get path to exe. GetModuleFileName(NULL, ...
The problem is that sometimes it returns the short path (8.3) instead of a normal long path.
MSDN specifies that
The string returned will use the same format that was specified when the module was loaded. Therefore, the path can be a long or short ... | You cannot avoid it - if the dll is loaded with a short name, that's what you get.
Use GetLongPathName to convert if needed.
|
5,416,048 | 5,416,066 | C++ why is my class still abstract? | I'm sure its something simple on my part, but I can't figure out why my compiler thinks one of my classes is abstract. Here's the situation:
I have an abstract base class like so:
class AnimatedDraw
{
public:
virtual void Draw(sf::RenderWindow &window) = 0;
virtual void Draw(sf::RenderWindow &window, sf::Shader... | Your base class declaration doesn't have an ampersand after sf::Shader:
virtual void Draw(sf::RenderWindow &window, sf::Shader shader) = 0;
The derived class has, hence it's a different overloaded function.
|
5,416,107 | 5,416,132 | Initialising an array in a class in C++ | I am writing a class for a stack with 4 elements. Defined like this:
// HPStack.h
class HPStack{
public:
HPStack();
void push(int x);
int pop();
int peek();
private:
int stack[];
};
// HPStack.cpp
HPStack::HPStack(){
int stack[4] = {0,0,0,0};
}
// push/pop functions
//... | HPStack::HPStack(){
int stack[4] = {0,0,0,0};
}
Here, stack is declared as a local variable. If your class has a member variable also called stack then it is not initialized and not visible in the constructor because it has been hidden.
If you want to zero-initialized a member array, you can value-initialize i... |
5,416,127 | 5,419,118 | QGraphicsView scroll problem | I have the following situation here: I do some drawing on a graphics scene, in one type of central widget, and some times this also involves scrolling the scene. Then the user clicks somewhere else in the application, the central widget is changed to something else (and the graphic views' scroll bar positions are saved... | If the scene rect changes after user edit, the saved scroll position will no longer be valid since the new min/max are now different.
Recentering the scene may be a better solution:
QPointF center = my_qgv->viewPort().rect().center();
center = my_qgv->mapToScene(center);
...
// user edit; reconstruct scene
//
my_qgv->c... |
5,416,143 | 5,416,493 | How to know library is debug library or release? | I am using mysql cpp library .
I checkout the recent copy from there bzr trunk and
used cmake to generate library .
First time I used release mode and second time I used debug mode to build.
The both library have
a mysql_debug.cpp
U mysql_debug
Is there a way to check in program (C or C++ code) or using nm that li... | I have seen false negatives with nm so I do not trust it. When I want to check to see if an object file has debug info I run objdump -x on the object file or library and look to see if there are headers that say dbg, stabs, or dwarf. This is not the most elegant solution by any means, but it has never been wrong and ... |
5,416,368 | 5,417,057 | How to wrap multithreaded C++ library using Python C/API? | This is a somewhat long question, but I hope I can express it clearly.
I am trying to wrap a C++ library using Python/C API. The main library, say, mylib, has its own object system (it is something like an interpreter for another language ) and uniquely identifies each object in its environment by an Id. It creates mul... | From your description it doesn't really sound like a threading issue at all: you claim you define the Dummy class without using the Python API, but that would mean Dummy instances are not PyObjects, so the reinterpret_cast will do the wrong thing. You can't create PyObjects by just instantiating a C++ class; you need t... |
5,416,405 | 5,443,586 | New class member of static library missing after compilation | Good morning,
I´m facing a very strange problem on which I haven´t found a solution yet.
I hope someone could give me a clou.
I´m having a class compiled to a static lib.
I´m using this class in a simple console program to perform tests on that class.
The class worked like a charm until I added a new data member (std:... | thx to everybody who were spending time thinking about my problem.
Anyway - i solved it last night.
When I created the test program I was a lazy fool it seems.
Instead of including the original header, I copied it to the test project.
Don´t know what got into me that eve.
Sorry for wasting your time!
Regards,
Phil
|
5,416,513 | 5,416,764 | Why is deleted memory unable to be reused | I am using C++ on Windows 7 with MSVC 9.0, and have also been able to test and reproduce on Windows XP SP3 with MSVC 9.0.
If I allocate 1 GB of 0.5 MB sized objects, when I delete them, everything is ok and behaves as expected. However if I allocate 1 GB of 0.25 MB sized objects when I delete them, the memory remains ... | I cannot positively state this is the case, but this does look like memory fragmentation (in one of its many forms). The allocator (malloc) might be keeping buckets of different sizes to enable fast allocation, after you release the memory, instead of directly giving it back to the OS it is keeping the buckets so that ... |
5,416,721 | 5,416,755 | Visual C++ Project type for Windows Service that calls the WinAPI directly | I want to create a Windows Service using the Windows API (no .NET, no ATL/COM). What kind of project do I have to create in Visual C++ 2010?
| "Win32 Console Application" or "Win32 Project" - then deal with the service setup/control code yourself.
See Writing a Service Program's main Function
|
5,416,800 | 5,416,814 | How can I add boost threads to a vector | I have something like this that is incorect:
vector<boost::thread> vec;
for(int agent = 1; agent <= numAgents; ++agent)
{
boost::thread agentThread(sellTickets, agent, numTickets/numAgents);
vec.push_back(agentThread);
}
Maybe i should add pointers to boost::thread in the vector, but then I don't know how to a... |
You must have a compiler with move-semantics supported in order to make your code work,
or use vector<shared_ptr<boost::thread>> with code like:
vec.push_back(make_shared<boost::thread>(sellTickets, agent, numTickets/numAgents));
or use boost::thread_group.
|
5,416,872 | 5,416,981 | Using export keyword with templates | As i Understand "export" keyword can be used so that one can expose template classes or function signatures through an header file and abstract the actual implementation in a library file.
Can anyone please provide a practical sample program which shows how to do this?
Are there any disadvantages or important points to... | Attention: This answer is about the historical use of export pre-C++20; C++20 repurposes the keyword for use in modules.
First of all: most compilers (including gcc, Clang and Visual Studio) do not support the export keyword.
It has been implemented in a single front-end: the EDG front-end, and thus only the compilers ... |
5,416,934 | 5,417,514 | C++ file operations cause "crash" on embedded Linux | I'm in a embedded led measuring system project now. It uses ARM & linux, and has 64M memory and 1G storage. When measuring, it's supposed to write data to a .csv file. I did it this way:
Create/open a file before measurement begins
In the measuring loop, when data is ready, put it into the file, then go to next measur... | You write to 'out_put', the ofstream, but never check if the stream is still valid.
You could change it to
while (out_put.good() && (!userStoped())
To prove to yourself that it is the writing to a stream which is causing the problem, comment out all of the measuring code, just write lots of 'x' (or your choice of c... |
5,416,960 | 5,416,997 | reference to array, not quite working as intended | Greetings,
Since my last question about C++, I actually learned quite an amount. I am now comfortable with classes, just not so comfortable with pointers and references yet.
Please note, I am not asking you nesceserally to solve my problem, I'm asking why I'm not getting the wished result.
here are some code snippets t... | Your condition boils down to this:
if((board[move] != 'X') || ('O'))
'O' will always evaluate to true in this case, so you always pass the condition. What you want is this:
if((board[move] != 'X') && (board[move] != 'O'))
To verify, this code runs fine for me:
#include <iostream>
bool validateMove(const char (&board... |
5,416,985 | 5,417,102 | Cannot find boost library | This is a very basic question, I only post because I've spent already some time into it. This is what I've done so far:
Downloaded and compiled the boost library:
sudo ./bootstrap.sh and sudo ./bjam install
This way it was installed into /usr/local/lib.
In my source code I've added only:
#include <boost/asio.hpp>
usi... | Did the ./bjam install tool also run the ldconfig(8) tool? ldconfig(8) needs to be run after new libraries are installed to update the caches used by ld.so(8) at program execution time.
|
5,417,201 | 5,417,617 | Qt place new window correctly on screen, center over mouse, move into screen | After many months of trying, searching, reviewing code, etc. I'm unable to find a solution to properly positioning a new window in QT. In my most basic case I simply want to get the final size of the window and center it under the mouse. It will be shifted to ensure that no part of the window is outside of the screen. ... | Edited to look more scientific: I have changed the arbitrary number of calls to
processEvents with a loop that checks the return value.
Edited again: It seems that the new version is not safe: it can get stuck in the loop. So I've put a limit in the number of iterations.
Original:
Tell me about it. If I may be permitte... |
5,417,215 | 5,417,289 | function template specialization compile error | ##A.hh
template<class T> void func(T t) {}
template<> void func<int>(int t) {}
void func2();
##A.cpp
void func2() {}
##main.cpp
func("hello");
func(int());
The error I get is: error LNK2005: "void __cdecl func(int)" (??$func@H@@YAXH@Z) already defined in A.obj,
one or more multiply defined symbols found
Is a f... | As template<> void func<int>(int t) {} is a function overload rather than a function template (i.e., all types are known at the point of definition so it is no longer a template), it must be marked as inline or defined in a .cpp file to avoid multiple definition errors, just as with any other function definition.
|
5,417,283 | 5,417,380 | suitable I/O model for the application which maintain 1000 TCP connection | I am working on Gateway Simulator which can simulate 1000 gateway.Gateway is connected with the data center and client app is connected with the data center.
Gateway
Stream the video to data center for playing or recording
Respond with status info about sensor connected with gateway
Other status information of the gat... | The C10K problem discusses this in great detail and should be enough to get you an understanding of what's involved in accepting a large number of connections.
|
5,417,453 | 5,417,495 | Capturing dns requests | How it is possible to capture dns requests, just requests, I don't need anything else. What library (c++) is best for this?
| libpcap is the most popular and best-supported network packet capture library I know; it supports easy query strings like udp port 53.
|
5,417,523 | 5,417,795 | How to interfere other windows program (with C#, C++ or Java) | Sorry for the unclear title,but my english is not good enough to describes my question in one line.
For example, i have a udp gaming program called Garena,its halt user for 5s after every attemp to join room (by some client-code i guess),therefor i downloaded another program which called Garena Auto-joiner(C++) ,this p... | There's a lot of ways to interfer with other programs. For some samples:
DLL Injection - using one of several methods
Packet Injection - for networked programs
Windows Debug API
Code Injection - modifying the running program
|
5,417,644 | 5,417,819 | tinyxml c++ using TiXmlText in storing integer data | as per the class reference the TixmlText takes const char* values as input.
i need to store integer data read from a text file into xml. the integer data is stored in int vector and each element of the vector is converted to const char* before passing it to Tixml text function.
const char* intToXmlChar(int num)
{
... | If you're compiling TinyXML with STL support (which you probably should be) TiXmlText also has a std::string constructor. As sekmet64 says, the memory allocated by the std::string for c_str() is released when the function exits so you are, in effect, returning a pointer to garbage.
However, I would strongly recommend a... |
5,417,752 | 5,417,955 | Differentiate between a number (of type double) with decimal places and one without - c++ | I am trying to implement a simple decimation algorithm in c++. I have two arrays, say p & q, where the subscripts are related to each other by the following relation:
p[k] = q[0.5*k]. This means that the following sequence should hold valid:
p[0] = q[0]
p[1] = 0
p[2] = q[1]
p[3] = 0
p[4] = q[2]
and so on... | Presuming that the coef can be anything else,
p[floor(coef*k)] = (fabs(coef*k-floor(coef*k))<1E-6)?q[k]:0;
|
5,417,829 | 5,431,387 | How can C++ virtual functions be implemented except vtable? |
Possible Duplicate:
A question about virtual mechanism in C++
Is using vtable the only way to implement virtual member functions mechanism in C++? What other ways exist?
| Another known mechanism is type dispatch functions. Effectively, you replace the vtable pointer by a typeid (small enum). The (dyanmic) linker collects all overrides of a given virtual function, and wraps them in one big switch statement on the typeid field.
The theoretical justifcation is that this replaces an indirec... |
5,417,835 | 5,417,876 | how to modify the number of parallel compilation with Xcode | How to change the number of parallel compilations when building a C++ project with XCode ?
I am not talking about distributed builds, but on simultaneous compilations of a set of source files from a single project, on a single computer.
(currently using Xcode 3.2.4)
Thanks
| Adjust the PBXNumberOfParallelBuildSubtasks user default, for example:
defaults write com.apple.XCode PBXNumberOfParallelBuildSubtasks 6
|
5,417,992 | 5,419,865 | Automatic / templated generation of test vectors in C++ | I want to find a good way to generate test vectors automatically. By way of example, I am testing an audio processing module by calling a function that exercises the module-under-test with the specified test vector and in doing so makes various checks for proper operation and correctness of module output.
void runTe... | It was very tempting to think a bit about this very programmer-friendly task :)
Here I came with dynamic solution using boost::any as the medium to store "erased" types in.
More static solution would use probably Boost.Tuple and Boost.Fusion/Boost.MPL indeed, but I'm not sure it is worth the trouble.
The code is protot... |
5,418,137 | 5,418,229 | C++ compatibility between Visual Studio and gcc under Linux | I am trying to build a project written in VS 2008 using QtCreator under Linux and I get loads of errors:
/home/ga/dev/CppGroup/MonteCarlo/main.cpp:1: error: stray ‘\377’ in program
/home/ga/dev/CppGroup/MonteCarlo/main.cpp:1: error: stray ‘\376’ in program
/home/ga/dev/CppGroup/MonteCarlo/main.cpp:1: error: stray ‘#’ i... | That looks like a UTF-16 BOM for little-endian UTF-16. You need to make sure the file is saved as UTF-8 or convert it manually via iconv -f UTF-16LE -t UTF8 myfile.
|
5,418,306 | 5,418,344 | C++: how do I assign values to a list of vectors efficiently? | Reading this question, I've decided I need to use something like this:
list<vector<double> > psips;
for a simulation in c++. The question is, what is the simplest (and a reasonably efficient) way of initiating a list like this containing N vectors with d zeros in each?
Cheers!
| std::list<std::vector<double> > psips(N, std::vector<double>(d));
See #3 here and #2 here.
|
5,418,557 | 5,425,754 | How can I make Visual Studio save all files as UTF-8 without signature on Project or Solution level? | I am trying to configure a VS c++ project in a way that it can be compiled by gcc in Linux. It seems that I need the files to be encoded as UTF-8 without signature (which is not the default). Is it possible to set something on the project or solution level, so that after someone opens the solution and saves their chang... | Visual Studio will remove the BOM by going to Save As... and selecting "Save With Encoding..." and selecting "UTF-8 without signature". Once it is saved without the BOM, VS will not add it again. Unfortunately, there is no way to make this default for all files in VS and must be done manually each time a file is saved ... |
5,419,016 | 5,419,202 | String class allocating on stack for small strings? | Do anyone know if there is a STL interface compatible string class that allocates memory for small strings on the stack (up to a certain threshold) and the heap for larger strings ?
I'm looking to optimize a program and I'm using allot of small local strings that easily could fit on the stack, instead of being allocate... | You can provide a custom allocator for std::basic_string (it is the third template argument). This answer explains how use that and links to an implementation of a stack-allocator that can be used.
|
5,419,356 | 5,419,388 | redirect stdout/stderr to a string | there has been many previous questions about redirecting stdout/stderr to a file. is there a way to redirect stdout/stderr to a string?
| Yes, you can redirect it to an std::stringstream:
std::stringstream buffer;
std::streambuf * old = std::cout.rdbuf(buffer.rdbuf());
std::cout << "Bla" << std::endl;
std::string text = buffer.str(); // text will now contain "Bla\n"
You can use a simple guard class to make sure the buffer is always reset:
struct cout_... |
5,419,369 | 5,419,402 | str.find() seems to be ignoring the first character in a string | In the application where the complete code is
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Insert";
int kint = 0;
if (kint == 0 && str.find("Insert"))
{
cout << "found" << endl;
}
return 0;
}
No cout ever occurs. If you search for "nsert" instead... | You're missing the fact that when find doesn't return anything, it returns npos not zero. A return value of 0 means that it found what it was looking for at index 0.
if (kint == 0 && str.find("Insert) != string::npos) { ... }
[NOTE: for about 15 seconds this answer claimed, wrongly, that str.find() returns str.end() o... |
5,419,493 | 5,419,616 | Is there any C/C++ system() function accepting unicode? | Question: In C/C++, is there any system function that accepts Unicode ?
See below for reason:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
// http://stackoverflow.com/questions/3313332/bringing-another-apps-window-to-front-on-mac-in-c
system("osascript -e \"tell application \\\"Ad... | system() does not care about the encoding as far as I know, it should just pass it through.
maybe your question is "how to type a UTF-8 string literal in C", or "what encoding does osascript expect"?
the portable way to do UTF-8 in C is with \x escape sequences, though if you are willing to rely on C99 or a specific co... |
5,419,670 | 5,419,786 | Inner class depending on a template argument | Consider next example :
#include <iostream>
#include <typeinfo>
template< int N, typename T >
struct B
{
struct C;
};
template< typename T >
struct B< 0, T >::C
{
typedef T type;
};
template< int N, typename T >
struct B< N, T >::C
{
typedef T type[N];
};
int main()
{
std::cout<<"n=0 type = " << t... | You can't define C outside B this way - C doesn't exist for the B specialization you're creating. If you want to specialize B::C, you need to specialize B. Are you trying to do the following?
template< int N, typename T >
struct B
{
struct C {
typedef T type[N];
};
};
template< typename T >
struct B< 0... |
5,419,698 | 5,420,308 | What alternative syntax exist for C/C++? (think SPECS or Mirah) | I wondered if there are any simpler or more powerful syntax for C or C++. I have already come across SPECS. That is an alternative syntax for C++. But are there any others and what about C?
It could also be a sort of code generator so that things like functors could be defined less verbosely. I imagine it could be made... | The only general-purpose tool that I'm aware of is Lazy C++, which lets you create a single .lzz source file from which it can generate the .h and .cpp files.
There are also numerous approaches to doing code generation for C++. (For examples, see Cog, Pump, or Wikipedia's list.) These aren't full-fledged alternate sy... |
5,419,740 | 5,419,789 | Which is the better practice: global constant or #define? |
Possible Duplicate:
C++ - enum vs. const vs. #define
Before I used #define I used to create constants in my main function and pass them where they were needed. I found that I passed them very often and it was kind of odd, especially array sizes.
More recently I have been using #define for the reason that I don't hav... | They don't do quite the same thing. #define lets you affect the code at compilation time, while global constants only come into effect at runtime.
Seeing as #define can only give you extra trouble because there's no checking going on with how you use it, you should use global constants when you can and #define when you... |
5,419,992 | 5,421,034 | What factors should I consider when choosing between C# and C++ for an image-processing project? | I want to develop some image processing code and I am wondering if there is a big difference between developing them in C++ and C#?
Is there any detail document that explains what is good to implement in C# and what is good to implement in C++?
As far as I know, since C# code are compiled to machine code just before ru... | .NET IL is compiled to machine code, just as C++. But almost always the C++ code will be faster, because:
The compilation time becomes part of the runtime (once only, but sometimes this is an issue)
JIT-compilers spend less time on optimization than AOT-compilers, for the reason mentioned above. Therefore the code gen... |
5,420,171 | 5,420,237 | Make a variable unavailable in portion of codes | From time to time, I want, as a safety check, to check that a variable v is not used in some portion of code, or in the remainder of some function, even though it is still visible in the scope of this function/portion of code. For instance:
int x;
// do something with x
DEACTIVATE(x);
// a portion of code which should... | The best way to achieve this is to actually have small scopes in your code, i.e. use short, focused methods which do one thing only. This way you tend to have few local variables per each individual method, and they go out of scope automatically once you don't need them.
If you have long legacy methods which make you w... |
5,420,317 | 5,420,568 | Reading and writing binary file | I'm trying to write code to read a binary file into a buffer, then write the buffer to another file. I have the following code, but the buffer only stores a couple of ASCII characters from the first line in the file and nothing else.
int length;
char * buffer;
ifstream is;
is.open ("C:\\Final.gif", ios::binary );
// ... | If you want to do this the C++ way, do it like this:
#include <fstream>
#include <iterator>
#include <algorithm>
int main()
{
std::ifstream input( "C:\\Final.gif", std::ios::binary );
std::ofstream output( "C:\\myfile.gif", std::ios::binary );
std::copy(
std::istreambuf_iterator<char>(input),
... |
5,420,361 | 5,420,394 | Create a file C++ (cross-platform solution for Unix and Windows) | Is there a way from C++ code to use (fstream, FILE, etc.) to create a file on both Unix and Windows?
If not what you can do in order to have your code run on both Unix and Windows?
| ofstream out(path);
or
FILE *fp = fopen(path, "w");
will create the file path if it does not exist.
|
5,420,597 | 5,420,755 | Strange problem with std::cout | I have 2 loops:
//Loop 1
for ( vector<string>::iterator iter = vecv.begin() ; iter != vecv.end() ; iter++)
{
cout << "-----IN LOOP----" << *iter;
}
//Loop 2
for ( vector<string>::iterator iter = vecv.begin() ; iter != vecv.end() ; iter++)
{
cout << "-----IN LOOP----" << *iter << endl ;
... | How do you know it doesn't print anything without endl? By observing running program? If so, the problem is that cout provides buffered output: it actually prints somehting on the screen (or in the file) only when its buffer is full.
endl on other hands flushes the buffer.
If you want unbuffered output you can use cerr... |
5,420,647 | 5,420,734 | Compilation and execution time of C++ vs C source code | I am not sure if this is a valid comparison or a valid statement but over the years I have heard folks claiming that the programs written in C++ generally take a longer time for compilation than the same written in C and that the applications coded in C++ are generally slower at run time than ones written in C.
Is ther... | I'll answer one specific part of the question that's pretty objective. C++ code that uses templates is going to be slower to compile than C code. If you don't use templates (which you probably will if you use the standard library) it should be very similar compilation time.
EDIT:
In terms of runtime it's much more subj... |
5,420,916 | 9,830,673 | How to throw an exception by its run-time type? | I want to call a function that may throw an exception. If it does throw an exception, I want to catch it and pass the exception object to a handler function. The default implementation of the handler function is simply to throw the exception. Here is whittled-down code to illustrate the issue:
struct base_exception ... | You can put a throw_me virtual function in the base exception class, and have every derived class override it. The derived classes can throw the proper most derived type, without slicing. Even though the function has the same definition in each class, they're not the same - the type of *this is different in each case.
... |
5,421,152 | 5,421,256 | C++: how do I convert hex char to unsigned char? | I have a method that takes unsigned chars, but I want to pass it 0x01.
I know I can represent hex chars in strings by going "\x01"...
but that is still a signed char.
EDIT:
some code:
kennys_hash((unsigned char const *)"\x00"); // the method call
the error:
src/main.cpp:88: error: invalid conversion from ‘const unsig... | 0x01 is the same as 1, which is positive, and thus it doesn't matter if it's considered to be signed or unsigned, the value is the same.
If you want to have an unsigned type on the literal, use 0x01u.
|
5,421,387 | 5,422,814 | Question about the usage of CRITICAL_SECTION | Given the following code,
class MyCriticalSection : protected CRITICAL_SECTION
{
public:
MyCriticalSection()
{
InitializeCriticalSection(this);
EnterCriticalSection(this);
}
~MyCriticalSection()
{
LeaveCriticalSection(this);
DeleteCriticalSection(this);
}
};
clas... | Your update is no better. If you want to do this in an RAII style then you need to work a bit harder. The key is that you need to separate the critical section object which is statically allocated, and the lock which is local to all blocks that need protection.
The following is lifted from Jonathan Dodds but it is a ... |
5,421,627 | 5,422,187 | Can I safely replace a bool member with unsigned char in a public header? | I ship a public header that users compile against to utilize classes contained within. I need to fix an issue in the shared library that implements one of these public classes and have a requirement that existing users need not recompile their libraries when installing a patch. The fix requires a bool member to be ab... | I don't know about GCC, but I did some similar hacks with MSVC 6 a long time ago (most of them were replacing a DWORD with a pointer). Worked just fine.
Of course, as many others already wrote, sizeof(whateverYouUse) must equal sizeof(bool).
That shouldn't be a problem though, since you can always use
class PublicAPI{
... |
5,421,687 | 5,439,684 | boost::spirit stream_parser consumes too much? | I'm having some trouble integrating a class with iostream parsing
support into a spirit parser. The example below (modified from the Spirit examples) demonstrates the
problem. If I attempt to parse ONLY the custom class, it succeeds as
shown by the first parse and call to assert. If I attempt to parse the
custom class ... | This turned out to be a bug in the stream parser component. It didn't account for the fact that the underlying std stream was buffering the input. The problem is fixed in SVN and the fix will be part of Boost V1.47. I added a new test to Spirit's regression test suite based on your code - I hope you don't mind. Thanks ... |
5,421,705 | 5,421,741 | c/c++ boost - problem compiling | I've been pulling my hair out trying to figure out how to compile my app with boost regex.
I've installed boost from source on centos 5.
g++ -lboost_regex -o my_app my_app.c $(mysql_config --libs --cflags)
It compiles without any errors, however when I execute it:
error while loading shared libraries: libboost_regex.s... | Did you try LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH your_program to make sure it knows where to find the shared object? You can set the path when you link by using -Wl,-R/usr/local/lib.
EDIT: To be more clear, when you link your code the linker will embed an RPATH and RUNPATH into the binary. These values tell ... |
5,421,822 | 5,421,870 | error in :c++ template function | Hi I try build a tamplate function in vc++ like below:
template<class _Fn0,class _Fn1> void for_each(_Fn0 _Func0,_Fn1 _Func1)
{
_Func0(12);
_Func1(12);
}
when I use for _Func0/1 a global function this work propely.
void aglobal(int a)
{
a++;
}
for_each(aglobal,aglobal);
but when I use a memeber cla... | A::aa and A::bb are nonstatic member functions; you are trying to call them as if they were nonmember functions.
A nonstatic member function can only be called on an instance of the object.
To fix it, you can
make aa and bb static, or
pass an instance of A into for_each so that it can call the functions on that inst... |
5,421,956 | 5,421,969 | Static const variable is not constant in child class | I am using Visual Studio 2008 and have two classes Parent and Child. Parent declares some static const variables in the header, which are then defined in the cpp file. When I try to use the defines as cases in a switch statement in a child class I get the error: C2051: case expression not constant. So I've done some... | You can only use a static const integer-type member variable in a constant expression if
it is initialized with a constant expression and
that constant expression is visible at the time that it is used.
In your switch, the value of Parent::A is visible because its initializer is in the Parent.h header file. The sa... |
5,422,019 | 5,422,134 | Specifying thread stack size in pthreads | I want to increase the stack size of a thread created through pthread_create(). The way to go seems to be
int pthread_attr_setstack( pthread_attr_t *attr,
void *stackaddr,
size_t stacksize );
from pthread.h.
However, according to multiple online references,
The s... | Never use pthread_attr_setstack. It has a lot of fatal flaws, the worst of which is that it is impossible to ever free or reuse the stack after a thread has been created using it. (POSIX explicitly states that any attempt to do so results in undefined behavior.)
POSIX provides a much better function, pthread_attr_setst... |
5,422,025 | 5,422,327 | C++ / Java / C# Image processing library | What would be the best library choice for finding similar parts in images and similarity matching?
Thank you.
| It sounds like the Scale Invariant Feature Transform (SIFT) is probably the algorithm you're really looking for. Offhand, I don't know of any general-purpose image processing library that includes it, but there are definitely standalone implementations to be found (and knowing the name should make Googling for it rela... |
5,422,081 | 5,422,176 | CPP unit build error in VS 2010 | I am builidng CPPunit 1.12.1 using VS 2010. I able to build CPP unit successfully on VS 2008. I am building only CPPUnit library.
I am getting following error. How can i fix this error.
error MSB3073: The command "copy "D:\src\cppunit\.\Debug\cppunit.lib" ..\..\lib\cppunit.lib
:VCEnd" exited with code 1. C:\Program F... | These are post-build event errors.
Right click on your project-name in Visual Studio Solution Explorer:
Properties >> Post-Build Event
Remove the text from CommandLine textbox if you don't want post-build events. Or fix the path!
|
5,422,102 | 5,439,585 | MagickQuantizeImage usage | I am processing some images using ImageMagick library. As part of the processing I want to minimize the number of colors if this doesn't affect image quality (too much).
For this I have tried to use MagickQuantizeImage function. Can someone explain me whow should I choose the parameters ?
treedepth:
Normally, this inte... | This is a really good description of the algorithm
http://www.imagemagick.org/www/quantize.html
They are referencing the command-line version, but the concepts are the same.
The parameter measure_error is meant to give you an indication of how good an answer you got. Set to non-zero, then look at the Image object's me... |
5,422,317 | 5,422,515 | Year is out of valid range: 1400...10000 | I'm attempting to use boost::date_time to parse a date string (obtained from the Twitter API) into a ptime object. An example of the date format is:
Thu Mar 24 16:12:42 +0000 2011
No matter what I do though, I get a "Year is out of valid range" exception while trying to parse the string. The date format looks correct ... | Both %T and %q are output-online format flags.
To demonstrate that, change your format to "%a %b %d %H:%M:%S +0000 %Y" and your program will run as described.
As for time zone input, it is a bit more complex, you may have to pre-process the string to change +0000 to posix time zone format first.
EDIT: for example you c... |
5,422,555 | 5,422,612 | How do I find the directory path of a file I created from ofstream in C++? | I want to get the directory of a file which I created using ofstream.
Code I wrote is something like
std::ofstream txt("sample.txt", std::ios::binary);
Then I write some things to the txt file, then call txt.close() to close the ofstream. While writing, I want to get the location of the sample.txt file and write it o... | You should look into Boost.Filesystem for portable path handling. C++ does't have too much for paths, as you might be running on platforms without a file system. However, you could try to get something with getcwd and appending '/' between the output and your file name. getcwd is not part of C, but it's available on Wi... |
5,422,579 | 5,422,921 | Double initialization of a static STL container in a C++ library | There are a few good questions and answers here around the "static initialization order fiasco", but I seem to have hit against yet another expression of it, specially ugly because it does not crash but looses and leaks data.
I have a custom C++ library and an application that links against it. There is an static STL c... | One way to work around initialization order problems is to move the static variables from global scope to local scope.
Instead of having a registry variable within the class, put it into a function:
vector<string> & MyLibClass::GetRegistry()
{
static vector<string> registry;
return registry;
}
In the places wh... |
5,422,594 | 5,422,753 | What's the correct syntax for a member function of a class template returning a type defined in that class? | I am working through Accelerated C++ at the moment, and I am stuck on exercise 11-6. The idea is to reimplement the standard library vector as a class called Vec.
I am having trouble with the iterator erase(iterator) member, because I don't know the correct syntax when outside of the class definition, and everything I'... | template <class T>
typename Vec<T>::iterator Vec<T>::erase(typename Vec<T>::iterator pos){
//^^^^^^^^ note this ^^^^^^^^ note this as well!
//your code!
}
That is, typename is required at two places. It's because iterator is a dependent name, so typename is required!
Read this exce... |
5,422,795 | 5,422,966 | unsigned int* assignment changing the target unsigned int | Ok this must be something dumb. I ran into this when moving some code over and figured I had made a typo or was failing to use the debugger correctly. As a sanity check I created this test case but it still appears to be failing.
unsigned int vtxIdx = 0;
unsigned int* tgtIdx;
NSLog(@"Init %d", vtxIdx);... | For your second output statement, do you get the same thing if you print the values of both vtxIdx and *tgtIdx?
Does anything change if you initialize tgtIdx = NULL;?
If you run each NSLog function twice in a row with the exact same arguments, do they output the same thing each time?
You mentioned a debugger in your qu... |
5,422,810 | 5,422,957 | Visual Studio 2010 doesn't display debug info for local variables | Visual Studio 2010 doesn't display debug info for local variables. I have no problem seeing my class variables though. Is there some setting that I'm missing?
This is a "debug" build.
I tried going to Project Properties -> C++ -> Optimizations and disable all optimizations.
| This can help.
http://support.microsoft.com/kb/2452649
This is the main entry
http://social.msdn.microsoft.com/Forums/en/vsdebug/thread/6133b9d0-81c6-4e30-bfe5-5b3d6e104300
|
5,423,077 | 5,423,582 | STA (Single Threaded Apartment) COM Object - Spawn worker threads? | Is it a bad thing to spawn worker threads in your STA COM object (ie. COM object creates a thread to perform a task)? I think, the answer is - that depends!
For example in my case:
The worker threads that I am using will not interfere/access COM or COM Services.
Reason why I am asking this is because by STA COM definit... | No, that's not a bad thing. Apartments explicitly exist to help you getting multi-threaded code working. An STA thread is a safe home for a COM server that's not thread-safe, COM's apartment threading model ensures that it is always used in a thread-safe way. All you have to do is the marshal the interface pointer y... |
5,423,246 | 5,423,637 | how to detect if a type is an iterator or const_iterator | I'm wondering, if there is a way to check at compile time whether a type T of some iterator type is a const_iterator, or not. Is there some difference in the types that iterators define (value_type, pointer, ...) between iterators and const iterators?
I would like to achieve something like this:
typedef std::vector<int... | C++03 Solution:
As none of the answer seems correct, here is my attempt which is working with GCC:
template<typename T>
struct is_const_pointer { static const bool value = false; };
template<typename T>
struct is_const_pointer<const T*> { static const bool value = true; };
template <typename TIterator>
struct is_cons... |
5,423,248 | 5,423,297 | Writing front end gui for commandline application | Can anyone please, point out some good tutorials, to develop a front end gui for commandline applications ? I mean writing a front end for applications like ffmpeg,nmap etc. I know that there exists many for these applications but I really need to know how to do it?. I'm planning to develop gui for some c++ application... | Wrapping command line applications usually means executing the command line application, handling their command line parameters, and parsing their output.
For a GUI toolkit I would suggest going for one of the major cross platform toolkits:
Qt (C++)
GTK+ (C, has C++ wrapper called gtkmm)
wxWidgets (C++)
|
5,423,260 | 5,423,324 | Trouble converting string from commandline to array of floats | char * temp_array;
strcpy(temp_array, argv[i + 1]);
for(int j = 0; j < 8; j++)
{
fann_input[j] = atoi(temp_array[j]);
printf("%f\n", fann_input[j]);
printf("o%c\n", temp_array[j]);
}
fann_input is a float array.
on the atoi line, I ... |
The prototype of main is int main(int argc, char **argv), even though argv should be considered constant.
You're copying into a random part of memory because temp_array is not initialized.
You're calling atoi on individual characters instead of on a string.
atoi converts to int, not to float, although that shouldn't b... |
5,423,506 | 5,423,725 | Code reuse problem with a template Vector class for 3D math | I have a template Vector class for 3D vector math. I'd like to have variants of this class of different type and size (e.g. Vec2i, Vec2f, Vec3i, Vec3f) and be able to construct one from the other, like so:
Vec2i v(1, 2);
Vec3f u = Vec3f(v, 0);
Currently, I have a number of constructors in Vector for accomplishing thi... | A Vec2 and a Vec3 are quite different IMO, what code reuse would you expect if they were related?
For the different built-in types, simply use template classes and template constructors:
template<typename T1>
struct Vec2 {
Vec2(T1 const & X, T1 const & Y) : x(X), y(Y) {}
template <typename T2>
Vec2(Vec2<... |
5,423,600 | 5,423,661 | Getting child window's handle C\C++ | I've tried searching here and on google, i ended up with the "GetDlgItem" method, but it doesn't work.
Here is my code:
HWND hwnd_Parent;
HWND hwnd_Child;
hwnd_Parent = FindWindow(NULL,"MyTitle");
hwnd_Child = GetDlgItem(hwnd, 0x00030756);
hwnd_Parent is ok (i even did some post message tests), but hwnd_Child is null... | You need to know the ID of the window to use GetDlgItem(). I suspect you are passing in an HWND that you got from Spy++.
It looks like you are poking around in another app because if it was your own app then you wouldn't need to call FindWindow, and you'd know the control ID.
Probably the easiest way to find this wind... |
5,423,708 | 5,423,719 | Iterator error value | whats a value that is generally used as an error value besides <container>.end()? im doing a simple linear search through a std::list<int>and i want a way to know that the search did not turn up a place in the list
| All of the standard C++ classes return <container>.end() when a search result fails since end() doesn't actually point to an element in the container (it points "past-the-end" of the container). I don't see a reason why another type would be necessary.
|
5,423,821 | 5,423,859 | Deleting an Array of Pointers - Am I doing it right? | I feel a little stupid for making a question about the deletion of pointers but I need to make sure I'm deleting in the correct way as I'm currently going through the debugging process of my program.
Basically I have a few arrays of pointers which are defined in my header file as follows:
AsteroidView *_asteroidView[1... | This is correct. However, you may want to consider using Boost.PointerContainer, and save you hassle the hassle of manual resource management:
boost::ptr_vector<AsteroidView> _asteroidView;
for(int i = 0; i < 16; i++)
{
_asteroidView.push_back(new AsteroidView());
}
You do not have to manage the deletion, the cont... |
5,423,929 | 5,423,986 | Realtime progress from Windows service | I'm working on an application which I think would be better suited to being a Windows service. The only issue I have come up against in planning to convert it is that it has a window which displays activity. Now I know it's bad practice (and deprecated in Win7) to show a GUI from a service so my question is, what is th... | Create a service that does the work, and an optional GUI application that, if running, sits in the system tray and allows you to open a window watching the progress. You can communicate the progress over e.g. shared memory or named pipes - but remember that the service is running while noone is logged in, so it should ... |
5,423,960 | 5,636,974 | How can I recognize RTL strings in C++ | I need to know the direction of my text before printing.
I'm using Unicode Characters.
How can I do that in C++?
| If you don't want to use ICU, you can always manually parse the unicode database (.e.g., with a python script). It's a semicolon-separated text file, with each line representing a character code point. Look for the fifth record in each line - that's the character class. If it's R or AL, you have an RTL character, and '... |
5,424,042 | 5,424,111 | Class variables: public access read-only, but private access read/write | Whoopee, not working on that socket library for the moment. I'm trying to educate myself a little more in C++.
With classes, is there a way to make a variable read-only to the public, but read+write when accessed privately? e.g. something like this:
class myClass {
private:
int x; // this could be any type, hyp... | Of course you can:
class MyClass
{
int x_;
public:
int x() const { return x_; }
};
If you don't want to make a copy (for integers, there is no overhead), do the following:
class MyClass
{
std::vector<double> v_;
public:
decltype(v)& v() const { return v_; }
};
or with C++98:
class MyClass
{
std:... |
5,424,093 | 5,424,313 | how to iterate into a smaller container (i.e. stride != 1) | There is a question that is very similar in spirit here. Unfortunately that question didn't prompt much response - I thought I would ask a more specific question with the hope that an alternative method can be suggested.
I'm writing a binary file into std::cin (with tar --to-command=./myprog).
The binary file happens ... | I would write my own class that reads two chars and converts it to float.
struct FloatConverter
{
// When the FloatConverter object is assigned to a float value
// i.e. When put into the vector<float> this method will be called
// to convert the object into a float.
operator float() { return 1.0; /... |
5,424,324 | 5,735,733 | Fast conversion of C/C++ vector to Numpy array | I'm using SWIG to glue together some C++ code to Python (2.6), and part of that glue includes a piece of code that converts large fields of data (millions of values) from the C++ side to a Numpy array. The best method I can come up with implements an iterator for the class and then provides a Python method:
def __array... | So it looks like the only real solution is to base something off pybuffer.i that can copy from C++ into an existing buffer. If you add this to a SWIG include file:
%insert("python") %{
import numpy as np
%}
/*! Templated function to copy contents of a container to an allocated memory
* buffer
*/
%inline %{
//==== AD... |
5,424,444 | 5,424,596 | Reading stdin from another thread | I am using p_threads in my code on unix. In my main program I have a thread Node which makes 2 threads one of which is doing a read from the standard input using getline. All of this working fine.
Except at some point during my code I have to "restart my thread that reads from the standard input". And when i do that, ... | You are probably aborting the thread that is still connected to standard input, remember that you aborted the thread while doing getline.
Now I don't know if there is a way to acquire the standard input pointer and free it to be able to get more lines but there probably is a method to continue reading the lines tha pre... |
5,424,532 | 5,424,979 | Speeding up a matrix computation using parallel processing in C++? | I'm trying to compute the following:
Y = Y0 - ( Un.(A*Y0) + Vn.(Y0*Z) )*dt
in the fastest/most efficient manner possible where Y0, Un, Vn, A, and Z are matrices dimensioned on the order of 300 X 300, "." is the matrix dot product, and "*" represents matrix multiplication.
My questions are:
Is computing the computation... | Your problem is very small. You should try using something like Eigen (or as you mentioned ATLAS). I prefer Eigen since it is fast to use.
|
5,424,897 | 5,424,934 | Opening a file in C++ | I am trying to open a file stored on my c drive with name test.txt.I am getting a lot of errors.I am new to filing in C++.Please help me out thanks.
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream mystream;
mystream.open("C:\\test",ios::in||ios::out... | This
mystream.open("C:\\test",ios::in || ios::out);
should be
mystream.open("C:\\test",ios::in | ios::out);
|
5,424,983 | 5,425,026 | traversing through a list | im trying to traverse through a list 2 values at a time, but for some reason, its getting stuck in an infinite loop
i have:
list<mystruct> a, b; // defined, each guaranteed to have at least 1 value
a.insert(a.end(), b.begin(), b.end());
a.sort(mysort);
list<mystruct>::iterator it1 = a.begin(), it2 = it1// or = a.begin... | You want to use it2 = a.erase(it2); otherwise it2 will be pointing to an element that you've erased from the list. a.erase returns the element following it2.
|
5,424,990 | 5,425,032 | c++ std::set insert causing segmentation fault | All-
I can't quite figure out why this piece of code is resulting in a segmentation fault... Any help would be great.
#include <iostream>
#include <set>
using namespace std;
class A{
public:
int _x;
A(int x){
_x = x;
}
};
bool fncomp(A a1, A a2){
return a1._x < a2._x;
}
int main(){
bool... | Well, look at your code. You declared a function fncomp, but are you really using that function anywhere? You initialize fn_pt with it, but fn_pt is not used anywhere. Doesn't it seem strange to you? How do you expect your testSet object to know that you want it to use your fncomp as the comparator, if you never ask yo... |
5,425,065 | 5,425,343 | c++ pimpl idiom : Implementation depending on a template parameter | In this question I unsuccessfully asked how to use different pimpl implementation depending on a template argument.
Maybe this example ilustrates better what I am trying to do :
#include <iostream>
template< int N, typename T >
struct B
{
B() : c( new C< N > )
{}
template< int M >
struct C;
C< N >... | What you're trying to do is not allowed by the language.
§ 14.7.3.16 (FCD 2010-03-26) states:
In an explicit specialization
declaration for a member of a class
template or a member template that
appears in namespace scope, the member
template and some of its enclosing
class templates may remain
unspecializ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.