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,609,724 | 7,610,490 | Using a library written in C++ from a pure C project on Linux? | Found this statement over at PSE: (quoting Bob)
One of my favorite tricks on Windows and Mac OS doesn't work on Linux.
That trick is to write a DLL/dylib using C++ internals, export a C
API, and then be able to call into it from C programs. Linux shared
objects (the local equivalent of a DLL) can't really do tha... | I am doing this thing all the time, and it works fine. I am pretty sure that that guy had a totally unrelated problem and blamed the library search paths for it.
I have never seen any linux distro where the libstdc++.so is not in the /usr/lib[64]/ path.
Which also makes me wonder how C++ programs generally work for th... |
7,609,940 | 7,610,061 | Storing data in memcache to be accessed by different languages | I am working on a system that has components written in the following languages:
C
C++
C#
PHP
Python
These components all use (infrequently changing) data that comes from the same source and can be cached and accesed from memcache for performance reasons.
Because different data types may be stored differently by diff... | memcached I think primarily only understands byte[] and representation of byte is same in all languages. You can serialize your objects using protocol buffers or a similar library and consume it in any other language. I've done this in my projects.
|
7,609,981 | 7,610,048 | Possible memory leak with malloc, struct, std::string, and free | I've a situation like the following, and I'm not sure whether or not the std::string elements of the struct leak memory or if this is ok. Is the memory allocated by those two std::strings deleted when free(v) is called?
struct MyData
{
std::string s1;
std::string s2;
};
void* v = malloc(sizeof(MyData));
...
M... | There is a leak indeed. free doesn't call MyData destructor (after all it's a C function which doesn't know anything about C++ stuff). Either you should use new/delete instead of malloc/free:
MyData* d = new MyData;
d->s1 = "asdf";
d->s2 = "1234";
delete d;
or call destructor by yourself:
void* v = malloc(sizeof(... |
7,610,045 | 7,610,095 | pointer becomes null when constructor finishes running | I have a camera class that has two pointers as parameters:
Camera::Camera(
float fOVDeg, float nearCull, float farCull,
float xPos, float yPos, float zPos,
D3DMATRIX* matProjection, D3DMATRIX* matView)
{
this->SetCamera(fOVDeg, nearCull, farCull);
this->AdjustCamera(xPos, yPos, zPos);
matProje... | You are passing matProjection by value, therefore, the assignments to it in the constructor assign to a local copy (which is not visible outside). Try using a reference:
Camera::Camera(
float fOVDeg, float nearCull, float farCull,
float xPos, float yPos, float zPos,
D3DMATRIX* &matProjection, D3DMATRIX* &ma... |
7,610,121 | 7,687,639 | How to be warned when overriding a virtual method with wrong visibility | When overriding a virtual method, I noticed that when I make a mistake in the visibility (protected method overridden as a public method), I'm not warned by the compiler.
It is valid C++, but usually it is a mistake.
For example:
#include <iostream>
class Base
{
protected:
virtual void ProtectedMethod(void)
{
... | I found a solution to my needs using ctags.
CTags can parse C++ and dump information to a file.
Using the following options:
$CTAGS -f $TAGFILE --fields=fkstia --c++-kinds=+p -R $SOURCES
I can get all the needed information in an easily parseable format.
Piping $TAGFILE through a few grep commands, I can verify that ... |
7,610,283 | 7,610,907 | Expose Member Data Through Read-only Iterator | I have a class 'MyClass' which contains some data stored in std::maps. The standard maps contain pointers to objects, e.g.
private:
std::map<int,Object*> m_data;
I want to expose the data to the outside world but I do not want other classes/functions to be able to modify either (i) the map m_data or (ii) the object... | Try exposing a boost transform_iterator wrapped around the map's const_iterator. The transform function should be something like
[](const pair<int, object*>& x)
{
return make_pair(x.first, const_cast<const object*>(x.second));
}
|
7,610,668 | 7,610,690 | Are there any advantages to making a free static function? | I have a .cpp file which has some static free functions. I know how that would help in a header file, but since the cpp is not included anywhere, what's the point? Are there any advantages to it?
| Declaring free functions as static gives them internal linkage, which allows the compiler more aggressive optimizations, as it is now guaranteed that nobody outside the TU can see that function. For example, the function might disappear entirely from the assembly and get inlined everywhere, as there is no need to provi... |
7,610,868 | 7,610,961 | modifying least significant bits in double (Java and C++) | How to set to zero N least significant bits of a double in Java and C++?
In my computations, the "...002" in 1699.3000000000002, is caused by numerical error, so I would like to eliminate it.
| In Java, 1e-12*Math.rint(1e12*x) will round a double and return a double as the result.
In C++, you can write 1e-12*floor(1e12*x + 0.5).
Note, however, that these behave differently if 1012x is exactly between two integers. The Java version will round towards an even number, whereas the C++ version will always round up... |
7,611,153 | 7,611,671 | glutBitmapString() was not declared in this scope | when i try to plot some strings with the following code:
// label min and max for current vector
glRasterPos2f(nx+1,y1);
glutBitmapString(GLUT_BITMAP_8_BY_13,"min");
glRasterPos2f(nx+1,y2);
glutBitmapString(GLUT_BITMAP_8_BY_13,"max");
i get the error
error: ‘glutBitmapString’ was not declared in ... | What implementation of Glut are you using? According to the FreeGlut documentation, the original Glut does not include glutBitmapString
http://freeglut.sourceforge.net/docs/api.php#FontRendering
And indeed, there is no mention of glutBitmapString in the Glut documentation
http://www.opengl.org/resources/libraries/glut... |
7,611,168 | 7,611,273 | How can I determine if a compiler uses early or late binding on a virtual function? | I have the following code:
class Pet {
public:
virtual string speak() const { return ""; }
};
class Dog : public Pet {
public:
string speak() const { return "Bark!"; }
};
int main() {
Dog ralph;
Pet* p1 = &ralph;
Pet& p2 = ralph;
Pet p3;
// Late binding for both:
cout << "p1->speak() = " << p1->speak... | You can look at the disassembly, to see whether it appears to be redirecting through a vtable.
The clue is whether it calls directly to the address of the function (early binding) or calls a computed address (late binding). The other possibility is that the function is inlined, which you can consider to be early bindin... |
7,611,198 | 7,611,392 | Adding .lib files in Microsoft Visual Studio 2010 | I just downloaded Visual Studio 2010, and they changed a lot since Visual Studio 2008. These options were changed: the header includes, the lib directory to add, and all changed.
I followed a series of tutorials to do that, but in the other version I just had to add the mylib.lib string in the textfield, but now I look... | If you're looking for how to get a lib file imported in to your project, you can do this either by editing the project settings, under Linker>Input:
...or you can use a #pragma...
#pragma comment( lib, "MyLib.lib" )
I typically add this right in to the header file for the library I want to import. Alternatively, you... |
7,611,416 | 7,612,120 | How do I run POCO C++ server pages? | I'm a beginner in C++ server pages. I have tried C++ Server Pages by micronovae, but couldnt connect ODBC it used to give link error "undefined reference to SQLAllocHandle@12", I could not resolve it. Similar to micronovae,POCO also provides C++ Server Pages. so thought of try it. I tried one sample from http://pocopr... | The samples you show only create the individual page (handler) implementation.
You need to add an actual HTTPServer to serve that page.
See: http://pocoproject.org/docs/Poco.Net.HTTPServer.html
There is a sample in the sources download under
poco-1.4.2p1.zip\poco-1.4.2p1\Net\samples\HTTPTimeServer
You should be able ... |
7,611,468 | 7,611,514 | Difference between two methods of creating of 2d array | What is the difference between two arrays definitions? Are they realized different in memory?
int var = 5;
int (*p4)[2] = new int [var][2]; // first 2d array
int** p5 = new int*[var]; // second 2d array
for(int i = 0; i < var; ++i){
p5[i] = new int[2];
}
| Yes, they're very different. The first is really a single array; the second is actually var+1 arrays, potentially scattered all over your RAM. var arrays hold the data, and one holds pointers to the var data arrays.
|
7,611,550 | 7,636,348 | Why would an Overlapped call to recv return ERROR_NO_MORE_ITEMS(259)? | I did a few tests with an I/O-Completion port and winsock sockets.
I encountered, that sometimes after I received data from a connection and then adjacently call WSARecv again on that socket it returns immediately with the error 259 (ERROR_NO_MORE_ITEMS).
I am wondering why the system flags the overlapped transaction w... | It looks like I was sending less data than was requested by the receiving side.
But since it´s an overlapped operation receiving a small junk of the requested bunch via the TCP-connection would trigger the completion indication with the error ERROR_NO_MORE_ITEMS, meaning there was nothing more to recv than what it alre... |
7,611,628 | 7,611,695 | Output precision is higher than double precision | I am printing some data from a C++ program to be processed/visualized by ParaView, but I am having a problem with floating point numbers. Paraview supports both Float32 and Float64 data types. Float64 is equivalent to double with the typical limits +/-1.7e +/- 308. But, my code is printing numbers like 6.5e-318. This ... | Subnormal numbers, i.e. numbers with the smallest-possible exponent and leading zeros in the fraction, can be smaller than 1E-308, down to 1E-324. You can probably filter them out using std::numeric_limits.
|
7,611,699 | 7,611,753 | Regarding the differences between malloc and new in terms of their respective mechanisms of handling memory allocation? | What are the differences between malloc and new in terms of their respective mechanisms of handling memory allocation?
|
malloc doesn't throw bad_alloc exception as new does.
Because malloc doesn't throw exceptions, you have to check its result against NULL (or nullptr in c++11 and above), which isn't necessary with new. However, new can be used in a way it won't throw expections, as when function set_new_handler is set
malloc and f... |
7,612,006 | 7,612,076 | Is this a cast or a construction? | I'm a little confused after reading something in a textbook. Regarding the code:
void doSomeWork(const Widget& w)
{
//Fun stuff.
}
doSomeWork(Widget(15));
doSomeWork() takes a const Widget& parameter. The textbook, Effective C++ III, states that this creates a temporary Widget object to pass to doSomeWork. It ... | In C++ this kind of expression is a form of a cast, at least syntactically. I.e. you use a C++ functional cast syntax Widget(15) to create a temporary object of type Widget.
Even when you construct a temporary using a multi-argument constructor (as in Widget(1, 2, 3)) it is still considered a variation of functional ca... |
7,612,072 | 7,612,205 | Inheritance... C++ syntax | I have to make a trivial class that has a few subclasses and one of those subclasses has it's own sublcass.
AccountClass.h
#ifndef Account_h
#define Account_h
class Account{
public:
//Account(){balance = 0.0;}; Here's where the problem was
Account(double bal=0.0){ balance = bal;};
double getBal(){return... | There are multiple errors in the way you defined your constructors.
Some of them don't have a body defined
The intialisation lists are syntaxicaly not at the right place
You try to define two default constructor by using default valued parameters.
The initialisation list goes between the signature and the body.
Like... |
7,612,075 | 7,613,459 | How to use C++11 uniform initialization syntax? | I cannot understand when and how to use the new uniform initialization syntax in C++11.
For example, I get this:
std::string a{"hello world"}; // OK
std::string b{a}; // NOT OK
Why does it not work in the second case? The error is:
error: no matching function for call to ‘std::basic_string<char>::basic_string(<brace ... | The compile error for
// T t{u};
std::string a;
std::string b{a};
Is a combination of four things
The draft until not long ago said that if T has an initializer list constructor (std::string has one, taking char elements), that the initializer list is passed itself as an argument. So the argument to the constructor(s... |
7,612,233 | 7,613,167 | Windows Listen to service Status Changed | How Can I make an app that listens to services for Service Status Changed event. (I don't want repeated checking on of all services)
EDIT
I need it to work on Windows XP / 2000
| You are looking for NotifyServiceStatusChange which requires Vista. On 2000/XP you will need to poll.
|
7,612,297 | 7,612,335 | Can I reuse a TCP connection? | I'm connecting to a website and retrieving HTTP data by sending it a GET request. And I have to connect to the same site twice to retrieve two different pages. I'm new to network programming but I believe the connect function connects to the server, and creates a tcp connection.
Now each time I connect to the server to... | You could use HTTP 1.1 where connection are persistent or use HTTP 1.0 and send the header "Connection: Keep-Alive".
That way you can fetch a second page without connecting again (just GET again on the same socket).
|
7,612,376 | 7,612,845 | EXC_BAD_ACCESS when using VBO | I've made some rendering with out using VBO. Now i want to add VBO for more complex rendering. I'm just creating a VBO now, keeping the old rendering as it was and i render nothing with VBO now. Here is the code:
GLuint bufId;
glGenBuffers(1, &bufId);
glBindBuffer(type, bufId);
glBufferData(type, size, 0, GL_STATIC_DRA... | I've found the problem. You have to unbind VBO if you want to draw with out it:
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
after that everything worked
|
7,612,395 | 7,616,818 | Which `boost::system::error_code` value should be provided when `boost::asio::ip::tcp::resolver::resolve()` fails? | I want to return a boost::system::error_code indicationg whether a host/service could be resolved or not. There might be multiple reasons why a host/service look-up failed (e.g. network connection problems or an invalid argument).
What should be returned?
| It's impossible to get this right from outside resolve(). But you can get it to do it for you, by using one of the overloads that takes an error_code& as an out-parameter:
iterator resolve(const query & q, boost::system::error_code & ec)
iterator resolve(const endpoint_type & e, boost::system::error_code & ec)
and t... |
7,612,406 | 7,683,957 | MPI distribution layer | I used MPI to write a distribution layer. Let say we have n of data sources and k of data consumers. In my approach each of n MPI processes reads data, then distributes it to one (or many) of k data consumers (other MPI processes) in given manner (logic).
So it seems to be very generic and my question is there somethin... | As far as I know, there is no generic implementation for it, other than the MPI API itself. You should use the correct functions according to the problem's constraints.
If what you're trying to build a simple n-producers-and-k-consumers synchronized job/data queue, then of course there are already many implementations ... |
7,612,428 | 7,612,472 | Difference between uint8_t and unspecified int for large matrices | I have a matrix that is over 17,000 x 14,000 that I'm storing in memory in C++. The values will never get over 255 so I'm thinking I should store this matrix as a uint8_t type instead of a regular int type. Will the regular int type will assume the native word size (64 bit so 8 bytes per cell) even with an optimizing... | The standard doesn't specify the exact size of int other than it's at least the size of short. On some 64-bit architectures (for example many Linux and Solaris x86 systems I work with) int is 32 bits and long is 64 bits. The exact size of each type will of course vary by compiler/hardware.
The best way to find out is t... |
7,612,574 | 7,612,634 | Destructor for pointer to fixed size array | Suppose I have a C++ class with two private variables. A fixed size array, data, and a pointer to that array, pnt.
class MyClass
{
private:
double *pnt;
double data[2];
public:
myClass();
virtual ~MyClass();
double* getPnt() const;
void setPnt(double* input);
};
MyClass::MyCla... | I see no static array. I see a fixed-size array. Also memory for data is allocated as part of the object.
You must not explicitely delete a member of the class: the delete operator will take care of that IFF the instance was dynamically allocated.
{
MyClass x; // auto variable
} // x destructor run, no delete o... |
7,612,584 | 10,676,060 | Macros for Build Commands and Properties in Visual Studio 11 | Three-part question first:
Are the build-time macros fully fleshed out in Visual Studio 11?
How can I edit & define them in the IDE?
How can I let the macros still have their meaning during the Debugging session?
Note that I'm referring to the build-time macros such as $(ProjectDir), not the IDE macros used to rec... | If you haven't already figured out how to do this, you need to use your own property sheets.
Make a new property sheet, and use the section in Common Properties > User Macros.
For example, I have a macro called BOOST_VER in a property sheet called IncludeBoost.props that I set everything in.
User Macros
Name Valu... |
7,612,628 | 7,612,656 | Can Someone Explain This Snippet (Why Are These Braces Here)? | I apologize for this overly simplistic question, but I can't seem to figure out this example in the book I'm reading:
void f5()
{
int x;
{
int y;
}
}
What are the braces surrounding int y for? Can you put braces wherever you want? If so, when and why would you do so or is this just an error in th... | Braces like that indicate that the code inside the braces is now in a different scope. If you tried to access y outside of the braces, you would receive an error.
|
7,612,834 | 7,612,903 | Pointers of two dimensional array | There is such code:
int (*ptr_)[1] = new int[1][1];
ptr_[0][0] = 100;
std::cout << "to: " << &ptr_ << ' ' << ptr_ << ' ' << *ptr_ << ' ' << &(*ptr_) << ' ' << **ptr_ << std::endl;
Result is:
to: 0xbfda6db4 0x9ee9028 0x9ee9028 0x9ee9028 100
Why values of ptr_ and *ptr_ are the same? Value of ptr_ equals to 0x9ee9028, ... | ptr_ is a pointer to an array of length one. Variables of array type in C and C++ simply degrade to pointers when printed (among other things). So when you print ptr_ you get the address of the array. When you print *ptr_ you get the array itself, which then degrades right back into that same pointer again.
But in C++ ... |
7,613,082 | 7,613,113 | C++ exceptions in main | My class Person has different files as attributes.
class Person {
private:
fstream history;
fstream familyTree;
public:
Person() {
history.open("history.dat");
familyTree.open("tree.dat");
}
}
I need my program to return different values if any of the files couldn't be opened.
If hist... | You could throw exceptions in your constructor and catch them in main. Or you could catch the exceptions in your constructor and fix it so that the class can be correctly initialised whatever happens.
To make your class more testable, the constructor should do as little work as possible. I would have two methods:
... |
7,613,125 | 7,613,672 | How to make a transparent window with Qt Quick? | Is there a way to make the window of a qml application transparent?
I'm looking for a detailed description on how to draw simple shapes with qml while making the window of the application transparent, as well as the background. A working source code demo would be awesome.
| I finally found a simple way to draw a couple of red/blue rectangles while leaving the window transparent.
draw_rectangles.qml
import Qt 4.7
Item {
Rectangle {
opacity: 0.5
color: "red"
width: 100; height: 100
Rectangle {
color: "blue"
x: 50; y: 50; ... |
7,613,158 | 7,613,228 | Inheritance behavior issue | I've been reading about inheritance but I still dont have it 100% clear, here goes my question:
I have for example a class full of stuff:
class Something
{
public:
Something();
Something(int A);
Something(Something S);
~Something();
Something& operator=(const Something & s);
Something operato... | You don't have to repeat for methods. but for constructor, you have to define them properly in the sub class. Anyway the code is boiler plate unless you have anything extra.
SomethingMore::SomethingMore(int i_):Something(i_)
{
}
|
7,613,225 | 7,613,271 | Converting Bitmap to a vector of unsigned char | As the title says, I'm trying to find a method of converting a GDI+ Bitmap to a vector of unsigned chars, any help would be greatly appreciated.
| Have a look at Bitmap::LockBits. Once you've locked the bits, it should be trivial to copy them to a vector<unsigned char>. Better yet, resize the vector to the required size and let LockBits copy directly to it.
|
7,613,295 | 7,613,556 | pattern recognition and string matching | I have two files taken from two different server. In these two files are presents the matches of some football teams. As you know football teams can be called with differents names.
I would like implement a code that can recognise the same football match in the two files in order to take same variables from a file and... | Very simple script to replace aliases for teams. You'll need to fill it with aliases yourself, I made some up. If you have multiple games, the hash will overwrite the existing ones, as long as all the aliases are exchanged for full names.
#!/usr/bin/perl
use strict;
use warnings;
my %games;
while (<DATA>) {
chomp;... |
7,613,336 | 7,613,565 | c++ inheritance: error C2614 calling base class' constructor | I have a base class 'A' which has a subclass 'B' which has a subclass 'C' which has a subclass 'D'.
I want D to call 'A's constructor,
D(int x,int y):A(x,y){};
but I am getting the error message:
error C2614: 'D' : illegal member initialization: 'A' is not a base or member.
D can call any of 'C's constructors fine but... | As Mark Ransom's answer states, a derived class is only allowed to call its base class' constructor.
In your case, you can solve the problem by passing along the constructor arguments to D down the inheritance hierarchy until A's constructor is called by B with those arguments.
Another option is to create a protected ... |
7,613,386 | 7,613,919 | C++ Type Traits Overview | Has anybody put together a list of all the type traits available in standard <type_traits> (GCC-4.6.1) and Boost's own <boost/type_traits.hpp>?
| The full lists of traits are available online:
The Boost documentation lists the traits in <boost/type_traits.hpp>;
The C++0x draft lists the traits in <type_traits>.
However, the GCC implementation is not yet complete. GCC 4.6 is missing:
The std::underlying_type trait. This one will be on GCC 4.7.
The std::is_triv... |
7,613,423 | 7,613,466 | c++ win32 prevent application from running on windows xp | I've developed a application which uses Vista (or higher) API's and i would like to add a popup message if the application detects a unsupported OS.
I would like to add a popup message when a user runs my application on windows XP. Currently the application just throws a popup(messageBox) saying that some DLL's can't b... | In order to show a popup message, you need to run the executable. That means that you have to reduce your windows version to the lowest one you intend to 'support' (support here meaning be able to run at, and show a popup saying that it won't run). That would require you to delay the point were you link to your relevan... |
7,613,516 | 7,614,080 | algorithms for modular inverses | i have read section about The Extended Euclidean Algorithm & Modular Inverses,which states that it not only computes GCD(n,m) but also a and b such that a*n+b*b=1;
algorithm is described by by this way:
Write down n, m, and the two-vectors (1,0) and (0,1)
Divide the larger of the two numbers by the smaller - call ... | The division is supposed to be integer division with truncation. The standard EA for gcd(a, b) with a <= b goes like this:
b = a * q0 + r0
a = r0 * q1 + r1
r0 = r1 * q2 + r2
...
r[N+1] = 0
Now rN is the desired GCD. Then you back-substitute:
r[N-1] = r[N] * q[N+1]
r[N-2] = r[N-1] * q[N] + r[N]
= (r[N] * q... |
7,613,528 | 7,613,736 | Restrict passed parameter to a string literal | I have a class to wrap string literals and calculate the size at compile time.
The constructor looks like this:
template< std::size_t N >
Literal( const char (&literal)[N] );
// used like this
Literal greet( "Hello World!" );
printf( "%s, length: %d", greet.c_str(), greet.size() );
There is problem with the code howe... | There is a way to force a string literal argument: make a user defined literal operator. You can make the operator constexpr to get the size at compile time:
constexpr Literal operator "" _suffix(char const* str, size_t len) {
return Literal(chars, len);
}
I don't know of any compiler that implements this feature ... |
7,613,885 | 7,613,957 | awkward DLL exports section | I have a section of C++ code in MSVC2010 that creates a DLL wrapper. The section of code looks something like this...
extern "C" __declspec(dllexport) DWORD myDllExportFunction()
{
return (DWORD)SomeFunction(SomeParameter);
}
or...
_declspec(dllexport) int64 _stdcall myDllExportFunction2(<someType> someParameter)... | Try turning off debug information generation.
|
7,614,052 | 7,614,182 | Sending booleans over the internet (Windows & Linux) | I'm sending information from my server to clients and back again using packed structs (obviously there are a lot more data in the structs)
#pragma pack(push, 1)
struct other_data_struct
{
int hp;
int wp;
char movetype;
}
struct PlayerStats
{
int playerID;
other_data_struct data;
bool friendly; //<-this one messes ... | You could try bitfields, that way your packed struct contains 'int', but your code uses a more space-efficient representation.
I believe bitfields have some awful performance characteristics, so they may not be the way to go if you care more about access time than space usage.
|
7,614,184 | 7,614,253 | Why doesn't (&array)[i] take the address of the ith element? | Consider the following code
int tab2[2];
tab2[0]=5;
tab2[1]=3;
std::cout << tab2[1] << std::endl;
std::cout << (&tab2)[1] << std::endl;
As I have read in other topics, an array can decay to pointer at its first element. Then why doesn't the [] doesn't work the same for tab2 and &tab2 in the above code? What is differe... | It's already "converted" as a pointer. You can use the [] notation with arrays or pointers...
(&tab2) means you get the address of your array... In a pointer perspective, it's a pointer to a pointer ( ** ).
So you are trying to convert a variable (which is an array) as a pointer. Ok, but then you try to access the [1] ... |
7,614,286 | 7,615,698 | How do I get CMake to create a dll and its matching lib file? | I'm using CMake to create a shared library via Visual Studio 2010. The solution outputs a dll file, but not a matching lib file. How do I tell CMake to generate the lib file so I can link other projects to the dll?
| First of all check that you have at least one exported symbol in your shared library. Visual Studio does not generate the .lib file if dll does not exports symbols.
Next, check your cmake files - probably you have set CMAKE_ARCHIVE_OUTPUT_DIRECTORY variable or ARCHIVE_OUTPUT_DIRECTORY property of the shared library tar... |
7,614,517 | 7,622,914 | Cross platform build system with IDE? | I've been searching since around a year for a combination of C++ build system and IDE which brings the following features:
Cross plattform build system that builds atleast on Windows, Linux and Mac OS.
Some sort of inteligent code completion (IntelliSense of Visual Studio, that thing fromEclipse).
Debugger integrated ... | Here is what I ended up doing:
I stuck to CMake over qmake, since it simply seems more powerful, and is easy to install seperatly. Also both only generate Makefiles so they pretty much do the same for me.
Since the Eclipse/VisualStudio project files created by CMake are only there for building I couldn't use them (run... |
7,614,520 | 7,614,663 | Strange bug in usage of abs() I encountered recently | I have C++/C mixed code which I build on
a) Visual C++ 2010 Express(Free version) on Win-7 x32.
b) Cygwin/Gcc environment installed on a Windows-7 Home premium edition x32. The gcc version 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)
c) Ubuntu 10.04 Linux- GCC version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)
I have a code a... | math.h has the C version of abs which operates on ints. Use <cmath> for the C++ overloads or use fabs() for the C floating point version.
|
7,614,606 | 7,667,161 | Solving hid.lib "unresolved external symbol" linker errors in VC++ | As the title suggests, I am having the following linker error:
error LNK2019: unresolved external symbol "unsigned char __stdcall
HidD_GetAttributes(void *,struct _HIDD_ATTRIBUTES *)"
(?HidD_GetAttributes@@YGEPAXPAU_HIDD_ATTRIBUTES@@@Z)
when calling result = HidD_GetAttributes(WriteHandle, &attributes) in my code... | Just solved the problem. Apparently "hid.lib" was written in C which was resulting in some name mangling. Using
extern "C"
{
#include "hidsdi.h"
}
cleared everything up.
|
7,614,632 | 7,614,730 | After writing to a stringstream, why does extracting into a string cause that string to become bogus? | I'm encountering a puzzling bug involving stringstream. I've got a object whose properties I want to dump to a file using dumpState(). This object has a number of member objects, each of which has had operator<< defined for them. Here's the code:
void dumpState(int step){
stringstream s;
s << DUMP_PATH << step;
s... | you should use an ostringstream and call s.str() to get the contents.
|
7,614,633 | 7,618,389 | How to make a function template the least priority during ADL? | I have a problem where I'd like to provide a generic version of a function foo which may only be applied when there is absolutely no other match for an invocation. How can I modify the following code such that last_resort::foo is a worse match for derived::type than base::foo? I'd like to find a solution which does not... | last_resort::foo can be removed from the overload set with disable_if. The idea is to disable last_resort::foo(T) if foo(T) is otherwise well-formed. This causes last_resort::foo(T) to be the worst match for foo:
namespace test
{
template<typename T> struct has_foo { ... };
}
namespace last_resort
{
template<typena... |
7,614,682 | 7,614,747 | Marshal structure with integer references to C# | Hi I'm trying to create and marshal the following structure from C# into C++ and maintain the linked reference. I'm unsure how this structure should be defined in C#? In C++ the structure must look like below, with the const reference maintained.
// C++
struct {
int a; // my value
const int& b = a;... | This should work:
[StructLayout(LayoutKind.Sequential)]
public struct MyCStruct {
public int a;
public IntPtr b;
}
|
7,614,683 | 7,614,794 | error accessing elements of array of std::pair | I have defined an array of pairs as following:
std::pair<int,int> delta[4];
delta[0] = std::make_pair(0,1);
delta[1] = std::make_pair(1,1);
delta[2] = std::make_pair(1,0);
delta[3] = std::make_pair(1,-1);
but when I try to access the elements like:
delta[2].first
I get an error as following :
binary '[' : 'std::pair<... | You method signature only specifies a reference to a single std::pair instance. You would probably want your signature to look something like the following if you want to pass an array of std::pair.
int who_won(std::pair<int,int> delta[],std::vector<std::vector<int>> &grid)
|
7,614,755 | 7,614,961 | How to synchronize access to a global variable with very frequent reads / very rare writes? | I’m working on debug logging infrastructure for a server application. Each logging point in source code specifies its level (CRITICAL, ERROR, etc.) among other parameters.
So in source code logging point looks as:
DBG_LOG_HIGH( … )
which is a macro that expands to
if ( CURRENT_DEBUG_LOG_LEVEL >= DEBUG_LOG_LEVEL_HIGH )... | There is nothing that requires that a write made on one thread on one core will ever become visible to another thread reading on another core, without providing some sort of fence to create a 'happens before' edge between the write and the read.
So to be strictly correct, you would need to insert the appropriate memory... |
7,614,852 | 7,614,916 | String Comparison return value (Is is used in applications that sorts characters ?) | When we use strcmp(str1, str2); or str1.compare(str2); the return values are like -1, 0 and 1, for str1 < str2, str1 == str2 or str1 > str2 respectively.
The question is, is it defined like this for a specific reason?
For instance, in binary tree sorting algorithm, we push smaller values to the left child and larger v... | The purpose of having three return values is exactly what it seems like: to answer all questions about string comparisons at once.
Everyone has different needs. Some people sometimes need a simple less-than test; strncmp provides this. Some people need equality testing; strncmp provides this. Some people really do need... |
7,614,866 | 7,614,899 | C++ Template Instantiation - Why must mine always be explicit, unlike STL? | Any one of my C++ projects will generate a linker error unless I include an explicit template instantiation for every templated class/method/function I author and use.
STL classes seem to have no such problem.
Is there some simple code of conduct (pun intended) I can adhere to which allows deferred instantiation like t... | For templates you need to put all the template code and methods into headers rather than source files. The standard library does this.
|
7,614,972 | 7,615,048 | Can changes to a dll be made, while keeping compatibility with pre-compiled executables? | We have a lot of executables that reference one of our dlls. We found a bug in one of our dlls and don't want to have to re-compile and redistribute all of our executables to fix it.
My understanding is that dlls will keep their compatibility with their executables so long as you don't change anything in the header fil... | Your understanding is correct. So long as you change the logic but not the interface then you will not run into compatibility issues.
Where you have to be careful is if the interface to the DLL is more than just the function signatures. For example if the original DLL accepted an int parameter but the new DLL enforced ... |
7,615,369 | 7,615,552 | Can't initialize struct with nested pointers to other structs | I'm using a third party library which defines this struct:
typedef struct
{
unsigned short nbDetectors;
//! structure of detector status
struct DetectorStatus
{
unsigned int lastError; //< last detector internal error
float temperature; //< detector temperature
... | if you want to have everything on the stack this should do it:
// Getting structs on the stack initialized to zero
HardwareStatus status = { 0 };
HardwareStatus::DetectorStatus detectorStatus = { 0 };
HardwareStatus::DetectorStatus::EnergyStatus energyStatus = { 0 };
HardwareStatus::DetectorStatus::GridStatus gridStatu... |
7,615,443 | 7,615,865 | Using boost::asio to find all reachable ips on a subnet | I would like a way to use boost to find all reachable ips(responding to a ping) on a subnet.
i.e. given subnet = 10.10.10.0 and ips 10.10.10.1-5 that are reachable, the result should be a list: 10.10.10.1 , ... , 10.10.10.5
Currently I have a script that pings the subnet and checks the arp cache for reachable ips.
| They have a ping example in the docs.
|
7,615,541 | 7,615,580 | Rule of three with smart pointer? | I'm a little confused by using "rule of three" with smart pointers. If I have a class whose only data member is a smart pointer, do I need to explicitly define destructor, copy constructor, and assignment operator?
My understanding is that since smart pointer will handle the resource automatically, then I don't need to... | The default destructor is fine, because the destructor of shared_ptr will take care of the deallocation of the object. The default copy constructor may be acceptable depending on your purposes: when you copy the object that owns the shared_ptr, the copy will share ownership with the original. The same would naturally b... |
7,615,615 | 7,615,673 | Setting the szTip field of the NOTIFYICONDATA structure | The szTip field is 128 characters long, and unicode. It is of type TCHAR, which is typedef'd as WCHAR. So i have no clue why the following code snippet will not compile.
nid.szTip = _T("ToolTip");
The compile error is
error C2440: '=' : cannot convert from 'const wchar_t [8]' to 'WCHAR [128]'
Any advice?
| Your code would work if you were assigning to a TCHAR*. However, szTip is not a TCHAR*, it is declared as TCHAR szTip[64].
So you need to copy the contents of the string to the buffer. Like this:
_tcscpy(nid.szTip, _T("ToolTip"));
Do you really need to support both ANSI and Unicode builds? If not then stop using TCH... |
7,616,062 | 7,616,079 | C++ Strong Random Number Generator - necessary? | My newest project is the development of a text based RPG and now I need a random number generator, a good one to compute in different situations whether some action can be performed without problems or not. Everyone of us knows, that the basic functions std::srand and std::rand are simple and easy algorithms to compute... | My suggestion is to use Boost.Random. It has a number of quite good (and fast) RNGs. You don't need a cryptographically secure one, but the ones they offer are better than rand.
I'd go with mt19937 myself. It has a long period and is pretty fast. But Boost.Random has lots of these things, for most of your non-cryptogra... |
7,616,132 | 7,617,025 | Get SFML cross-platform typedefs in SWIG | I'm writing an C++ game and I'm connecting it with Lua. The tool I chose for this task was SWIG, since I want to make my game available to be written in python or some other language. I'm also using SFML 1.6 as the API for multimedia access. This game is also intended to be cross-platform compilable. I'm working at the... | Any types defined in limits.h are not standard and probably shouldn't be relied on. If you want cross-platform fixed size integer typedefs, the C++11 standard library provides the cstdint header. This header gives you typedefs for signed and unsigned 8, 16, 32, and 64-bit integers: int32_t, uint32_t, int8_t, and so on.... |
7,616,263 | 7,616,928 | QDateTime::fromString not accepting my QString? | I have a .txt file which is filled with lines like this below:
2011-03-03 03.33.13.222 4 2000 Information BUSINESS ...etc blabla
2011-03-03 03.33.13.333 4 2000 Information BUSINESS ...etc blabla
2011-03-03 03.33.13.444 4 2000 Information BUSINESS ...etc blabla
In some point in my code i do some calcula... | Your string has extra characters, most likely a space in the beginning. Your format string is 23 characters and you are using left(24), so there must be one extra character. You said in the comment to Stephen Chu's answer that changing 24 to 23 dropped the last millisecond character, so the extra character must be in t... |
7,616,281 | 7,616,425 | Linker error while implementing pimpl idiom | Edited to provider a little more clarity. Apologies for confusing everyone.
This is under Windows.
I have a static library that implements a class using the pimpl idiom. The pimpl header is not only used by the consuming code but it also links against the static library. Yet, when I compile the consuming code (.exe), t... | When you create a static library, the linker doesn't try to resolve everything that is missing; it assumes you'll be linking it later to another library, or that the executable itself will contribute some missing function. You must have forgotten to include some crucial implementation file in the library project.
The o... |
7,616,374 | 7,616,463 | how to "usb to tty"? | I'm new to the C++ world but have strong knowledge in several languages (so i'm not THAT lost). I just received an usb missile launcher as a gift and wanted to control it via different platforms, including web. To do so, i was planning to use a "serial to socket" proxy i wrote in python (and then use socket after that.... | on linux it is easy to access the usb ports directly using the libusb-dev package and tools. Of course commands etc... are vendor specific but there exist already libs for perl and python to control various usb missle launchers. E.g.:
http://code.google.com/p/pymissile/
https://metacpan.org/pod/Device::USB::MissileLaun... |
7,616,475 | 7,621,535 | Can Google Mock a method with a smart pointer return type? | I have a factory that returns a smart pointer. Regardless of what smart pointer I use, I can't get Google Mock to mock the factory method.
The mock object is the implementation of a pure abstract interface where all methods are virtual. I have a prototype:
MOCK_METHOD0(Create, std::unique_ptr<IMyObjectThing>());
And I... | Google Mock requires parameters and return values of mocked methods to be copyable, in most cases. Per boost's documentation, unique_ptr is not copyable. You have an option of returning one of the smart pointer classes that use shared ownership (shared_ptr, linked_ptr, etc.) and are thus copyable. Or you can use a raw ... |
7,616,482 | 7,617,538 | is there an API for GIT (C++ or other languages) | A company asked me to program a GIT wrapper for them.
The people there have absolute no versioning systems experience, but it will be incorporated in their daily routine eventually (through my program).
I'm planning on using VC++ to create a tiny windows applet that will help ppl in this process. Any thoughts on that?... | For almost (but not all!) use cases, libgit2 is the easiest way to interact with Git repositories via code.
|
7,616,510 | 7,616,718 | Can you set a maximum limit to an integer (C++)? | If I never want an integer to go over 100, is there any simple way to make sure that the integer never exceeds 100, regardless of how much the user adds to it?
For example,
50 + 40 = 90
50 + 50 = 100
50 + 60 = 100
50 + 90 = 100
| Here is a fairly simple and fairly complete example of a simple ADT for a generic BoundedInt.
It uses boost/operators to avoid writing tedious (const, non-assigning) overloads.
The implicit conversions make it interoperable.
I shunned the smart optimizations (the code therefore stayed easier to adapt to e.g. a modulo... |
7,616,511 | 7,616,820 | Calculate mean and standard deviation from a vector of samples in C++ using Boost | Is there a way to calculate mean and standard deviation for a vector containing samples using Boost?
Or do I have to create an accumulator and feed the vector into it?
| Using accumulators is the way to compute means and standard deviations in Boost.
accumulator_set<double, stats<tag::variance> > acc;
for_each(a_vec.begin(), a_vec.end(), bind<void>(ref(acc), _1));
cout << mean(acc) << endl;
cout << sqrt(variance(acc)) << endl;
|
7,616,530 | 7,616,574 | Operator overloading equivalent in C++ for PHP, echo/print class variable for default output | I don't know how to really ask this because I am fairly new to programming in comparison to many of you. What I am looking for is a default printing or echoing of a class. I'll give you the c++ equivalent.
ClassName varClass(param);
cout << "Default print: " << varClass << endl;
As you can see in that brief example... | You can define a __toString method that defines the behavior of the object in case it is cast to a string.
public function __toString() { return $this->customPrintFunction(); }
|
7,616,714 | 7,659,560 | access QWebPage object from WebView QML element | Is there a way to access the QWebPage object from WebView's underlying QWebView object?
QWebView has:
QWebPage * QWebView::page () const
src: http://doc.qt.nokia.com/4.7-snapshot/qwebview.html#page
However it doesn't seem to be exposed in QML
| I haven't tryed it, but ...
In qdeclarativewebview_p.h at line 59 there is defined as public:
159 QWebPage *page() const;
160 void setPage(QWebPage *page);
So you should be able to access this at least from C++ (but not directly from QML).
If you need it in QML, you can inherit the original QDeclarativeWebView and e... |
7,616,740 | 7,616,940 | Templated function can't be found, despite being declared | I have a code example here: http://codepad.org/9JhV7Fuu
With this code:
#include <iostream>
#include <vector>
#include <map>
#include <list>
#include <set>
namespace Json {
template <typename ValueType>
struct Value {
Value() {}
Value(int) {}
Value(float) {}
Value(unsigned int) {}
Value(std::string... | Well, as we know, you must declare the function before using it in C++, you declared
template <typename T>
Json::Value<T> toJson(T x) {
return Json::Value<T>(x);
}
which matches with pretty much anything and then you started using it in the template <typename T, typename U>
Json::Value< std::pair<T, U> > toJson(s... |
7,616,791 | 7,616,855 | Create java native method for constructor | I am writing a program in Java and I would like to create a native interface for a library written in C++. But I am confused with how to write a native method declaration for a constructor.
Say I have this C++ class and constructor:
template <class _Tp,class _Val>
class Arbitrator
{
public:
Arbitrator();
}... | Create native method. For example, private native void init(). Call it from constructor in Java. In it's JNI implementation access C++ class as needed.
You will have to use JNI generated method signatures anyway, so you can't map directly Java class to C++ class if that's what you wanted to do.
|
7,616,867 | 7,616,933 | how to test a string for letters only | how could I test a string against only valid characters like letters a-z?...
string name;
cout << "Enter your name"
cin >> name;
string letters = "qwertyuiopasdfghjklzxcvbnm";
string::iterator it;
for(it = name.begin(); it = name.end(); it++)
{
size_t found = letters.find(it);
}
| STL way:
struct TestFunctor
{
bool stringIsCorrect;
TestFunctor()
:stringIsCorrect(true)
{}
void operator() (char ch)
{
if(stringIsCorrect && !((ch <= 'z' && ch >= 'a') || (ch <= 'Z' && ch >= 'A')))
stringIsCorrect = false;
}
}
TestFunctor functor;
for_each(name.begin(), name.end(), functor);... |
7,617,203 | 7,618,145 | Is it possible to use type traits to check whether a type is a container? | Can I use C++ Type Traits to check if a type is an STL-like container? I already know of GCC's builtin __is_class but I would like to be a bit more specific if possible.
| You could build your own traits classes to check a type for the Container interface. This would involve validating that certain associated types (such as container::iterator) exist and validating that certain expressions (such as container.empty()) are valid (i.e., they compile without error). Various SFINAE techniques... |
7,617,421 | 7,617,766 | Request for member which is of non-class | I've got a C++ class I want to use which has all the code in the header file, rather than the CPP file. I'm trying to call it from an objective-C file which inherits a UIViewController class. I've renamed the file to .mm and imported the header file for the C++ file. When I compile, I keep getting a compile-time error ... | I'm not a C++ coder, so this was probably an obvious mistake, but if anyone else comes across a similar problem, I simply changed my code from:
myObject.method();
to
myObject->method();
|
7,617,549 | 7,617,572 | Where to find Open Source Implementations of Hashing/Crypting Algorithms(header files) | I am trying to find open source implementations of Hashing/Crypting(is it HMAC?) algorithms such as SHA256, SHA512, MD5. This is in C++/C
I know of things like Crypto++ but I find them really difficult to include in my projects because they are in DLL's, ie, I really just dont know how to include & use them in my proje... | Use Google Code Search instead of Google. It'll search open source repositories for whatever you need.
Here is a search for MD5 or SHA implementations in C or C++.
|
7,617,703 | 7,617,711 | segmentation fault when erasing an object from a vector c++ | So I am seg faulting when I run this function
class vector <Record<value> >::iterator itr = records.begin();
for (; itr != records.end(); ++itr) {
if (itr->isSelected()) {
itr = records.erase(itr);
recordSize--;
}
}
where my vector is of vector <Record <value> > r... | In the case where you're deleting the last element, itr will first be records.end() because that's what records.erase() will return, and then you're incrementing it with ++itr. Try:
while (itr != records.end()) {
if (itr->isSelected()) {
itr = records.erase(itr);
recordSize--;
} else {
++itr... |
7,617,759 | 7,617,853 | Length limit of array of characters | My question revolves around the program shown below (environment is Mac Xcode).
#include <iostream>
int main () {
char nameOne [5];
std::cin >> nameOne; // input: BillyBobThorton
std::cout << nameOne; // output: BillyBobThorton
char nameTwo [5] = "BillyBobThorton"; // compile error, initializer string... | Is there perhaps a more appropriate way to store user input to an array of characters?
Yes! The most appropriate way in C++ is to use std::string. This will prevent your user overrunning the end of the buffer you've allocated and corrupting your stack. If you only want to display a certain number of characters, you can... |
7,617,919 | 7,617,965 | How would you find the min depth of a tree? | I know how to find the max depth of a tree using a stack and inorder traversal, but I cannot figure out how to find the min depth of a tree (not necessarily a BST) using a stack or queue instead of recursive calls.
| One thing to note here is that when you perform recursion you are using your process execution stack. This generally has some limit set by OS. So with each recursion the process state is pushed onto this stack. So at some point stackoverflow occurs.
If you end up doing a iterative version as apposed to recursive, note ... |
7,617,966 | 7,617,975 | c++ strtok in function changes original string value as parameter | when I use strtok to tokenize a c++ string, it happens a confusing problem, see the simple code below:
void a(string s){
strtok((char*)s.c_str(), " ");
}
int main(){
string s;
s = "world hello";
a(s);
cout<<s<<endl;
return 0;
}
the program outputs "world".
Shouldn't it output "world hello"? Bec... | The problem is (char*)s.c_str(), you are casting the constness away and modified the string contents in a way that you are not supposed to. While the original s should not be modified, I pressume you may have been hit by a smart optimization that expects you to play by the rules. For instance, a COW implementation of s... |
7,618,052 | 7,618,140 | Whats the difference between a uniformed and non-uniformed histogram? | I am using openCV and am wondering about the diff between being uniformed or non-uniformed.
Could someone give me a simple, NON-TECHNICAL description?
Thanks
| A uniform histogram has bins that are exactly the same size,
For example a uniform historgram from 0-10 with 2 bins would contain the bins
{0-5} and {5-10}
Basically the histogtram is split evenly into a certain number of bins all the same size.
A non-uniform histogram will contain bins that are not of uniform size, et... |
7,618,068 | 7,618,108 | Static variables used as constants return zero in other class | I have a class that I'm using to store some static default variables for a visual experiment I'm creating.
They are not marked as const, because Im using a GUI to tweak them at runtime.
When I log them in the main class ( which calls the static function init on the Defaults class ) - they are valid. But in the constru... | // header.h
namespace Constants {
namespace Forces {
extern int MAX_LIFETIME;
extern float GRAVITY_FORCE;
}
}
// my_constants.cpp
namespace Constants {
namespace Forces {
int MAX_LIFETIME = 3000;
float GRAVITY_FORCE = 40000.0f;
}
}
Then include header.h in a file that uses the... |
7,618,088 | 7,618,100 | Function of type unsigned int returns negative number | Wow I thought I knew my C++ but this is weird
This function returns an unsigned int so I thought that means I will never get a negative number returned right?
The function determines how many hours ahead or behind of UTC you are. So for me I'm in Australia, Sydney so I am +10 GMT which means I am UTC = LocalTime + (-10... | Here's what I think is happening:
The value of tzInfo.Bias is actually -10. (0xFFFFFFF6)
On most systems, casting a signed integer to an unsigned integer of the same size does nothing to the representation.
So the function still returns 0xFFFFFFF6.
But when you print it out, you're printing it back as a signed integer.... |
7,618,192 | 7,618,203 | Best Algorithm to randomly generate a number that is divisible by N | Is there a better agorithm to do the following?
I am trying to generate 50 random numbers that are divisible by 7. I then select one of those 50 at random & return that number.
Is there a more efficient/better way to randomly generate numbers that are divisible by 7? Is there a better way I could code/do this?
unsi... | Why can't you just do this?
return (rand() % MAX) * 7;
It does almost the same thing.
Where MAX is small enough to avoid overflow during the multiplication by 7. Which you can define as:
const MAX = INT_MAX / 7;
Or if you want it to be fast, you can do something like:
return (rand() & 0xff) * 7;
|
7,618,235 | 7,618,386 | separating string of characters and int from a input string in c++ | I am trying to sort integers and strings from an input string.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
int main(){
char x[10];
int y;
printf("string: ");
scanf("%s",x);
y=atoi(x);
printf("\n %d", y);
getchar();
getchar(); }
suppose the input is 123a... | If you wish to use the C programming language concepts, then consider using strtol intead of atoi. It will let you know what character did it stop at:
Also, never use %s in a scanf, always specify the buffer size (minus one, since %s will add a '\0' after storing your input)
#include <stdio.h>
#include <stdlib.h>
int m... |
7,618,375 | 7,618,468 | Initializing array of pointers | I have a Deck object (deck of cards) which is a double-ended queue implemented as a doubly-linked list. I would like to be able to shuffle the queue at will, but the way I would go about it is beyond me. So instead I've opted to pre-shuffle an array a pointers to the cards and enqueue them after the fact. Problem is... | Your code has many problems
You are looping with 1 <= i <= 20 but for an array of 20 elements indexing goes from 0 <= index <= 19. You need to use cards[i-1] = new Card(i,path);
You are allocating the array of pointers cards but you are not deallocating it (memory leak). Either deallocate it with delete[] cards; once ... |
7,618,491 | 7,622,216 | Find Duplicates in an array in O(N) time | Is there a way to find all the duplicate elements in an array of N elements in O(N) time?
Example:
Input: 11, 29, 81, 14, 43, 43, 81, 29
Output: 29, 81, 43
Sorting the input and doing a linear scan to detect duplicates destroys the order and gives the output: 29,43,81.
Sorting-by-key another array of indices {0,1,...N-... | I believe a good solution (decent memory usage, can be used to immediately determine if an entry has already been seen thus preserving order, and with a linear complexity) is a trie.
If you insert the elements into the trie as if they were a string with each digit (starting from the MSD) in each node, you can pull this... |
7,618,590 | 7,618,643 | Order of evaluation of expression | I've just read that order of evaluation and precedence of operators are different but related concepts in C++. But I'm still unclear how those are different but related?.
int x = c + a * b; // 31
int y = (c + a) * b; // 36
What does the above statements has to with order of evaluation. e.g. when I say (c + a) am I... | The important part about order of evaluation is whether any of the components have side effects.
Suppose you have this:
int i = c() + a() * b();
Where a and b have side effects:
int global = 1;
int a() {
return global++;
}
int b() {
return ++global;
}
int c() {
return global * 2;
}
The compiler can choos... |
7,618,631 | 7,618,663 | Error trying to access a struct type using a pointer to a vector of structs | #include <iostream>
#include <vector>
using namespace std;
struct a_struct { int an_int; };
int main ()
{
vector <vector <a_struct> > the_vec;
vector <a_struct> * p_vs;
p_vs = & the_vec[0];
*(p_vs)[0].an_int=0; //error: 'class __gnu_debug_def::vector<a_struct,
//std::allo... | In C++, [] and . have higher precedence than *.
Your last line
*(p_vs)[0].an_int=0;
when fully parenthesized, is
*((p_vs[0]).an_int)=0;
Since p_vs was declared as
vector <a_struct> * p_vs;
it is as if p_vs is an array of vector <a_struct> elements, so p_vs[0] is a vector<a_struct>.
And vector<a_struct> objects ind... |
7,618,816 | 7,618,857 | How I could to forbid show of hidden/system files in TOpenDialog? | I tried to write a program for safe deleting files. However, I have a problem with deleting system files (recycle bin etc.). Now my question is. Which way to hidden files (from users) at this dialog. Other files I add to listview and then rewrite them zeroes. After that I delete this files without recycle.
| The only way guaranteed to do this is to write your own open file dialog. But I'd advise that you find a better way of doing this, since that's considered pretty bad form.
It just occurred to me, but what you could do (and I'm not saying it's easy or nice) is launch the open file dialog, then using the handle to the wi... |
7,618,873 | 7,619,033 | Is there any difference between __typeof and typeof? | There are more operators that work when we add __ to them too.
what does __ mean?
| An identifier with double underscores is reserved for the implementation. typeof is a compiler specific extension to the language, so naming it __typeof ensures no user code has an identifier with the same name
|
7,618,889 | 7,619,028 | exception handling iterator interface | I'm trying to make a watertight interface to a library that I'm designing. The user is to enter two dimensional data and so I thought an iterator interface similar to std::transform would be transparant.
However, I am unsure how to exception handle any abuse of the iterators.
My interface is like so (I can change the ... | I wouldn't add any checks to the method, but document that the exception specification depends on the used iterators. So the user can use checked iterators if he doesn't care about performance losses or unchecked iterators and get best performance. I think most implementations of STL iterators has asserts that check fo... |
7,619,295 | 7,619,311 | compile time error regarding template function instantiation | I am trying to write a container class with iterator. This is my class:
template <class T>
class C{
private:
T* v;
int MAX_SIZE;
int i;
public:
C (int size){
MAX_SIZE = size;
v = new T (MAX_SIZE);
i = 0;
}
~C(){ delete v; }
class iterator{
private:
T* v;
public:
iterator(T* ip){ ... | Have a look the function template:
template<T>
void print(typename C<T>::iterator & start, typename C<T>::iterator & end);
And your usage:
print(ic.begin(), ic.end());
So the problem is, T cannot be deduced from the function argument. The Standard calls it non-deducible context. Here I've explained similar question ... |
7,619,338 | 7,619,487 | Which one is faster ? Function call or Conditional if Statement? | Please consider the branch prediction too before answering this question.
I have some scenarios where i can replace a conditional statement with a call to a function with the help of function pointer.Some thing like this. (you can think of component based programming over inheritance for a similar type of senario)
... | You replaced an if statement with an indirection.
Both your if statement, and the indirection requires memory access.
However, the if will result in a short jump - which will probably won't invalidate the pipeline, while the indirection may invalidate the pipeline.
On the other hand, the indirection is a jump, while th... |
7,619,384 | 7,619,406 | Where is the access violation is my code? | I'm getting an Access Violation when attempting to run this code which finds prime numbers in a bound.
int main () {
cout << "Program initialized successfully. Please wait for the next message to appear." << endl << endl ;
int Primes[51] ;
int runner = 0 ;
int chaser = 0 ;
int bound = 0 ;
int c... | Here :
for ( chaser = 0 ; Primes[chaser] != 0 ; chaser ++ ) {
you didn't initialize you Primes array with 0, so the loop can loop over and over and chaser can be bigger than 51 (the size of you Primes array) and then Primes[something_bigger_than_50] will raise an access violation.
|
7,619,492 | 7,619,504 | Multiplying real matrix with a complex vector using BLAS | How can I use Blas to multiply a real matrix with a complex vector ? When I use functions like ccsrgemv() I get type mismatch errors?
error: argument of type "float *" is incompatible with parameter of type "std::complex<float> *"
| Use two matrix-vector multiplications (A * (x + iy) = A * x + i A * y). More precisely, consider your complex vector as two entangled real vectors with stride 2. BLAS lets you do this.
UPDATE: actually, I did not notice that you were doing Sparse BLAS. For dgemv my trick works, but for csrgemv it doesn't. I'm afraid yo... |
7,619,563 | 7,619,827 | error: 'IOCTL_STORAGE_QUERY_PROPERTY' was not declared in this scop | I've included winioctl.h and there is no #define for IOCTL_STORAGE_QUERY_PROPERTY in that file !! http://www.osronline.com/ddkx/storage/k307_8z3m.htm Says Its in ntddstor.h But I cannot find any ntddstor.h on my Windows XP.
HoweverIOCTL_STORAGE_QUERY_PROPERTY mentions its supposed to work with Windows XP (I dont nee... | I have used MinGW to compile these kind of programs. It may not be so easy to find, because frankly, the MinGW site is quite a mess, but they provide a lot of DDK header with no pain. Then I simply copy/paste the structs and defines I need and that I cannot find in the SDK headers. The macros, I define them conditional... |
7,619,770 | 7,619,804 | Copy part of file in C++ | I'm currently busy with a project in which I have to copy a part from a file to another file, so I made a code for that using fread and fwrite. But I came across a problem: for testing purposes I made a code which should copy a whole file, but somehow the code creates copies that are larger than the original file. See ... | You're opening the destination file in text mode, instead of binary mode, so the newline translation happens behind your back. Change the mode to "wb".
Other notes:
Use streams rather than stdio.
Don't write byte-for-byte. Use a larger buffer, your method will take forever for larger files.
|
7,619,788 | 7,645,651 | Can I import a class into ClassWizard in VS2010 | Is there a way in VS2010 to import a class from a .h and .cpp file into ClassWizard such that I can use ClassWizard to manipulate it (e.g. add variables etc...) Quite a number of the files that I brought into the project when I moved over from VS2008 do not seem to be available to ClassWizard. Back in VS6, I could do... | Figured a workaround. My hunch was that VS2010 was reading the //{{AFX_DATA(CMyClass) comments when existing files are added into a project, so I did the following;
Edit the files to include a set of AFX... comments copied from
another class
Replace the class name with the correct class
Remove the .h and .cpp fil... |
7,620,003 | 7,620,240 | How do you tell pyximport to use the cython --cplus option? | pyximport is super handy but I can't figure out how to get it to engage the C++ language options for Cython. From the command line you'd run cython --cplus foo.pyx. How do you achieve the equivalent with pyximport? Thanks!
| One way to make Cython create C++ files is to use a pyxbld file. For example, create foo.pyxbld containing the following:
def make_ext(modname, pyxfilename):
from distutils.extension import Extension
return Extension(name=modname,
sources=[pyxfilename],
language='c++')
... |
7,620,116 | 7,620,234 | c++ win32 get system volume accelerator | is it possible to detect which keys are used for a system volume accelerator in win32 using c++? For example: if the user presses fn + key up (and this is also the key combination to change the system volume), i would like to detect this event and response to it.
| This is handled by the machine's BIOS. It produces a keystroke, VK_VOLUME_DOWN or VK_VOLUME_UP virtual key. DefWindowProc handling of that WM_KEYDOWN message produces WM_APPCOMMAND, APPCOMMAND_VOLUME_UP/DOWN. DefWindowProc handling of that message adjusts the volume.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.