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 |
|---|---|---|---|---|
7,698,228 | 7,698,288 | What are guidelines of whether to throw an exception in C++ standard function? | I have found out that C++ standard functions show very different behavior when having an exception. This seem to contradict its touting of "try/throw/catch". Can anyone please briefly explain what are the C++ designer's reasoning behind these choices?
Do nothing, for example, try to pop() a stack when it is empty (ins... | Most of the behaviour of C++ library functions can be explained by the general C++ philosophy "you don't pay for what you don't use". That means that any particular construction shouldn't incur any unneeded overhead when you use it correctly.
Optionally, more expensive, checked versions may exist, such as std::vector::... |
7,698,451 | 7,743,530 | C++ 11 threading API: is there a free implementation for MSVC 2010? | Is there any free 3rd-party implementation of std::thread API for use in MSVC versions older than 11?
| Boost::thread is a way to go!
|
7,698,460 | 7,700,236 | Tile engine performance issue | I am using SFML and I can't find any explanation on how the library is working and I have performance issues.
I am trying to make a tile map made of 50x50 tiles that are each 20x20 pixels wide.
1) Each tile is a sf::sprite whose graphic image is simply a big image (my tileset), on which I set a 20x20 subrectangle.
2) I... | This is generally considered the wrong way to render a tile map.
The more correct way is to create a large texture, or sf::Image in this case, and then rendering your tiles onto this texture, and then rendering this large texture to the screen. There are cases where this approach isn't feasible, but for most cases, it'... |
7,698,476 | 7,698,486 | Is p = array the same as p = &array[0]? | int numbers[20];
int * p;
Are the two assignments below the same?
p = numbers;
p = &numbers[0];
| Yes both are same.
In this case, Name of the array decays to a pointer to its first element.
Hence,
p = numbers; //Name of the array
is same as:
p = &numbers[0]; //Address of the First Element of the Array
|
7,698,732 | 7,700,438 | glVertexPointer invalid operation | I'm having rather strange problem with OpenGL. When I try to use glVertexPointer with no buffer bound to GL_ARRAY_BUFFER and using Vertex Array Object(VAO), it generates invalid operation error. This error is nowhere in documentation of glVertexPointer.
When I generate buffer and bind it to GL_ARRAY_BUFFER, error disap... | The extension registry for ARB_vertex_array_object clearly states, that they cannot be used with client-side arrays. This shouldn't be different for the core OpenGL versions supporting VAOs and is due to the fact, that VAOs are server-state. So it is completely expected behaviour to get an invalid operation error. Just... |
7,698,775 | 7,698,801 | About strongly typed enumerations forward declaration | I've a set of classes in my namespace and want to group forward declaration in a define.hpp file.
I've already achieve this in others projects, here is an example :
namespace Makefile
{
class Builder;
class Config;
class Options;
class Target;
class Tool;
}
My problem is that — for example — the Co... | You simply make the opaque enum in the usual place:
namespace Makefile
{
class Config
{
public:
enum class OperatingSystem : unsigned int;
};
}
And then, wherever you want to define the enum constants:
namespace Makefile
{
enum Config::OperatingSystem : unsigned int
{
MacOSX =... |
7,698,979 | 7,699,021 | Can't put math.h in a namespace | I'm doing some cross platform development, and I ran across another weird problem..
namespace Math
{
#include <math.h>
}
This is what I am trying to do. It works fine on iOS, but on Android everything inside math.h is not a member of Math when I try to compile it. After some trial an error I found out that the nd... | What about <cmath>? it puts everything in std:: (in C++11).
|
7,698,986 | 7,699,043 | emit std::string with qt signal | I am trying to emit standard string with qt signal. The signal will be delivered as queued. I registered the type with qRegisterMetaType , like it says in the qt documentation, but no luck. I am registering it like this
qRegisterMetaType<std::string>("std::string")
| You should also do:
Q_DECLARE_METATYPE (std::string)
Quoting Qt Doc
Adding a Q_DECLARE_METATYPE() makes the type known to all template
based functions, including QVariant. Note that if you intend to use
the type in queued signal and slot connections or in QObject's
property system, you also have to call qRegist... |
7,699,053 | 7,699,077 | C++ Semicolon after class, struct, enum,... useless but compilers still emit errors? |
Possible Duplicate:
In C++ classes, why the semi-colon after the closing brace
This is something I have wondered about for quite some time, why do you have to put a semicolon after the closing bracket of a class, struct or enum in c++?
Worse (or the actual question), why does compilers emit errors about it when they... | It's a leftover from C. You can declare variables after cladd/struct/enum declaration. the code:
class A{};
A a;
Is identical to:
class A{} a;
The compiler needs the ; to know you don't want to declare variables after the class declaration.
|
7,699,064 | 7,699,087 | c++ overload operators | I'm noobie in c++.
I have class DataBase which contains tables( class Table) and I must overload operators to get next result:
dataBase(3,5)=someTable; - this code must replace tables 3-5 from database with table someTable.
So, help me please whith overload methods signatures.
| The signature for overloading the function call operator within your DataBase class is:
reference_type operator()( int first, int last );
Where reference_type is a proxy reference, that is a helper type that stores a reference to the database and the first and last indexes, and overloads operator= to do the replacemen... |
7,699,097 | 7,699,114 | Extracting string from character array | I've tried memcpy / strncpy / std::copy but neither of them seem to work resulting the program to crash.
Here's what i need to do:
I'm trying to parse arguements from user input for instance.
"message -add 0xAE"
i need to fetch the 0xAE part into an integer, heres some pseudo-code
_input will hold the full string "mess... | Are you looking for:
int value = 0;
char c;
for(int i = strlen("message -add 0x"); c = *(_input + i); i++) {
value <<= 4;
if(c > '0' && c <= '9') {
// A digit
value += c - '0';
} else if(c >= 'A' && c < 'G') {
// Hexadecimal
value += 10 + c - 'A';
}
}
?
|
7,699,167 | 7,699,199 | calling more than one function in STL algorithm | The classical example using STL algorithms:
void foo(int){};
vector<int> collection;
collection.push_back(3);
collection.push_back(4);
... etc.
std::for_each(collection.begin(), collection.end(), bind(foo, _1));
But what if we have more then one function, which needs to be called with the same argument values:
void b... | Since you tagged the question with C++11, then you can use lambda as:
std::for_each(collection.begin(), collection.end(), [](int a)
{
bar(a);
beer(a);
});
I recall that C++11 has std::begin and std::end as free functions, which should be preferred over the member functions:
std::for_each(std::begin(collectio... |
7,699,259 | 7,699,283 | How does adding a private member variable break C++ ABI compatibility? | The pimpl idiom is commonly used in order to allow changing code in dynamically linked libraries without breaking ABI compatibility and having to recompile all the code that depends on the library.
Most of the explanations I see mention that adding a new private member variable changes the offsets of public and private... | The main problem is that, when you allocate a new instance of a class (either on the stack, or via new), the calling code needs to know the size of the object. If you later change the size of the object (by adding a private member), this increases the size needed; however your callers are still using the old size. So y... |
7,699,502 | 7,699,513 | Float display 0 number after 1.5 | I have a float that adds numbers and its not displaying all the decimal points i wish for example i have 1.25 add 1.25 as a float and it shows as 1.5. How can i have it display as 1.50 for example?
| #include <cstdio>
/* ... */
printf("%.02f", f);
See the documentation for printf().
|
7,699,588 | 7,699,614 | Why is *&x not the same as x? | Short version:
The following code doesn't compile:
CComBSTR temp;
CMenu().GetMenuString(0, temp, 0);
but this does:
CComBSTR temp;
CMenu().GetMenuString(0, *&temp, 0);
Why?
Full code:
#include <atlbase.h>
extern CComModule _Module;
#include <atlapp.h>
#include <atlwin.h>
#include <atlctrls.h>
int main() {
CCo... | Because the unary operators & and * can be overloaded, which I guess CComBSTR does.
* Update: *
For those who wonder how to get the address of a variable whose type has overloaded operator& there is TR1's std::addressof, and a Boost implementation of it for C++03 compatibility.
|
7,699,795 | 7,699,834 | Similar to ptr_map container | I decided to throw out boost from my project. Any way to have best implement of container instead of ptr_map? As I know it holds a smart pointer as a value. Maybe QMap<Key, std::shared_ptr<Type*>> could do that?
| What's wrong with std::map<Key, std::shared_ptr<Type>>? Advantages over QMap:
standard solution
has better worst-case time bounds (QMap is a skip list, so expected time bounds are the same)
64-bit clean whenever the compiler/library is (QMap uses int for sizes)
interface is more similar to boost::ptr_map
|
7,699,802 | 7,699,809 | Run time error with array | I can't understand why I get the run time error:
the variable ia is being used without being initialized.
However, as far as I can see, I have initialized it.
#include <iostream>
using namespace std;
int main()
{
//array dimensions
const int row_size = 2;
const int col_size = 4;
//array definition
... | C++ array indexes are zero-based. So to access the fourth column of the second row, you need to access ia[1][3].
|
7,699,919 | 7,699,992 | C++ destruction list | I have a class to do a computation using some callbacks. those callbacks need to allocate data (dynamic arrays) that needs to live outside of the callback scope but not after the class destructs. I thought about make a vector of auto_ptr that will just get destructed automatically when the class destructs:
class MyClas... | You could use a vector<shared_ptr<void>>.
Read this: Why do std::shared_ptr<void> work
|
7,699,963 | 7,700,093 | Templates don't always guess initializer list types | #include <initializer_list>
#include <utility>
void foo(std::initializer_list<std::pair<int,int>>) {}
template <class T> void bar(T) {}
int main() {
foo({{0,1}}); //This works
foo({{0,1},{1,2}}); //This works
bar({{0,1}}); //This warns
bar({{0,1},{1,2}}); //This fails
bar(std::initializer_list... | GCC according to C++11 cannot deduce the type for either first two calls to bar. It warns because it implements an extension to C++11.
The Standard says that when a function argument in a call to a function template is a { ... } and the parameter is not initializer_list<X> (optionally a reference parameter), that then... |
7,699,973 | 7,700,009 | While keeps repeating on letters but not on #'s | I have a while loop here that only takes in 1 and 2 as the number, if i insert and number that is not these my else statement will keep asking for the correct one, which works correctly. But if i insert a letter my else statement loops forever. How can i fix this?
#include <iostream>
using namespace std;
int main()
{... | If you enter a non-number, then cin >> myChoice fails. That means that it leaves the input intact in the input buffer and when you get there again it tries to parse it and fails, and so on... You must clear the error state and ignore the non-digits. The simplest way is something like this:
cout << "Try again: ";
cin.cl... |
7,700,123 | 7,700,393 | std::vector constructor behavior | Take the following code:
std::vector<std::vector<int>> v(10, 10);
This code doesn't compile with libstdc++. It does compile with Visual Studio's C++ library, however. The behavior I would expect is that v is filled with 10 vectors of size 10, and this is what I get with Visual Studio.
The constructor invoked with Visu... | std::vector<std::vector<int>> v(10, 10);
This should not compile, because the vector's single argument constructor is explicit.
C++03:
explicit vector(size_type n, const T& value = T(), const Allocator& = Allocator());
C++11:
explicit vector(size_type n);
This means a number like 10 can't implicitly turn into a vect... |
7,700,205 | 7,700,375 | How do I integrate an ASM obj file with a C++ program? | I want to integrate ASM and C++ code in Visual Studio 2010. Basically, I want to be able to use certain routines created in ASM in my C++ code.
So I want to know:
How do I add the ASM obj files to VS2010 in the first place?
How do I call a function in the ASM code from the C++ part of the code?
Suppose that I make a ... | All of these samples have what you need:
http://msdn.microsoft.com/en-us/library/t13a3526%28v=VS.80%29.aspx
You will have to let visual studio automatically "convert" them to the new project format, but I just tried it with the PRIMESSTEP2 example and it worked.
All you need is a function prototype like:
void sieve(voi... |
7,700,264 | 7,700,603 | Visual Studio 2010 + Visual Assist C++: Are there any automated ways to create getters and setters? | So I am creating a simple class like:
class file
{
public:
boost::filesystem::path path;
bool is_directory;
boost::uintmax_t target_size;
void get(boost::shared_ptr<boost::asio::ip::tcp::socket> socket, boost::shared_ptr<http_response> response);
void set()
};
and I see that if some automated proce... | Select class variable and from context menu pick Refactor (VA X) -> Encapsulate Field. You can customise the format by modifying Refactor Encapsulate Field snippet. You can find more on customising snippets here.
The snippet I personally use yields Java-like accessors with doxygen documentation stubs:
//! \return
$end$... |
7,700,361 | 7,700,379 | Converting a GMP integer to a base N integer | GMP allows to print a mpz_t up to base 62, but I want to represent a number into any base N, and for this I first need to generate an array of integers (let us say I will limit myself to base 2 ^ 64), so an array of unsigned long might do it.
For example if I want to take any integer and convert it to base 792, I can't... | Internally, GMP's functions directly or indirectly call the mpn layer - which are documented here:
http://gmplib.org/manual/Low_002dlevel-Functions.html#Low_002dlevel-Functions
The mpn_get_str only supports bases up to 256. So I don't think you can go higher unless you write your own base conversion (which is not trivi... |
7,700,397 | 7,700,998 | Vectorizing An Expression Using Eigen | In my program -- which uses the Eigen library -- I need to operate on 2D vectors. In my inner loop I have the following function:
static inline double eval(double x, double y, double xi, double yi)
{
const double invlen2 = 1/(x*x + y*y);
const double invlen4 = invlen2*invlen2;
const double invlen6 = invle... | This answer has nothing to do with Eigen, but since you mentioned manually dropping down to assembly, I'll add this.
You don't need to use assembly to vectorize code. There are compiler intrinsics that will let manually vectorize without assembly:
http://software.intel.com/sites/products/documentation/studio/composer/e... |
7,700,400 | 7,700,425 | What's a good hash function for English words? | I have a long list of English words and I would like to hash them. What would be a good hashing function? So far my hashing function sums the ASCII values of the letters then modulo the table size. I'm looking for something efficient and simple.
| To simply sum the letters is not a good strategy because a permutation gives the same result.
This one (djb2) is quite popular and works nicely with ASCII strings.
unsigned long hashstring(unsigned char *str)
{
unsigned long hash = 5381;
int c;
while (c = *str++)
hash = ((hash << 5) + hash) + c; /*... |
7,700,506 | 7,700,512 | Can I get some assistance with this C style string in C++? | I'm trying to understand un-managed code. I come from a background of C# and I'm playing around a little with C++.
Why is that this code:
#include <iostream>
using namespace std;
int main()
{
char s[] = "sizeme";
cout << sizeof(s);
int i = 0;
while(i<sizeof(s))
{
cout<<"\nindex "<<i<<":"... | C strings are "nul-terminated" which means there is an additional byte with value 0x00 at the end. When you call sizeof(s), you are getting the size of the entire buffer including the nul terminator. When you call strlen(s), you are getting the length of the string contained in the buffer, not including the nul.
Note t... |
7,700,703 | 7,700,767 | static constexpr method implementation causes gcc bug? | Here is a piece of code:
class Class
{
static constexpr int getBug();
};
constexpr int Class::getBug()
{
return 0;
}
What I basically do is declaring a static constepxr method in class declaration, then I implement it.
The original code was split in two file, and contained more methods / attributes which have... | This is because constexpr is a new feature of the language, and according to the C++0x Support in GCC page, the support for this feature was first added to GCC in 4.6. My suspicion is that it is in fact a bug in the compiler, that could be fixed in 4.6.1 or later.
GCC 4.5.2 generates an error because the feature isn't... |
7,700,713 | 7,700,775 | How much overhead should I expect from a wrapper function | This question is more or less similar to this Extend an existing API: Use default argument or wrapper function?
but sufficiently different. Please read.
I have a class Foo that has function oldFunc that is used in many parts of my program.
In order to introduce new behaviour to Foo I implemented newFunc and made it pri... | In this particular case, there will be no overhead on any non-idiotic compiler as the function will be inlined. Your code would be equivalent to:
class Foo
{
public:
Foo(){ useNew = false;}
void setUseType(bool useType){ useNew = useType;}
std::string oldFunc(int r)
{
if(useNew )
{
return std::s... |
7,700,750 | 7,700,757 | Deleting char pointer array | I want to delete a char * array, which should be simple right? char * = new char[length]; then use delete[] char;?
Also, I am unable to use std::string for this exercise.
I'm getting this error:
HEAP CORRUPTION DETECTED: after Normal block (#137) 0x00794B50.
CRT detected that the application wrote to memory aft... | You messed the brackets up. It should be:
myString = new char[length + 1];
Square brackets will create an array. Normal brackets will allocate only one with whatever constructor takes that one operand.
|
7,700,794 | 7,700,812 | Printing a table C++ | I am trying to print a table that looks like this:
Number of Queues
Oc 2 3 4 5
50,000 average-max average-max average-max average-max
100,000 average-max average-max average-max average-max
150,000 average-max average-max ... | while (amount < 400000)
{
amount += 50000;
for (int i = 2; i <= 5; i++) //2 and 5 for the number of queues
{
Simulator simulator(i, amount);
simulator.start();
cout << setw(5) << amount << setw(10) << simulator.getAverage() << "-" << simulator.getMax(... |
7,700,868 | 7,701,210 | What are Window's FFT functions? | I'm writing a Win32 application, using just C++ and WinApi calls. I need to run an 8192-point FFT over 20ms of WAVEFORMATEX data. What would be the most efficient method of accomplishing this?
| As we fleshed out in the comments, the MSDN Documentation for XDSP functions may be of relevance to you.
The functions don't appear to take WAVEFORMATEX directly, but if you can convert it to the appropriate format you can use FFT to do what you want.
Note that it's part of the DirectX SDK, so you're introducing a new ... |
7,701,050 | 7,702,788 | Input validation for Integer and Double data types | Because there was an error in the code when I posted this question, it is not a good question. I have deleted and replaced it with a link to a correct solution.
Correct Solution for Input Validation
| cin.getline(buffer, '\n');
<-- is wrong, need buffer size.
cin.getline(buffer, 10000, '\n');
|
7,701,221 | 7,701,261 | How to pass "literal" integers by reference in C++ | To avoid the inefficiency of copy-by-value when calling a function (say, "fillRect"), I want to pass the parameters by reference.
If I supply the parameters as declared local variables, it works fine. But if I supply any as "literal" integers, I get a compile error (no matching function).
void fillRect( int &x, int &y,... | You cannot bind a literal to an lvalue reference to non-const (because modifying the value of a literal is not an operation that makes sense). You can however bind a literal to a reference to const.
So this will compile if you declare fillRect as:
void fillRect(int const& x, int const& y, int const& width, int const& h... |
7,701,283 | 7,701,546 | SignedXML class equal to visual C++? | Are there have any class equal to SignedXML visual in C++ (I mean not dependency on .net framework)?
| You can digitally sign XML from a Windows C++ app using libxml and xmlsec. You will probably also need openssl and libxslt.
It can take a bit of time to get them compiled with settings compatible with your app, but once they are compiling and linking they work OK.
|
7,701,312 | 7,701,337 | Trimming white spaces/converting iterators | I wanted to write two one-line functions which will trim white spaces from left and right side of a string. Left side weren't problem:
void trimLeft(string &s) {
s.erase(s.begin(), find_if(s.begin(), s.end(), (int (*)(int))isgraph));
}
But when I tried something similar for right side:
void trimRight(string &s) {
... | You can use the base() member function to recover the underlying iterator from its reverse_iterator.
void trimRight(string &s) {
s.erase(find_if(s.rbegin(), s.rend(), (int (*)(int))isgraph).base(), s.end());
}
|
7,701,326 | 7,701,334 | Assigning references | Consider the following declarations:
Object *a;
Object *b;
There are two ways of assigning a to b, by value or by reference:
a = b; // by reference
*a = *b; // by value
If the declarations are:
Object &a;
Object &b;
(I know its not possible to declare them without initializing them, its just to show the types)
There... | That overwrites the object referred to.
And no, it is not possible to rebind a reference so that it refers to a different object. If you need to do that, use a pointer instead.
|
7,701,349 | 7,701,361 | Issue when using modulus operator or other arithmetic operands in a class | Hello im having an issue when using the % operator in my class method functions.The console window pop ups but then another window opens when saying " ".exe has encountered a problem and needs to close. any idea? Heres the line of code of when i omit works fine.
r = gnumer % gden;
| Is gden zero? Modulus by zero is just as bad as dividing by zero.
|
7,701,479 | 7,701,495 | Use exec/fork to run external process | I am using C++ and trying to run a shell command in an external process. Here is the code I have so far:
pid_t pid;
pid = fork();
if(pid == 0){
execv(args[0],args);
} else {
wait();
}
My first problem is that I need to get the output from the shell command passed to exec and I do not know how to get that. Aft... | args[0] is presumably the name of the running program, so it will fork and then exec itself.
In order to collect output, you will need to arrange to explicitly pass it. The Unix pipe() call is frequently used for this.
|
7,701,577 | 7,701,589 | Visited pages for particular user from log file | How to find visited pages for a particular user from a big log file that contains list
of sessionId and PageId combination in each separate line?
File is big enough not to fit in memory. It means find out page that is being visited most in same session(user).
for e.g.
My file is (order is sessionId, PageID)
usera pa... | I think the first step would be to remove all "non-usera" lines since you're doing per-user parsing. This would be a one-time job separating all users into different files. After that you can do a line-by line analysis keeping only a couple of lines in "history". You can do this using a simple line parser without havin... |
7,701,754 | 7,701,769 | array class nodes not work | i have following code,which does not show me anything
#include <iostream>
using namespace std;
class Array{
private :
long *a;
public:
Array(int size){
a=new long[size];
}
void set(int index,long value){
a[index]=value;
}
long get(int index){
if (in... | index>(sizeof(a)/sizeof(long))
Is wrong. You're taking the size of a pointer, not the size of your array...
|
7,701,783 | 7,701,804 | Ofstream overwrite files contents when executed more than once | Suppose I declared a file ofstream myFile. Now I only want to create this file once, and when I execute this line a second time I don't want to overwrite the file and create a new one?
| If you have a one-file one-function setup (such as a log) you may consider using a static variable.
For example:
static ofstream* mylogger::outfile = new ofstream ("log.log");
Just too be cool from main function you should push a clean up function
atexit (mylogger::closePointers);
|
7,701,809 | 7,701,820 | issues with UDP server and client in C | I am trying to send/receive some data across 2 computers (mac, ubuntu) using a UDP connection and they are connected with an ethernet cable. When I run the server to receive some data from a client, I get the data but if I send it back, the client does not receive it. On further investigation, I found out that the cli... | Make sure you populate len before calling recvfrom, it's a value-result argument.
len = sizeof(clientAddress);
n = recvfrom(sockfd, msg, 1000, 0, (sockaddr *)&clientAddress, &len);
|
7,701,866 | 7,702,024 | How to build C++ project embed all dynamic link library in exe file? | everybody, I am getting started develop a C++ project and in this project I must use some opensource project have several dll file. Then I have a question "How to build C++ project embed all dynamic link library in exe file?"
Thank for help!
Note: Sorry, I forgot that I'm using visual studio compiler on x86
| There is no general answer to your question. It depends whether you need it to be cross platform or not.
However, since you're mentioning "visual studio compiler on x86", I bet you're targeting Windows. In such a case you have two options:
the official and recommended way: embed your dlls as resources in your executab... |
7,701,891 | 7,701,927 | C++ using namespace statement | namespace MyNamespace
{
static void foo1()
{
}
}
using namespace MyNamespace;
class MyClass
{
void foo2()
{
::foo1();
}
};
The scope resolution operation :: means using method in the global namespace. Here we can use ::foo1(). This means method foo1() is in the global namespace, ... | Section 3.4.3.4 of the C++2003 standard has an answer:
A name prefixed by the unary scope operator :: (5.1) is looked up in
global scope, in the translation unit where it is used. The name shall
be declared in global namespace scope or shall be a name whose
declaration is visible in global scope because of a usi... |
7,701,921 | 7,705,263 | free cv::Mat without releasing memory | I pass the Mat data (not a cv::Mat object) to a function, And make this function the new owner of this data. however, I need a method to free the original object, without freeing the data buffer it points to.
I know that this will happen to cv::Mat that were created from external data, I just need to use this feature f... | You can use addref() method but you will have a memory leak.
Actually it is not a good idea to detach data from Mat:
It was not designed for that;
You can not guarantee that pointer obtained from general cv::Mat points to the beginning of allocated memory block;
Most probably you will be unable to release that memory ... |
7,701,993 | 7,702,000 | casting object with user defined type | Can we cast an object with user-defined types, like we do for normal data types?
Like say we do type cast for int like:
int variable_one = (int)variable_name;
So can we do like: (complex) object_name;
where complex is the class I have written for complex number addition using operator+ overloading.
Is it possible in th... | int variable_one=(int)variable_name; is a C style cast.
C++ offers many casting operators:
dynamic_cast <new_type> (expression)
reinterpret_cast <new_type> (expression)
static_cast <new_type> (expression)
const_cast <new_type> (expression)
Have a look at article about type casting or refer to any C++ introductory boo... |
7,702,243 | 7,702,265 | C++ reinterpret_cast, making unique number | Recently, i'm using a code to make unique int number for my classes.
I used reinterpret_cast<int>(my_unique_name) where my_unique_name is a char [] variable with unique value. Something like below:
const char my_unique_name[] = "test1234";
int generate_unique_id_from_string(const char *str)
{
return reinterpret_cast... | No, it is not. You are casting the address of the string, not its contents.
To create a numeric value based on string input, use a hash function. However, this doesn't create a truly unique number, because of the so-called pigeonhole principle.
|
7,702,266 | 7,703,096 | Different Source Files For Different Compile Options in Visual Studio | Is there a Standard(ish) or a way todo this is Visual Studio to dealing with different source files for different compile options?
Right now I have an OpenGL and DirectX framework and I am in the process of merging them together. Currently how I'm differentating them is by included in a #if defined in the source file
/... | I would recommend that you factor out the platform dependent code into its own library and you build different versions of it. The actual project would have separate build configurations that would use one or the other.
|
7,702,342 | 7,702,407 | C++ TCP connection closing | I have a C++ application called A which open a TCP connection to Application B.
Application C knows about this connection and can close the socket from B side.
My question is:
how can I know if the connection has closed in proper closing, or it is the network connection problem?
Currently I have a timeout which knows ... | If the connection was closed properly, recv() will return zero. If it was closed improperly, recv() will eventually timeout (although there can be other reasons for that), and send() will eventually return -1 with errno ECONNRESET or whatever it's called.
|
7,702,343 | 7,702,467 | Programmatically catching windows close event when out of GDI resources | I'm trying to catch all unexpected terminations in my process.
I've used these functions to catch all the unhandled errors and exceptions that i can think of, but still it's not enough:
SetUnhandledExceptionFilter(OnUnhandledNativeException);
set_terminate(set_terminateHandler);
set_unexpected(set_unexpec... | Ok, solved the problem.
It WAS catching the crash.
The problem was that as part of the process of salvaging the data from the crash, it was opening a Form which was supposed to notify the user that an error has occurred.
Of course, we're out of GDI objects, so the Form can't be drawn, so that in itself threw and exce... |
7,702,426 | 7,703,490 | boost program options parse_config_file | I want to save the settings (in a file) of my application in boost program_options way
This is my function
void MainWindow::saveSettings()
{
po::options_description desc("Allowed options");
desc.add_options()
("ip",deImPath->text().toStdString().c_str())
("cp",deCalPath->text().toStdString().c_... | boost::program_options purpose is to pass parameters to your program.
If you want to store a configuration that the program can write too, you can use Boost.PropertyTree or Qt's QSettings class.
|
7,702,463 | 7,702,846 | What is special about the executables compiled with Visual Studio 11 which results in that the executables cannot be executed on Windows XP? | I compile my C++ source code with Visual Studio 11 Developer Preview. I statically link to the runtime library.
The resulting executable cannot be executed on Windows XP. When I try to execute it on Windows XP I get the error message "[Executable Path] is not a valid Win32 Application.".
According to Microsoft Visual S... | They seem to drop support for older systems in every new release of VS (NT4,2000,XP) Even if you don't use the CRT at all, they still force the PE subsystem version to high numbers. You can work around that by changing the numbers back to 5.0 in a post build step. Just changing those numbers should allow the exe to sta... |
7,702,543 | 7,702,762 | Visual C++ - Throwing unhandled exception from setting forms icon? | I can compile the solution with no errors, but when I'll try to run it, I get a crash window:
An unhandled exception of type
'System.Resources.MissingManifestResourceException' occurred in mscorlib.dll
Additional information: Could not find any resources appropriate for the specified culture or the neutral culture. Ma... | Take a look here :
http://www.mztools.com/articles/2005/MZ2005007.aspx
The exception is thrown because your icon cannot be located. You will probably need to compiles your resources under one .dll and put this under en-US subfolder on your project output. It did the trick for me at least. There are probably other solu... |
7,702,582 | 7,702,621 | linked list implementation | Here is simple linked list code:
#include <iostream>
using namespace std;
class link
{
public:
int data;
double ddata;
link *next;
link(int id,double dd){
data=id;
ddata=dd;
}
void diplay(){
cout<<data<<" ";
cout<<data<<" ";
}
};
class linkedlist{
p... | void diplay(){
cout<<data<<" ";
cout<<ddata<<" ";
}
Replace the display function with this code. (Instead of printing data and ddata you printed data twice)
|
7,702,612 | 7,702,665 | How to read an input from a client via socket in Linux in C++? | My goal is create an app client server, written in C++.
When the server read an input from the client, should process the string and give an output.
Basically, I have a simply echo server that send the same message.
But if the user types a special string (like "quit"), the program have to do something else.
My problem ... | Your data in buf may not be NULL-terminated, because buf contains random data if not initialized. You only know the content of the first num bytes. Therefore you also have to check how much data you've received before comparing the strings:
const char hello[6] ="hello";
size_t hello_sz = sizeof hello - 1;
if(num == hel... |
7,702,661 | 7,702,962 | Learning in C++/Waffles with object weights | I wonder if it is possible to pass object weights along with features in Waffles supervised learners (e.g. decision trees) for boosting purposes?
| This does not appear to be possible, but you could approximate weights by duplicating rows.
|
7,702,693 | 7,703,233 | Win32 DLL Window not showing | I've recently come up with some code that logic (and various places on the internet) says should work.
When injecting my Win32 DLL into any program though to test it, the Window I've create doesn't appear. I have no idea why this is, my code is as follows:
main.cpp
#include "stdafx.h"
#include "resource.h"
#include <tc... | In function GetWnd() the statement DialogBox(0,MAKEINTRESOURCE(IDD_DIALOG1),0,0); is wrong.
it must be something like :
DialogBox( hInst ,MAKEINTRESOURCE(IDD_DIALOG1),0 ,EventHandler );
where hInst is the instance-handle of your dll.
|
7,702,728 | 7,702,746 | Error when using `link` as a class name in C++ | Consider a simple program in C++:
#include <iostream>
class link {};
int main() {
link alink;
}
Compiling it with g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2 gives the following error:
test.cpp:6:8: error: expected ‘;’ before ‘alink’
Why do I get this error?
| Because link is also a posix function and the function name hides the class name.
You can say class link alink; but better put your class into a new namespace or rename it.
|
7,702,791 | 7,702,873 | On VTable pointers and malloc | Is there any compiler independent and syntactically elegant way to set a vtable pointer in an object allocated with malloc?
I cannot use new directly as I need to be able to control the flow of memory releases on demand which requires the use of void ptrs to hold memory locations in a memory manager until there is ampl... | You may not know that you can override global new and delete. Pay attention, you also need to override new[] and delete[] to be complete
Here an example:
void * operator new( size_t size )
{
return super_malloc( size );
}
|
7,702,793 | 7,702,801 | How to redirect output from reading a bash script in c++? | I know that the function:
system("myfile.sh")
exec a bash script.
Ok but now I want to redirect the output to my program to ensure the reading.
For example the script date.sh give me the date of my system, and i want to see it on my program with std::cout << OUTPUTDATE;
Is it possible?
How?
| Use popen instead of system.
The function popen will give you a FILE * you can read from.
FILE *script = popen("myfile.sh", "r");
while (fgets(line, LENGTH, script)) {
/* ... */
}
pclose(script);
|
7,702,812 | 7,702,834 | How many elements are there between two iterators | What's the best way to count all elements in an iterator?
I want code equivalent to this
template<typename T,typename S,S val>
struct ConstantFunctor : unary_function<T,S>
{S operator()(const T&) const {return val;}};
template<typename T>
struct TrueFunctor : ConstantFunctor<T,bool,true>{};
...
count_if(c.begin(),c.end... | If you want to count all elements in a range. then you can use std::distance, from the <iterator> header, like so:
int count = std::distance(begin(c), end(c));
It should be enough.
The online doc says about std::distance:
Calculates the number of elements between first and last.
|
7,702,857 | 7,702,880 | openGL for matrix stack | I have a win32 application, in which I want to use openGL just for its matrix stack not for any rendering. That is, I want to use openGL to specify the camera, viewport etc so that I dont have to do the maths again. While creating the scene, I just want to project the points using gluProject and use it. The projected p... | The Matrix stack could potentially live on graphics hardware in your implementation. OpenGL is quite reasonable therefore in insisting you have an OpenGL context in order to be able to use such functions. This is because the act of creating a context probably includes setting up the necessary implementation mechanics r... |
7,702,861 | 7,702,876 | c++ grade calculator console error | I am getting a segmentation fault in console while running the program
i am using codeblocks in ubuntu(linux)
it compiles with 0 errors and 0 warnings
code in pastebin
http://pastebin.com/wgSHPQjc
here is the code
#include <iostream>
#include <string>
using namespace std;
class Year
{
public:
Year(string sone, s... | int yearName[]; // array for string marks
string subjectName[]; // array for storin g subject names
These two lines should NOT compile if your compiler is Standard conformant.
Use std::vector :
std::vector<int> yearName;
std::vector<string> subjectName;
And then use push_back function to add elements to them.
Year(st... |
7,702,993 | 7,706,302 | CMAKE linking to system library | We would like to build a shared library with CMAKE system. It's something like:
lib/
CMakeLists.txt
src/
CMakeLists.txt
module/
CMakeLists.txt
module1.c
foo.c
module1.c needs some standard shared library like librt. We have
add_library(module module1.c)
target_link_libraries(module rt)
in ... | Actually what you are doing should work. If the compiler cannot find the library it may simply not be in the standard library paths. You can use the following help to specify different link_directories (-L/some/path parameter to the compiler).
cmake --help-command link_directories
Another useful thing you can do while... |
7,703,258 | 7,703,507 | Why is factorial recursive function less efficient than a normal factorial function? | I've got two functions that calculate the factorial of a number n.
I can't see why the 'normal' function needs less time to calculate the factorial of a number n.
This is the normal function:
double factorial(int n) {
double s = 1;
while (n > 1) {
s *= n;
--n;
}
return s;
}
And... | You write that the recursive function “should be less time-consuming as it doesn't create a new variable, and it does less operations”. The first assertion is pretty meaningless. Memory for local variables is typically allocated by a single subtraction operation, upon entering the function, and this takes insignificant... |
7,703,285 | 7,754,089 | Detecting when an application is being uninstalled in Windows | I have Adobe Air application that stores at user's machine sqlite files and different shared objects.The problem is that when a user runs application's uninstaller it doesn't remove that data.Adobe Air allows writing of native plugins using C++,C# ,Java etc.I would like to have a plugin that detects when this applicati... | I think that you can create a native application that knows how to install/uninstall the AIR application (using arh utility). The whole process is not easy at all, in order to do that you need to obtain approval from Adobe - read this link about redistribution and using the arh utility.
|
7,703,395 | 7,703,428 | Variadic templates mystery | Here is the code that works fine :
template<typename... Args> struct count;
template<>
struct count<> {
static const int value = 0;
};
template<typename T, typename... Args>
struct count<T, Args...> {
static const int value = 1 + count<Args...>::value;
};
now i was wondering why we need to partial specialize the cou... | With template <typename T, typename... Args> you can't create a specialisation that omits T (i.e. dd<>) — the pack can be empty, but T can't. So you declare the template as one that takes only a pack, specialise for empty pack to stop recursion, and partially specialise for <T, Args...> to unpack one type and create a ... |
7,703,427 | 7,704,025 | Move semantics and reference semantics | I'm writing a tree-like container, where each "node" has a list with branches/subtrees, currently my head looks like:
class _tree {
public:
typedef _tree* tree_ptr;
typedef std::list<_tree> _subTreeTy;
explicit _tree(const _ValTy& v, const _NameTy& n); //create a new tree
_tree(const _ValTy& v, const _... | Move semantics is about moving the internals of an object, not the object (as a typed piece of memory) itself. It's best to think about it in terms of values and invariants, since C++ still has value semantics even when moving is taken into account. This means:
std::unique_ptr<int> first(new int);
// invariant: '*this ... |
7,703,555 | 8,858,587 | Parametrized constructor in virtually inheriting abstract class | I have a classical virtual inheritance diamond:
class A {
protected:
A(const char *x) { ... }
}
class B: public virtual A {
protected:
B(): A(NULL) { ... }
public:
virtual void foo() = 0;
}
class C: public virtual A {
protected:
C(): A(NULL) { ... }
public:
virtual void bar() = 0;
}
class D: publ... | I am closing this as the rigth answer probably does not exist. IMO the best workaround is the
struct AbstractPlaceholder {
AbstractPlaceholder() {
assert(false);
}
};
class A {
protected:
A(const AbstractPlaceholder &ap) {}
A(const char *x) { ... }
};
|
7,703,597 | 7,703,722 | Performance issue with constructed classes, C++ | I am aware that this is an easy problem but I don't know how to do properly what I have in mind. I am using SFML but you don't need to understand how it works.
Here is my simple code snippet that generate tiles and assign them to a 2D-vector of tiles:
http://www.pastie.org/2665489
During the construction of the TilePla... | You have a lot of performance issues in your code. If the bottleneck indeed comes from push_back, you should take Masoud's suggestion and push pointers onto the array and not values.
Another suggestion is that you declare your functions and constructors to use references - for example:
Tile::Tile(const Tileset& tilese... |
7,703,786 | 7,704,935 | Symbols not found while building OpenCV's Hello World | I just installed openCV via MacPorts,
I also added the library folder to the compiler's settings.
But then when trying to build the following code,
#include <cv.h>
#include <highgui.h>
int main(int argc, char **argv) {
cvNamedWindow("My Window", 1);
IplImage *img = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8... | There are two separate steps to getting an OpenCV project to compile and link. First is adding the header search path in order to compile, which you've already done.
You also have to add the libraries to the project in order to link. That's this part:
Select Project -> New Group and create a group called OpenCV framew... |
7,703,790 | 7,704,062 | Alternatives to passing objects between modules | I am under the impression that, for a variety of reasons, it's not safe to pass standard library objects (templated ones in particular) between modules when they could be compiled with different versions of the standard library or different compilers. My goal now is to find a viable solution to this, particularly in th... | There is no solution besides breaking down your classes into their trivial member types, and passing them each individually, if you are using different compilers to compile your modules.
If you use the same compiler and only different versions of it, it may very well be, that the modules are already compatible (unless ... |
7,703,826 | 8,075,294 | cannot extract a double from a case insensitive string? | I am trying to come up with a case insensitive string, and I found the following on the web
http://www.gotw.ca/gotw/029.htm
So basically my code to come up with a case insensitive string is as follows
struct ci_char_traits : public std::char_traits<char> {
static bool eq( char c1, char c2 )
{ return toupper(c1... | You wrote a custom output operator "operator>>", but not an input operator "operator<<", and that's the one you need.
This works great:
ci_string str("2.0");
std::cout << str << std::endl;
because of the operator>>.
But
std::cin >> str
does not.
|
7,703,854 | 7,703,872 | Large out-of-range numbers appear in C++ rand() | Need to have an array full of random numbers within range. Code:
void fillArray(int *arr){
for(int i=0;i<(sizeof arr);i++){
arr[i] = rand() % 2 - 2;
}
}
int *arrPoint(int *arr, int max){
for (int i=0;i<max;i++){
printf("%d is %d\n",i,arr[i]);
}
return arr;
}
... | void fillArray(int *arr){
for(int i=0;i<(sizeof arr);i++){
Since arr is a pointer to an integer, sizeof arr is equivalent to sizeof (int *), which is apparently 4 (32-bits) on your platform. That's clearly not what you want. You only pass fillArray a pointer to the first element of the array.
If you need the numbe... |
7,703,880 | 7,758,013 | Suggestions for tools for tracing or profiling C++ console app execution and diffing traces | I want to perform a trace of the executions of Nmap with two different sets of command arguments and diff the results so that I can see why different paths are taken through the code.
On my Win32 XP SP3 box, the two commands nmap -F -v -d -n <target_host> and nmap -F -v -v -d -n <target_host> should take almost the sam... | Visual Studio 2010 Premium and Ultimate editions have a great tool for profiling from which the various elements of the generated reports can be exported (csv or xml).
I exported the call tree to csv and diff'd them with Beyond Compare and this has helped me a great deal.
|
7,704,144 | 7,704,235 | How do I use Glib (or Any other Library) to list all the files in a directory? | I cannot figure out how to use GLib (GIO?) to list all the files (file-names?) in a given directory. There is no good doc or tutorial. Any code snippets are welcome. If it is not possible (or too troublesome) to do this using GLib, Is there any good C or C++ third party library to do this. EXCEPT Boost.FileSystem as I ... | If you are looking for a glib example, here you go.
GDir *dir;
GError *error;
const gchar *filename;
dir = g_dir_open(".", 0, &error);
while ((filename = g_dir_read_name(dir)))
printf("%s\n", filename);
|
7,704,183 | 7,704,206 | stacklist implementation | following linked list implementation with stacks works fine
#include <iostream>
using namespace std;
class Link
{
public:
long ddata;
Link *next;
Link(long d){
ddata=d;
}
void displaylink(){
cout<<ddata<<" "<<endl;
}
};
class LinkedLis... | Your memory management is flawed - as is, it will leak because there are news but no deletes. Once you take care of the deletes, make sure you handle copies of the classes (have the rule of three in mind).
|
7,704,203 | 7,704,231 | C++ - writing directly to memory(Kernel) | I have asked pretty much the same thing before, but my post got deleted for some reason.
Anyway, I'm trying to use C++ and write a program that allows me to access directly to the memory and write stuff to it. I heard I need to do something with the kernel as that is a "bridge" that connects the OS and application (I t... | If you're interesting in working with the kernel, you're likely looking for the Windows Driver Kit, found here:
http://msdn.microsoft.com/en-us/windows/hardware/gg487428
It has a variety of lower-level tools and headers to help you write drivers and other kernel-mode code.
Typical programs obviously don't have carte bl... |
7,704,391 | 7,704,592 | Template aliases don't work | I'm trying to get template aliases to work on clang but it doesn't work although the reference sheet says it does
~~~~>$ cat template_alias.cpp
#include <vector>
using namespace std;
template<typename T>
using DoubleVec = vector<vector<T>>;
int main() { return 0; }
~~~~>$ clang template_alias.cpp -o template_alias... | Your second command (with -std=c++0x) is correct, as is your test case. You might be using a version of clang prior to its support for template aliases. You can check for this by doing:
#if __has_feature(cxx_alias_templates)
Here is a complete list of feature-test macros that clang uses:
http://clang.llvm.org/docs/L... |
7,704,395 | 7,704,864 | How does the safe bool idiom bool_type (and the safe bool idiom) work? | I was pointed to the 'safe bool idiom', and after trying to decipher what is going on (the explanation supplied on the site was not sufficient enough to grant me understanding of why it works), I decided to try to take the following code apart and make an attempt at simplifying it as much as possible. The site supplied... | Your reasoning goes wrong about here
operator void Testable::* () const //Same as bool_type, right?
This isn't correct. The type of bool_type is, as the compiler tells us in the error message:
'void (Testable::*)()const'
So, to replace it in the operator, you would need something like
operator (void (Testable::*)()... |
7,704,507 | 7,704,620 | How can OpenCV element pointer exist in Obj-C Class? | I am a new settle in Obj-C.
I want to wrap a OpenCV class in Obj-C.
I have a C++ class now, it is like:
class cxx {
private:
IplImage* image;
public:
cxx ();
void modify ();
};
Now I am rewriting in Obj-C, I get confused in the memory type of the pointers.
I put it in a class:
class obj_c:NSObjec {
Ipl... | @interface objc_c : NSObject {
IplImage * image;
}
- (id)init;
- (void)modify;
@end
That's how you make a class in objective-c. And in the body of the functions, init and modify, yes, you will be able to access the pointer. You don't have to declare properties unless you want to access an ivar from outside of the c... |
7,704,526 | 7,704,888 | Is thare in STL or BOOST map like container with find and pop operation? | I want my map to be searchable and I want to be capable to kick out from it elements that were inserted into it longest time ago (with api like map.remove(map.get_iterator_to_oldest_inserted_element()) ) like mix of queqe and map.. Is there any such container in STL or Boost?
| You can use boost::multi_index using the ordered_unique and sequence indices, as in this example.
#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/member.hpp>
// Element type to sto... |
7,704,528 | 7,704,619 | How to construct polygons from explicit equations? | Suppose I have an explicit equation that could represent an object shape in OpenGL, how should I sort of "plot" out the shape from the explicit equation?
For example, I have this explicit equation:
Both u and v are members of the real numbers.
I then tried to do this in OpenGL C++:
float maxParts = 20;
vector<float>... | You're generally going into the right direction. However you missed the crucial step, that you'll have to split down the patch into smaller quads (tesselate it). So you don't just iterate over the sampling points, you iterate over the patches and must generate 4 sampling points for each patch.
Also you need to supply t... |
7,704,589 | 7,704,782 | Basic Typelist functionality | I'm having a bit of trouble getting my head around TypeLists or lists of templates. That is:
class nulltype{};
template <typename HEAD, typename TAIL>
struct tlist
{
typedef HEAD head;
typedef TAIL tail;
};
template <class TList>
class OutputClass
{
public:
void output(Type t)
{
std::cout <... | We first need some helper templates. The first one checks if two types are the same:
template <typename T, typename U>
struct is_same
{
// Default case: T and U are not the same type
static const bool value = false;
};
template <typename T>
struct is_same<T, T>
{
// Specialization: both template arguments ... |
7,704,655 | 7,704,700 | C/C++/C# Set Window Position on a monitor | I want to move a Window (HWND) in a second monitor. The thing is that I tried many things like double the resolution or putting negative values and it never was able to put the window on my second monitor.
Any clue of how to do that in C/C++/c#
| Screen and the Form.StartPosition should get you there.
See the first answer to this post (for C#/WinForms solution): How do I ensure a form displays on the "additional" monitor in a dual monitor scenario?
|
7,704,660 | 7,704,692 | how to properly create an encryption in c++? | I have finished my program about encryption. The problem is, I need a shortcut. The program I have coded is too long and not very suitable. I'm just new to c++ programming. Can someone help me out? thanks! :) Here's my program:
#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main()
{... | You can replace that huge switch statement with this:
if (isalpha(string[ctr]))
{
int index = toupper(string[ctr]) - 'A';
cout << crypt[index];
}
else
cout << " ";
Also, do not call strlen for every iteration of the for loop, just do it once:
for(int ctr=0, len=strlen(string); ctr<len; ctr++)
{
....
}
... |
7,704,764 | 7,704,816 | Template parameters deduction with policies | I have a class that is supposed to be used to apply operators to scalars or vectors and a mix of these 2. The class works, but I have to manually pass the template parameters, while I would like them to be deducted from the constructor. The code is the following:
template <template <class,class> class OP, typename Type... | Class types can never have template arguments deduced; after all, how can the compiler know which constructors to consider before it even knows what class you are trying to create?
The solution is to write a helper function, ala std::make_pair.
template<typename T, typename U, typename V>
BinaryOperator<T, U, V> make_b... |
7,704,833 | 7,705,639 | Error caused when forking | I have the following code which forks two new processes to take the contents of the stdout of one and saves it to a file. It runs just fine and saves the file, but after it returns the following line in the calling function (no matter what it is) throws a EXC_BAD_ACCESS error. Why?
void test(vector<string> inp,int i){... | This works well for me:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/wait.h>
void test(/*vector<string> inp,int i*/){
int fds[2]; // file descriptors
long count; // used for reading from stdout
int fd; // single file descriptor
... |
7,704,870 | 7,704,903 | How to unlock boost::upgrade_to_unique_lock (made from boost::shared_mutex)? | So I had some shared_mutex and done this:
boost::upgrade_lock<boost::shared_mutex> lock(f->mutex);
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
now I want to "unlock it" or at least downgrade it to something like:
boost::shared_lock<boost::shared_mutex> lock_r(f->mutex);
How to... | If you let the upgrade_to_unique_lock go out of scope, it will automatically downgrade back to upgrade ownership.
For example
void foo() {
boost::upgrade_lock<boost::shared_mutex> lock(f->mutex);
// Do shared operations, as mutex is held upgradeable
// ...
if(need_to_get_unique)
{
boost::upgrade_... |
7,704,979 | 7,747,295 | How can I stop a DLL from terminating application servers when remote desktop sessions log off? | I have an application server (JBoss, but this also happens in Tomcat) running as a service in Windows Server 2003. It is running with the -Xrs flag.
The Java application running under the application server calls a customizable interface written in C++ via JNI (meaning we can alter this code), referencing a third-part... | I seem to have resolved it by adding an ignore handler to the stack every time the third-party DLL is called, but I fear each time I call my method, we keep adding handlers to the stack and obviously the third-party DLL does not remove its handlers. I do not know whether this is creating a memory leak.
Is there is a w... |
7,705,034 | 7,705,073 | Recursion on Integration Approximation Function | I am attempting to approximate integrals using an adaptive Trapezoidal Rule.
I have a coarse integral approximation:
//Approximates the integral of f across the interval [a,b]
double coarse_app(double(*f)(double x), double a, double b) {
return (b - a) * (f(a) + f(b)) / 2.0;
}
I have a fine integral approximation:... | I'm assuming you have currentLevel defined somewhere else. You don't want to do that. You also calculate your midpoints incorrectly.
Take a = 3, b = 5:
[a, b / 2.0] = [3, 2.5]
[a + b / 2.0, b] = 2.5, 3]
The correct points should be [3, 4] and [4, 5]
The code should look like this:
double trap(double(*f)(double x), dou... |
7,705,086 | 7,705,312 | C++ and RLE for sequences of symbols | I have difficulties with how to use RLE on sequences of symbols.
For example, I can do RLE encoding on strings like
"ASSSAAAEERRRRRRRR"
which will be transformed to:
"A1S3A3E2R8".
But I'd like to perform RLE on strings like
"XXXYYYYY(1ADEFC)(EDCADD)(1ADEFC)(1ADEFC)(1ADEFC)"
which will be transformed to:
"X3Y5(1ADEF... | You should break down this problem into smaller parts. First, you should have a function that tokenizes your stream and returns each individual part. For this example input stream:
"XXXYYYYY(1ADEFC)(EDCADD)(1ADEFC)(1ADEFC)(1ADEFC)"
this function will return the following elements, one per call:
X
X
X
Y
Y
Y
Y
Y
(1ADEFC... |
7,705,087 | 7,705,325 | Automatic conversion of C++ API to C#? | I am wondering if there is something like automatic conversion/wrapper code generation of a c++ API to C#?
Specifically I am seeking a way to call the Remote Desktop Services API from C#.
| You might try either decompiling RDCMan (http://www.microsoft.com/download/en/details.aspx?id=21101), it does it. Or there is an open source project on Codeplex that does it as well.
http://terminals.codeplex.com/
EDIT:
There is also a tool that Microsoft provides call aximp (http://msdn.microsoft.com/en-us/library/8cc... |
7,705,222 | 7,705,253 | Is it possible to remove queue element by value? | I want to remove element from queue with specific value. How to do such thing? (I am trying to create a concurrent mixture of map and queue and currently I try to implement on this answer)
So I currently have such code:
#ifndef CONCURRENT_QUEUED_MAP_H
#define CONCURRENT_QUEUED_MAP_H
#include <map>
#include <deque>
#in... | A deque is a sequence container, so you can only remove elements by value, which is best done with the remove/erase idiom:
std::deque<T> q;
T val;
q.erase(std::remove(q.begin(), q.end(), val), q.end());
If you are using the std::queue adapter, then you cannot do this at all, because the adapter only exposes the front... |
7,705,571 | 7,707,104 | Reading a mix of strings, ints and doubles from a file in C++ | I have a .txt file looking like this:
1
Some string
Some other string
3
10,5
20
20
I need to read all these values into different type of variables. As far as ints and doubles reading from file seems to be working but then it comes to strings the fun begins.
It seems that strings are read but then I try to output the... | file.open ("C:\path\file.txt");
\ is escape character
fix
file.open ("C:\\path\\file.txt");
|
7,705,621 | 7,706,112 | Passing objects (either XML output, or any C++ object types) from server to clients and vice versa through sockets | How can I pass an XML output result / other object types in C++ through sockets, and make sure that the data are not corrupted? The output size can be something between 100KB - 2MB in size. The UNIX sys/socket library would only allow me to send basic data types (like character string) as the socket message.
I know ... | If you want check that the received data is correct, you should use CRC or other error detection codings. However sockets try to guarantee it and you can feel free to check the data again. Also in network transmission, Speed and Reliability are tradeoff, you should take something between them depending on your applicat... |
7,705,660 | 7,705,706 | G++: Trying to add include and lib to default directory | I've compiled Google C++ Test. I'm now trying to add it to my g++ installation (on Cygwin) such that I don't have to specify -I, -L, and -l for every project. The steps I did were:
I put a symlink in /usr/local/include to GTEST_ROOT/include/gtest
I put symlinks in /usr/local/lib to the libs in GTEST_ROOT/lib (libgte... | You'll always need to pass -lgtest to your final compile/link step1. GCC will not search all the libraries in its search path for the symbols that it is missing (that would be way too expensive).
The library files themselves (.so or .a) need to be in the /usr/local/lib/ directory, or a symlink to those files. Symlinkin... |
7,705,724 | 7,705,793 | Shared memory in DLLs | How does sharing memory works in DLLs?
When DLL is attached to process, it uses the same memory addresses as process. Let's assume we have following function in DLL:
int * data = 0;
int foo()
{
if (!data) data = new int(random());
return *data;
}
When process A calls this function it creates new object (int) ... | You are correct, DLLs do NOT share memory across processes by default. In your example, both process A and B would get a separate instance of "data".
If you have a design where you want to have global variables within a DLL shared across all the processes that use that DLL, you can use a shared data segment as describ... |
7,705,747 | 7,705,804 | How to insert values in a c++ set | I'm trying to create a set of custom objects of the class Point
point.h
#ifndef POINT_H
#define POINT_H
class Point
{
float x_coordinate,y_coordinate;
public:
Point(float x, float y):x_coordinate(x),y_coordinate(y)
{}
float get_x()
{
r... | @Mat beat me to it to answer your specific question. So I'll just point-out some issue with your un-idiomatic C++. You don't need a conditional to return a boolean. Just return the value of what would have been your if statement:
bool operator==(const Point& rhs) const
{
return ((int)x_coordinate == (int)rhs.get_x(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.