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,785,576 | 7,785,619 | Correct use of shared_ptr to eliminate deallocation across DLL boundaries | I'm reading "Using shared_ptr in dll-interfaces". In that post, phlipsy suggested a way to pass no implementation specific object across DLL boundaries, at the end of his answer. Basically, the idea is to return a raw pointer from DLL and initialize the shared_ptr in EXE w/ that raw pointer.
I don't think it's correct.... | You're right with both statements. A second correct way would be to return a raw pointer by createObject(..), initialize a shared_ptr with it and pass a custom deleter to the shared_ptr. The custom deleter is a library function like releaseObject(..).
Edit:
With your version (createObject(..) returns a shared_ptr<..>) ... |
7,785,761 | 7,870,487 | How async_read_some() in boost::asio::ip::tcp::socket actually works? | It is written in the documentation:
This function is used to asynchronously read data from the stream
socket. The function call always returns immediately.
I know it is asynchronous, so it returns immediately. But what does async_read_some() differ from free function read()? When I try to std::cout my buffer used f... | No, async_read_some() does not request continuously.
The ip::tcp::socket::async_read_some() function will make a system call that starts the read.
After that, the next time you call io_service::run() on the io_service that you passed to the constructor of the ip::tcp::socket, the io_service will check to see if the asy... |
7,785,766 | 7,787,439 | Using QSqlDatabase connection in QtConcurrent::run (pseudo connection pooling) | I'm trying to find an efficient way to handle some database queries in Qt. The scenario essentially is that we have many events that we need to write to the db. We cannot block the main thread while writing so these writes are done in separate threads using QtConcurrent::run.
Now, the issue is that currently each concu... | According to the Qt documentation it is not possible. QtConcurrent::run() takes a thread from a pool of threads, so you don't know which thread will be used each time. I don't of a way to handle that. It will take the first thread available.
I really think you shouldn't be using QtConcurrent::run() in this situation. A... |
7,785,815 | 7,785,858 | Dynamically loading maps in a "tile engine" | I'm implementing a tile engine for games using C++. Currently the game is divided into maps, each map has a 2D grid of sprites where each represents a tile.
I am coding a system where if several maps are adjacents you can walk from one to the other.
At startup of the game, all the maps are instancied but are "unloaded"... | A different possibility to improve latency, but will increase overall number of ops needed:
Instead of waiting when you are 'too close' or 'too far' from a map, store in memory the maps for a bigger square around the player [i.e. if the map is 50x50, store 150x150], but show only the 50x50. now, every step - calculate ... |
7,785,886 | 7,785,963 | Access friend function defined in class | There is such code:
#include <iostream>
class A{
public:
friend void fun(A a){std::cout << "Im here" << std::endl;}
friend void fun2(){ std::cout << "Im here2" << std::endl; }
friend void fun3();
};
void fun3(){
std::cout << "Im here3" << std::endl;
}
int main()
{
fun(A()); // works ok
//... | class A{
public:
friend void fun(A a){std::cout << "Im here" << std::endl;}
friend void fun2(){ std::cout << "Im here2" << std::endl; }
friend void fun3();
};
Although your definition of fun2 does define a "global" function rather than a member, and makes it a friend of A at the same time, you are still m... |
7,786,177 | 7,786,541 | Making QListWidget resize its items to fill space | I've got a QListWidget and I've got a custom widget class, which I'm creating an instance of for each item appearing in the list widget.
But I can't figure out how to make my custom widget expand to fill all the available space of each row in the list widget.
My custom widget is created in Qt Designer, and I've set its... | I'm assuming you're putting items in here using QListWidget::setItemWidget()?
If that's the case, then you usually need to set the sizeHint() of your QListWidgetItem to that of your custom widget:
myListWidget->setItemWidget( myListWidgetItem, customWidget );
myListWidgetItem->setSizeHint( customWidget->sizeHint() );
|
7,786,234 | 7,786,247 | c++ libconfig parsing error? | I am trying to leverage the libconfig library in my c++ code to read in data. I have a bitmask binary value that I am trying to read in from an external file. The problem is when I read the data in, I believe libconfig is interpreting or parsing the integer as a base 10 number and not as a base 2 number and thus affe... | I'm not familiar with libconfig, but can you persuade it to read these bitmasks as strings? Then do the conversion in your own code.
|
7,786,383 | 7,786,461 | formatting phone number in c++ | Please assist, I am trying to format a phone number like (111)111-1111. I have the following code which works but I would like to write much shorter.
int main(){
string phone_number;
cin >> phone_number;
cout<<"(";
for(int i = 0; i < 3; i++) {
cout << phone_number[i];
}
cout << ")";
... | Another possibility:
cout << "(" << phone_number.substr(0,3) << ")"
<< phone_number.substr(3,3) << "-" << phone_number.substr(6,4) << endl;
|
7,786,507 | 7,787,163 | TLS Handshake message parsing | I am currently trying to implement a tls handshake into a http proxy that I am writing. I know that I could use OpenSSL to do the work for me but I am interested in writing it myself.
I am currently working through the TLS RFC and am confused about how to parse the ClientHello message, particularly the fact that it may... | The session_id is preceded by the length. Same with the cipher suites and compression algorithms.
What's you're missing is section 4.3 of the RFC:
Variable length vectors are defined by specifying a subrange of legal
lengths, inclusively, using the notation . When
encoded, the actual length precedes the ve... |
7,786,711 | 7,786,753 | Will the pointer ever be different than expected in this case? | Say I have a Listener class.
I have class A and class M which both implement the listener class.
Class A has 4 M's.
Each M has 1 A, but not as an A, as a Listener base class. (So downcasted A because M knows nothing about A).
When A gets a message from 1 of them M's it needs to be able to know which M sent it.
Therefor... | It will work as you expect.
In fact, in order to do the comparison, m_mInstance[0] will implicitly be cast to Listener* in order for the types to match. if (l == (Listener*)(m_mInstance[0])) ... would compile to the same target code. This will typically incur no overhead unless you have multiple inheritance, in which c... |
7,786,740 | 7,786,812 | c++ store a pointer to a member function of unknown class | I want to store a pointer to an object and a pointer to it's method of known signature. If I know the class then this pointer have type:
int (MyClass::*pt2Member)(float, char, char)
But how can i store the pointer if i don't know the type?
I want to do something like this:
myObject.callThisFuncLater(&otherObject, &oth... | You can use boost::function (and boost::bind) to store a piece of code to be called later.
class MyClass
{
public:
void callThisFuncLater( boost::function< int (float, char, char) > callBack );
};
...
myObject.callThisFuncLater( boost::bind( &otherObject::method, &otherObject ) );
|
7,786,787 | 7,786,848 | Can I use enum class values as arguments to varargs functions? | C++11 adds enum classes, which are stronger-typed enums - values of enum classes will not be implicitly converted to values of other enum classes or integers, and forward-declarations are permitted by virtue of an explicit size specifier.
Is it possible to pass values of such enumerations to varargs functions and remai... | Yes, you can. 5.2.2/7 explicitly allows arguments of any enumeration type. Unscoped enum values are integer promoted, but scoped enums (the enum class ones) are not.
Of course you still have to be careful in the implementation of the function.
|
7,786,886 | 7,786,974 | Pointer template specialization | I'm new to templates in C++, so here is my problem.
I've a generic class ProductItem that will do all the stuff I want, but I need to specialize a part in order to use pointers (for char*).
My code :
typedef unsigned char BYTE;
template<typename T>
class TProductTableItem
{
protected:
int Offset;
i... | You are mixing two distinct concepts: inheritance and template specialization.
Your class is not a template specialization but it derives from a template instantiation. However that template cannot be instantiated because when T = char * the statement Value = buffer[offset]; has a type mismatch error.
If you want to wr... |
7,786,975 | 7,787,074 | SQLite INSERT command return error "column number is not unique" | I have a text file with rows (lines). Each row is a record in database table. I read this file and fill database.
Tables creating command:
CREATE TABLE gosts(number TEXT PRIMARY KEY, userNumber TEXT, status TEXT, date TEXT, title TEXT, engTitle TEXT, description TEXT, mainCategory INTEGER, category INTEGER, subCategory... | I would bet that the difference between the good and bad rows were whether or not the value associated with the 'number' column was already in the table.
This is one of the reasons that table designs usually do not use TEXT valued columns for PRIMARY KEYs.
If it is possible to re-create your table, I would create an ID... |
7,786,994 | 7,787,253 | c++ getline() isn't waiting for input from console when called multiple times | I'm attempting to get a few user-input parameters from the console, two strings, two ints and a double. The relevant code I'm trying to use is this:
#include <string>
#include <iostream>
using namespace std;
// ...
string inputString;
unsigned int inputUInt;
double inputDouble;
// ...
cout << "Title: ";
getline(ci... | The problem is you are mixing calls to getline() with the use of the operator >>.
Remember that operator >> ignored leading white space so will correctly continue across lines boundaries. But stops reading after the input has successfully been retrieved and thus will not swallow trailing '\n' characters. Thus if you us... |
7,787,015 | 7,787,196 | Why is this allocation of a vector not accepted? | So I have declared a vector in my class header like this:
...
private:
vector<Instruction> instructions;
...
Then in the .cpp implementation in the constructor, I try to initialize it like this:
instructions = new vector<Instruction>();
Xcode tells me: No viable overloaded '='
I am basically trying to get thi... | when you write
vector<Instruction> instructions;
you already have instantiated instructions to whatever memory model the user of your class is using e.g.
class YourClass
{
vector<Instruction> instructions;
};
...
int main()
{
YourClass class1; // stack
std::unique_ptr<YourClass> class2(new YourClass); // heap
.... |
7,787,059 | 7,787,124 | g++ Undefined reference static member variable | I am Compiling this using g++ and a makefile. The g++ version is 4.1.2 20080704.
Here is the simplified code which still contains the error:
#ifdef __cplusplus
extern "C"
{
#endif
class MyClass
{
public:
MyClass() {};
MyClass& operator=(MyClass&);
static MyClass& instance() { return log; };
pr... | The declaration of MyClass::log in the class definition gets C++ linkage despite the extern "C", because static class members simply don't exist in C. But for some reason, the definition of MyClass::log outside the class definition gets C linkage, which doesn't make much sense to me.
But you can get around the proble... |
7,787,066 | 7,787,078 | Invalid combination of type specifiers? | This works in xcode, but not visual studio. The error is
error C2236: unexpected 'enum' 'abc::def::`anonymous-namespace'::'. Did you forget a ';'?
I can't figure out what is wrong.
namespace abc {
namespace def {
namespace {
long long enum {
aaa = 1L,
bbb = 2L,
};
}
}
}
| That syntax is bizarre, I don't see how it would work anywhere (EDIT: apparently it's a GCC extension -- thanks @PlasmaHH). This is the portable C++11 syntax you want:
enum : long long {
aaa = 1LL,
bbb = 2LL
};
|
7,787,198 | 7,787,684 | std::wstring: concatenation with + has no effect | The solution is probably obvious, but I do not see it. I have this simple C++ code:
// Build the search pattern
// sPath is passed in as a parameter into this function
trim_right_if(sPath, is_any_of(L"\\"));
wstring sSearchPattern = sPath + L"\\*.*";
My problem is that the + operator has no effect (checked in debugger... | As I found out the two NULL characters stored at the end of the string were the problem. Apparently std::wstring does not care about NULLs like good old C string does. If it thinks a string is 10 characters long, it does not care if some of those 10 characters are NULL characters. If you then append to that string, the... |
7,787,208 | 7,787,226 | Optional Template parameter | Is it possible to have optional template parameter in C++ , for example
template < class T, class U, class V>
class Test {
};
Here I want user to use this class either with V or without V
Is following possible
Test<int,int,int> WithAllParameter
Test<int,int> WithOneMissing
If Yes how to do this.
| You can have default template arguments, which are sufficient for your purposes:
template<class T, class U = T, class V = U>
class Test
{ };
Now the following work:
Test<int> a; // Test<int, int, int>
Test<double, float> b; // Test<double, float, float>
|
7,787,212 | 7,787,246 | SSL or TLS encryption for custom protocol | So I'm making my own peer-to-peer UDP protocol and I want to add encryption, so basically I want to have the clients exchange public encryption keys. What library would I use, and how would I generate the keys and use them to encrypt?
| SSL and TLS require a reliable transport protocol and cannot run over UDP. What you're looking for is DTLS. What you do from there depends on what library you use. Wikipedia lists several options.
|
7,787,267 | 7,787,281 | How create an standalone (without DLL file dependencies) C++Builder console application like a Delphi application? | When I create a Delphi console application, I can deploy the generated EXE file without worrying about external DLL files. But if I create very simple C++Builder (version 2007) console application (no VCL) the EXE file requires the CC3280MT.dll file to run.
How can I avoid which my C++Builder console application requi... |
In the project options, uncheck the linker option "Dynamic RTL".
In the packages options, uncheck "Link with runtime packages".
|
7,787,301 | 7,787,405 | Are "enum class" members instantiated immediately or later when used? | Consider this one
template<typename T>
struct A {
enum class X {
V = T()
};
};
For member classes and member functions, C++11 (and C++03) won't instantiate their definition unless we use them in a way that requires their definition. Is this true for enum class?
// valid?
A<std::string> a;
Unfortunately, I ca... | I think so. 14.7.1/1
The implicit instantiation of a class template specialization causes the implicit
instantiation of the declarations, but not of the definitions or default arguments, of [...] scoped member enumerations
|
7,787,353 | 7,787,366 | How can I interact with directories in C++? | Is the C++ language dealing with directories like create, delete, get directory content, search, etc.
Does C++ have an internal library or are there external libraries ?
Is there a recommended library?
| Boost.Filesystem is what you want:
The Boost.Filesystem library provides facilities to manipulate files and directories, and the paths that identify them.
|
7,787,500 | 7,787,528 | How to write a function that takes a functor as an argument | Basically I want to do this:
Can I use a lambda function or std::function object in place of a function pointer?
clearly that is impossible for now for functions that expect a function pointer. However, it will work for a function that expects a functor ( I have done it before with stl's sort() function)
However, I don... | Just write the function to take an arbitrary type:
template <typename Func>
void foo(Func fun)
{
fun(...);
}
This will then work with function pointers, functors and lambdas all the same.
void f() {}
struct G
{
void operator()() {}
};
foo(&f); // function pointer
foo(G()); // functor
foo([... |
7,787,664 | 7,787,785 | Writing binary data in c++ | I am in the process of building an assembler for a rather unusual machine that me and a few other people are building. This machine takes 18 bit instructions, and I am writing the assembler in C++.
I have collected all of the instructions into a vector of 32 bit unsigned integers, none of which is any larger than what... |
Keep an eight-bit accumulator.
Shift bits from the current instruction into to the accumulator until either:
The accumulator is full; or
No bits remain of the current instruction.
Whenever the accumulator is full:
Write its contents to the file and clear it.
Whenever no bits remain of the current instruction:
Mov... |
7,787,873 | 7,788,152 | boost asio need to post n jobs only after m jobs have finished | I'm looking for a way to wait for a number of jobs to finish, and then execute another completely different number of jobs. With threads, of course. A brief explanation:
I created two worker threads, both executing run on io_service. The code below is taken from here.
For the sake of simplicity, i had created two type... | Inside CalculateFib2 the first thing you do is wait for the condition (cv). This condition only gets signaled at the end of CalculateFib. So, it stands to reason that execution never continues, unless the condition is triggered (by posting CalculateFib) job.
Indeed, adding any other line like so:
io_service->post( boos... |
7,788,132 | 7,788,225 | How to extract a pixel from a png file using c++? | Is there an image library available that allows a user to extract pixels from a png file that has been loaded onto disk without decompressing it?
So I have 100k 8bit images of size 512x512 where each one is about 10kb when in png format. This means that I would only need 1GB of RAM to store all the images at runtime f... | I don't think you'll be able to get a pixel without decompressing at least the preceding part of the image. When you open a file, it will just point to the compressed data on disk. When you run it through a PNG library, it will be decompressed.
Your best bet, I think, and the canonical library for reading and writing P... |
7,788,216 | 7,788,224 | EXC_BAD_ACCESS and char pointer to float pointer cast | I'm currently writing a file loader for an ipad program and I'm getting strange EXC_BAD_ACCESS exceptions. Here is a short snipped of code that I think is the reason for the error:
float testFloat() {
char mem[32];
char *charPtr = &mem[0];
float *floatPtr = (float*)(charPtr + 1);
float f = *floatPtr; //... | You are correct, this is due to pointer alignment. On many RISC systems, the alignment needs to be at least as large as the data-type itself. (ARM falls into this category.)
In this case, float is 4 bytes, so the address needs to be aligned to 4 bytes. (divisible by 4)
Furthermore, this type of type-punning violates st... |
7,788,303 | 7,788,306 | c++ compile error with visual studio | I am learning C++ and I cannot compile it. I am new to C++ so bear with me please.
Here's a piece of code with the error:
#include<iostream>
#include<string>
using namespace std;
class Car {
private:
int carId;
string mechanicName;
double cost;
public:
const static double MIN_COST;
Ca... | const static double MIN_COST = 10.00;
should be
const double Car::MIN_COST = 10.00;
|
7,788,444 | 7,788,597 | Multiple definition of main: linking fortran with C++ | I would like to write a C++ program that calls the mvndst_() subroutine from
http://www.math.wsu.edu/faculty/genz/software/fort77/mvndstpack.f
On Linux, if I create test.cc:
extern "C" {
int mvndst_(int *, double *, double *, int *, double *, int *,
double *, double *, double *, double *, int *);
};... | I can't find any documentation for the -Mnomain option, but gfortran doesn't complain about it (it seems to pass it on to the linker). But it also didn't complain when I ran
gfortran -Mnoplatypus -o test test.o mvndstpack.o
So my guess is that it doesn't support -Mnomain, and that it's being silently ignored. (Eithe... |
7,788,508 | 7,788,551 | sizeof operands get evaluated? | AFAIK sizeof doesn't evaluate its operands it C++.
E.g.
int x = 0;
sizeof(x += 1); // value of x is not changed
But what does this mean?
int arr[5];
sizeof(arr+0); // here array is converted to pointer
Why does the arithmetic on array is applied here?
(§ 5.3.3/4) The lvalue-to-rvalue (4.1), array-to-pointer (4.2), a... | The sizeof() operator is calculated at compile time. The expressions are NOT evaluated. It is the type of the expression that is calculated (at compile time) and then used by sizeof().
So in your first one:
sizeof( x += 1);
The type of x is int. The result of the += operator is still int. So the sizeof() is still the ... |
7,788,612 | 7,788,625 | C++ Error: No match for 'operator=' | Having a problem when assigning a value to an array. I have a class I created called Treasury. I created another class called TradingBook which I want to contain a global array of Treasury that can be accessed from all methods in TradingBook. Here is my header files for TradingBook and Treasury:
class Treasury{
public:... | That's because yieldCurve[i] is of type Treasury, and new Treasury(treasuries[i]); is a pointer to a Treasury object. So you have a type mismatch.
Try changing this line:
yieldCurve[i] = new Treasury(treasuries[i]);
to this:
yieldCurve[i] = Treasury(treasuries[i]);
|
7,788,639 | 7,788,646 | Why does my pointer output a string and not a memory address in C++? | I'm working on a string class that employs pointers and I'm just having some difficulty in understanding how my print function works here. Specifically, why does cout << pString output the string and not the memory address of the dynamic array that it's pointing to? My understanding was that the variable pString was ... | This is because the << operator has been overloaded to handle the case of a char* and print it out as a string. As opposed to the address (which is the case with other pointers).
I think it's safe to say that this is done for convenience - to make it easy to print out strings.
So if you want to print out the address, y... |
7,789,007 | 7,789,017 | Reading from an iostream | Maybe I'm missing something, but I'm having a lot of trouble finding any information on how to how to read from an iostream (std::iostream& stream). Is there a way I can convert it to a string or similar?
For clarification this is (what I'm basically trying to do, for example):
std::stringstream ss("Maybe I'm missing s... | You read from an iostream the same way you would if you were using cin.
stream >> varName;
Crazy syntax yes, but that's what the makers of streams decided to do.
You can also use get and getline if your reading to strings. Get will get the next character or a specified buffer of characters, and getline will go to the... |
7,789,046 | 7,789,115 | UIView and XIB connections.Displaying it? | How can i display an XIB/NIB file on a UIView?I've searched but i didn't found this.I want to display the xib interface on a main view,i have five xib files and i need to each one be displayed on a UIView!Some people talked about this code code but where i implement this:
NSArray *screens=[[NSBundle mainBundle] loadNib... | I posted an article about loading custom views from a nib in my blog http://effectivemobility.blogspot.com/2011/05/using-custom-cells-in-your-uitableview.html
The key part is this method
+ (id)customViewForClass:(Class)customClass {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(cu... |
7,789,130 | 7,789,223 | WinAPI way to determine if a file is accessible/private | In win32 c++; is there a way to determine if a folder/file is accessible? You know how if you try to access a certain folder in the C:/Windows directory & you will get a popup saying "This folder is not accessible".
Maybe there is a file attribute constant that signifies that the file is private? Maybe something like F... | It wouldn't be a flag on the file itself because different accounts may have access to different files/directories. Instead, windows uses ACL's (access control lists), which are data structures that determine who has access to what.
ACLs in windows can be used with just about anything that is referred to by a handle (... |
7,789,163 | 7,789,390 | Using directive best practice | Is there any functional or optimization difference between the following?
// SomeClass.cpp
#include "SomeClass.h"
#include "SomeOtherClassInSomeClassNamespace.h"
using namespace SomeClassNamespace;
SomeClass::SomeClass() {}
void SomeClass::SomeFunc()
{
// uses some stuff in SomeClassNamespace not defined in So... |
Is there any functional difference between the following?
As long as the merged scopes resolve as expected, then No.
Is there any optimization difference between the following?
Runtime or binary size? No.
If you want build optimizations, then additional complexity will be introduced via using and/or by reopening th... |
7,789,326 | 7,789,468 | When is static cast safe when you are using multiple inheritance? | I found myself in a situation where I know what type something is. The Type is one of three (or more) levels of inheritance. I call factory which returns B* however T is either the highest level of a type (if my code knows what it is) or the 2nd level.
Anyways, I did a static_cast in the template which is the wrong thi... | A cross-cast:
struct Base1 { virtual void f1(); };
struct Base2 { virtual void f2(); };
struct Derived : Base1, Base2 {};
Base1* b1 = new Derived();
Base2* b2 = dynamic_cast<Base2*>(b1);
requires use of dynamic_cast, it cannot be done with static_cast (static_cast should have caused a compile-time error). dynamic_ca... |
7,789,333 | 7,789,379 | Is constructing and passing an array/other container in function call possible? | Is there any way to construct an array of strings inside a function call? For example, say I have a function like this:
void foo( char * [] strings )
{
//...does stuff
}
And instead of declaring the character array first and then passing it, is there any way, with arrays or any other container class, to call the ... | This works in C99:
void fun(char *argv[])
{
while(*argv)
printf("%s\n", *argv++);
}
fun((char*[]){"aaa", "bbb", NULL});
Since you mention "container" you probably use C++ so this answer is of limited value (unless you are using a compiler that accepts it as an extension - the way GCC does for example).
|
7,789,420 | 7,789,431 | avoiding negative values in C++ | I have the following function, and I tried to avoid negative values by including the if statement, but it didn't help.
...suggestions on how I might fix this...
double G(double S, double X, double r, double div, double k, double T)
{
double g=0;
g=Phi(d1(S,X,r,div,k,T))/(exp(-div*T)*S*k*sqrt(T));
if((isnan)(g) ||... | You have the right idea, but the syntax is a little bit off. Try this:
double G(double S, double X, double r, double div, double k, double T)
{
double g=0;
g=Phi(d1(S,X,r,div,k,T))/(exp(-div*T)*S*k*sqrt(T));
if(isnan(g) || isinf(g) || (g<0)) g=0;
return g;
}
|
7,789,575 | 7,789,657 | Displaying XIB on UIView!How can i set it? | How can i display a XIB interface on an UIView!Please be simple!
| a UIView interface built in a XIB can be displayed by linking that XIB with a UIViewController.
Check out the Apple documentation About Windows and Views.
And you can see how a XIB is set up just by creating a new project in XCode and choosing "Single View Application" as a template. If you're using XCode 4.2, the "Ma... |
7,789,668 | 7,789,732 | Why would the size of a packed structure be different on Linux and Windows when using gcc? | In the code below, why is the size of the packed structure different on Linux and Windows when compiled with gcc?
#include <inttypes.h>
#include <cstdio>
// id3 header from an mp3 file
struct header
{
uint8_t version[ 2 ];
uint8_t flags;
uint32_t size;
} __attribute__((packed));
int main( ... | Section 6.37.3 of the gcc attributes explains it as a difference in ABI specs, see here: http://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
|
7,789,679 | 7,789,754 | How to make the program work without asking for any linked files | When I make a simple program Whether Console or win32 When I copy the program to other pc or other os give me an error message, must have specific dll or lib files to the program works .
Example:
I created a simple console program and when it runs on other Windows or other pc asked me files (msvcp100d.dll, msvcr100d.dl... | That is not always a good idea, and with some libraries you may have licensing issues, but you can link everything statically, instead of dynamically.
For example, for the MS C/C++ runtime libraries (msvcp100d.dll, msvcr100d.dll), you could change the settings in the Visual Studio. Open the project properties, and go t... |
7,789,881 | 7,791,130 | OpenCV - how to form up a .avi from a list of .ppm files | I have a library to convert .oni file(video format from kinect) to .ppm files corresponding to each frame of the recorded video.
Based on these .ppm files I want to build a .avi file.
Is there any opencv function for doing this?
Any suggestion would help.
| You could use mencoder/ffmpeg to convert the pp to avi. Here is a tutorial.
|
7,789,926 | 7,789,943 | Do pointers have a size? | In C++, when using a pointer to multidimensional array like,
int arr[2][5];
int (*p)[5] = arr;
How does a int* is different from the one with size i.e. int (*)[5]?
| Pointers are always the same size for any particular machine (virtual, or otherwise). On a 32-bit machine, pointers are 32-bits wide. On a 64-bit machine, they are 64-bits wide. Similar rules apply for more exotic (by today's standards) architectures.
|
7,789,969 | 7,790,180 | fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory? | I am using visual studio 2005 to create a project. And I have folder structure in project as: a folder called code. this folder contains all *.cxx files.
Now, I have created a class xyz in header file xyz.h. And defined every thing in xyz.cxx which is placed in code folder.
But now when I try to compile it with visua... | Either move the xyz.h file somewhere else so the preprocessor can find it, or else change the #include statement so the preprocessor finds it where it already is.
Where the preprocessor looks for included files is described here. One solution is to put the xyz.h file in a folder where the preprocessor is going to find... |
7,790,122 | 7,790,317 | Increasing numbers in recursive functions | for a programming assignment, I have to load a tree into an array in order.
The recursive algorithm itself is no problem for me. The problem I'm having is keeping the subscript/element numbers increased periodically so that the data goes into the right array element, instead of overwriting each other after calls return... | Make your data parameter a reference to a pointer:
void foo(Node* currentNode, ContentType*& data) {
//...
*data++ = currentNode->data;
//..
}
|
7,790,524 | 7,790,684 | Missing operator<< but it's there | Int this class where operator<< is defined (see code) while trying to compile it with gcc 4.6.1 I'm getting following error: no match for 'operator<<' in 'std::cout << a'. What's going on?
template<class Int_T = int, typename Best_Fit<Int_T>::type Min_Range = std::numeric_limits<Int_T>::min(),
... | Your template has three arguments, a type, and two constants of a known best fit type, but your templated operator<< takes an instantiation of the template with three types.
template<class Int_T = int, typename Best_Fit<Int_T>::type Min_Range
= std::numeric_limits<Int_T>::min(), // ... |
7,790,687 | 7,790,820 | Is this strange inlining behavior of Visual C++ expected? | I have this (rather useless) code:
__declspec(noinline)
int foo( char* ptr, int offset )
{
if( 5 / offset == 3 ) {
return 1;
}
if( ptr != ptr + offset ) {
return 2;
}
return 0;
}
int _tmain(int /*argc*/, _TCHAR* /*argv*/[])
{
if( foo( 0, 0 ) ) {
rand();
}
}
I comp... | I guess so. You told it not to inline the function, but you didn't say it couldn't modify the function based on how it is used. It can see that the function is only ever called as foo(0,0), so why shouldn't it optimize the function for that?
try inserting a call to something like foo(1,2) in addition to the (0,0) call ... |
7,790,773 | 7,790,917 | setsockopt: Bad file descriptor in C++ | I have the famous error "address already in use" because I have no check for the bind function.
Here is my code:
memset(&(this->serv_addr), 0, sizeof(this->serv_addr));
this->serv_addr.sin_family = AF_INET;
this->serv_addr.sin_port = htons(port);
this->serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int yes = 1;
if (set... | You need to first create the socket via the socket call, like:
sock_fd = socket(PF_INET, SOCK_STREAM, 0);
(and check the return value; see man 2 socket for details)
Only then you may do your setsockopt call. Before the call to socket, your sock_fd variable will contain a random value (or 0) instead of a socket file de... |
7,790,808 | 7,791,486 | Does anyone have a wrapper for STL algorithms, taking one container instead of two iterators as first argument? | Does anyone know of a header file, or has taken the time to wrap all algorithms themselves?
Ie
std::fill(iterator start, iterator stop, value_type val) ->
xxx::fill(container& c, value_type val)
Update:
Seems boost range does exactly what I want.
| Boost Range
http://www.boost.org/doc/libs/1_47_0/libs/range/doc/html/index.html
|
7,790,877 | 7,791,082 | Forward FFT an image and backward FFT an image to get the same result | I am trying to FFT an image using the library from http://www.fftw.org/ so that I can do a convolution in the frequency domain. But I can't figure out how to make it work.
To understand how to do this I am trying to forward FFT an image as an array of pixelcolors and then backward FFT it to get the same array of pixelc... | One important thing to note when you do forward FFT followed by inverse FFT is that this normally results in a scaling factor of N being applied to the final result, i.e. the resulting image pixel values will need to be divided by N in order to match the original pixel values. (N being the size of the FFT.) So your out... |
7,791,299 | 7,793,007 | Use boost::function as function argument? | I want to call a function foo and let it behave differently.
(I'm adopting Strategy or Command pattern. They look similar to me.)
My overall plan is as follows..
First, define foo to take boost::function type
foo(boost::function<someType> execFunction)
{
// do something
execFunction(args);
// do something
}
Then, I... | This works very well. But sometimes it is preferable to work with a
functor so your callers are free to choose what is best for them and to prevent the smalll overhead that comes with a boost::function:
template<typename Func>
void foo(Func f) {
f(myArgs);
}
You can also add an overload for the specific boost::funct... |
7,791,330 | 7,791,396 | cannot convert parameter from `const char *` to `char *` | Given this code:
void group::build(int size, std::string *ips){
/*Build the LL after receiving the
member list from bootstrap*/
head = new member("head");
member *temp1,*temp2;
temp1 = new member(ips[0].data()); // error here
// ....
}
member::member(char *ip){
strcpy_s(this->ip_addr,sizeof(ip),ip);
this->next ... | Change line
member::member(char *ip)
to
member::member(const char *ip)
and, i'm not sure about your usage of strcpy_s
|
7,791,343 | 7,791,391 | srand not random at all - alternatives? | I was toying around with arrays, populating with pseudo random numbers, finding minimum and maximum values and their indices and number of occurrences and I noticed something strange - when using srand seeded with time the number of minimum and maximum value occurrences is ALWAYS equal. This doesn't seem very random to... | For a start, they're actually pseudo random numbers, not random numbers. In any case, it may be that a a truly random sequence has that exact property that you're seeing :-) The sequence 1,1,1,1,1 is as equally likely to occur in a truly random set as much as 5,2,4,2,99.
If you want a "more random" random sequence, I w... |
7,791,579 | 7,791,818 | C++ Template: Partial template Function Specialization in template class | I want to specialize specific function in template class.
Eg:
template<class T>
class A
{
public :
void fun1(T val);
void fun2(T val1, T val2);
};
template <class T>
void A<T>::fun1(T val)
{
// some task 1;
}
template <class T>
void A<T>::fun2(T val1, T val2)
{
// some task 2;
}
templa... | Your method fun2() is not a template method as itself, though it's a member of a template class. I don't find the proper technical term but in simple words, specializing fun2() will create an effect of a normal function definition. Putting the definition in header file will give you multiple definition error.
To solve ... |
7,791,675 | 7,800,435 | Windbg Set Conditional Breakpoints that depends on Call Stack | The problem: I need to make a script or an expression that that doesn't break if somewhere on callstack is a function with a specific name.
Specific question: How can I get functions on callstack to a list of strings ?
Example:
Module!MyFunctionWithConditionalBreakpoint
Module!Function1
Module!Function2
... | In WinDbg you may set a conditional breakpoint using special $spat function:
bp Module!MyFunctionWithConditionalBreakpoint "r $t0 = 0;.foreach (v { k }) { .if ($spat(\"v\", \"*Module!ClassA:MemberFunction*\")) { r $t0 = 1;.break } }; .if($t0 = 0) { gc }"
In pseudo-code it will be something like:
t0 = 0
foreach (token ... |
7,792,011 | 7,793,459 | Alternative to boost::shared_ptr in an embedded environment | I'm using C++ in an embedded linux environment which has GCC version 2.95.
I just can't extract boost::shared_ptr files with bcp, it is just too heavy.
What I'd like would be a simple smart pointer implementation of boost::shared_ptr but without all boost overheads (if it is possible...).
I could come up with my own ve... | if you don't need mixing shared and weak ptr,and don't need coustom deletors, you can just use the quick and dirty my_shared_ptr:
template<class T>
class my_shared_ptr
{
template<class U>
friend class my_shared_ptr;
public:
my_shared_ptr() :p(), c() {}
explicit my_shared_ptr(T* s) :p(s), c(new unsigned(... |
7,792,052 | 7,792,799 | C++ template to cover const and non-const method | I have a problem with duplication of identical code for const and non-const versions. I can illustrate the problem with some code. Here are two sample visitors, one which modifies the visited objects and one which does not.
struct VisitorRead
{
template <class T>
void operator()(T &t) { std::cin >> t; }
};
... | I tend to like simple solutions, so I would go for the free-function approach, possibly adding SFINAE to disable the function for types other than Aggregate:
template <typename Visitor, typename T>
typename std::enable_if< std::is_same<Aggregate,
typename std::remove_const<T>::type
... |
7,792,070 | 7,874,760 | How to send a mail using MAPI? | I want to send an e-mail using the mail client on the user's Windows computer. As far as I can tell from the net, MAPI is the way to go. However, after reading through the MSDN documentation, I find out that MAPI is quite vast, with no source code examples. And I have no need for 99% of the features, I just want to sen... | I have solved this by my own, with the help from various internet sources.
Official MSDN documentation
MAPIEx: Extended MAPI Wrapper
Once the code is properly tested & documented, I will try to post it here for future reference.
|
7,792,153 | 8,154,100 | CMake: how to specify custom import library name (MSVC) | I generate a shared library named, for example, mylib80.dll (it has
postfix "80", because I want to embed version info into library name.
I use set_target_properties with _POSTFIX property to achieve
this. By default, CMake names corresponding import library as
mylib80.lib. But I want my shared lib to have an import li... | Use the following CMake target properties to specify separate names for *.lib and *.dll files, rather than using the _POSTFIX property:
http://cmake.org/cmake/help/cmake-2-8-docs.html#prop_tgt:ARCHIVE_OUTPUT_NAME
http://cmake.org/cmake/help/cmake-2-8-docs.html#prop_tgt:LIBRARY_OUTPUT_NAME
http://cmake.org/cmake/help/cm... |
7,792,163 | 7,792,208 | dmDeviceName is just 'c' | I'm trying to get the names of each of my monitors using DEVMODE.dmDeviceName:
dmDeviceName
A zero-terminated character array that specifies the "friendly" name of the printer or display; for example, "PCL/HP LaserJet" in the case of PCL/HP LaserJet. This string is unique among device drivers. Note that this name ma... | Most likely you are using the Unicode version of the structure and thus are passing wide characters to printf. Since you use a format string that implies char data there is a mis-match.
The UTF-16 encoding results in every other byte being 0 for characters in the ASCII range and so printf thinks that the second byte of... |
7,792,235 | 7,793,622 | C++ compilation static variable and shared objects | Description :
a. Class X contains a static private data member ptr and static public function member getptr()/setptr().
In X.cpp, the ptr is set to NULL.
b. libXYZ.so (shared object) contains the object of class X (i.e libXYZ.so contains X.o).
c. libVWX.so (shared object) contains the object of class X (i.e libVWX.s... | The function is "public static", so I assume it's OOP-meaning of "static" (does not need instance), not C meaning of static (file-static; local to compilation unit). Therefore the functions are extern.
Now in Linux you have explicit right to override library symbols, both using another library or in the executable. All... |
7,792,260 | 7,792,377 | C++ Error with the operator* in a custom iterator for a b-tree | I'm getting the following error when trying to return the value using the operator*() in my custom iterator.
error: invalid initialization of non-const reference of type 'char&' from a temporary of type 'char'
If anyone is able to help me out, that would be great!
The specifics of the code is as follows:
Test code:
... | You're trying to use a reference to a temporary variable
template <typename T> T btree_node<T>::value() const { return value_; }
^^^
This returns a temporary copy of value_.
template <typename T> typename btree_iterator<T>::reference btree_iterator<T>::operator*() const {
^^^... |
7,792,682 | 7,792,727 | Skip same multimap values when iterating | Is there any good way to achieve the desired output below without having to remove the same values or creating another list/vector etc? I am trying to map words found in different documents to their document names as shown in the desired output.
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#i... | You could change inverts into map<string,set<string>>, mapping each word to the set of file names where it appears.
|
7,793,156 | 7,796,602 | OpenCV - HSV range of values for tracking red color | Could you please tell me how to what are ranges for Hue, Saturation and Value indices for intense red?
I try to use this values for color tracking and I couldn't find a specific answer via Google.
| You are the only one who can answer this question, since we don't know your criteria for "intense red". Collect as many samples as you can, some of which you consider intense red and some which are close but just miss the cut. Convert them all to HSL. Study the pattern.
You might put together a small app that has slide... |
7,793,340 | 7,807,173 | how to convert regex code in C# to c++ | I have this code in C#:
string data = "something ... 1,000 anything 20,000 other thing...";
string pattern = @"[0-9]+([\,|\.][0-9]{1,})*([\.\,][0-9]{1,})?";
MatchCollection collection = Regex.Matches(data, pattern);
foreach (Match item in collection)
{
Console.WriteLine("{0} - {1} - {2}", item.Value, item.Index, ... | I solved this way:
struct MatchInfo
{
string value;
int index;
int length;
};
vector<MatchInfo> DoRegex(string data, string pattern)
{
regex patternRegex(pattern);
sregex_token_iterator end;
vector<MatchInfo> result;
for (sregex_token_iterator i(data.begin(), data.end(), patternRegex); i !... |
7,793,381 | 7,793,423 | Ignoring a return-by-reference result from a function | Suppose i have a function that returns an important result and several unimportant results. I declared it so that the unimportant results are returned by reference:
int CalculateStuff(int param1, int param2, int& result1, int& result2);
I would like to call this function to calculate some stuff, but at call site i wan... | It is legal; auto_ptr objects will remain alive until the end of expression (i.e. function call). But it is ugly as hell.
Just overload your function:
int CalculateStuff(int param1, int param2, int& result1, int& result2);
int CalculateStuff(int param1, int param2) {
int r1=0, r2=0;
return CalculateStuff(para... |
7,793,419 | 7,793,523 | Fastest way of finding two minimum int64 elements in array | I have arrays with sizes from 1000 to 10000 (1k .. 10k). Each element is int64. My task is to find two smallest elements of the arrays, the minimum element and the minimum from the remaining.
I want to get fastest possible single-threaded code in C++ for Intel Core2 or Corei7 (cpu mode is 64 bit).
This function (gett... | Make sure your array-reading is will-behaved so it doesn't introduce needless cache-misses.
This code should probably be very close to bandwidth-bound on modern CPU:s, assuming the array-reading is simple. You need to profile and/or calculate if it still seems to have any headroom for CPU optimizations.
|
7,793,545 | 7,794,558 | Are there any projects using the Qt libraries for other things than desktop clients? | Qt has libraries for other things than UI:s. Are there any larger projects using the Qt libraries for other things that desktop clients?
| Qt does have a home in the embedded market space. I have seen applications in many different fields, including Building Security Systems, Medical Devices, GPS Units, Car Entertainment Systems, Tablets, and even Smart Phones. A look at the Qt in Use Speakers and Abstracts from the 2011 Qt Developers Days gives some mo... |
7,793,723 | 7,794,088 | Convert Mat to **float | I have an OpenCV function which return type is Mat.
How do I convert that to a 2 dimensional float array (** float)?
Probably very simple but I have not been able to do it myself.
| A quick look at the documentation for the Mat class doesn't reveal any obvious 'convert to float**' operator, but you could probably do it by hand:
Mat mat = (Mat_<float>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
// allocate and initialize a 2d float array
float **m = new float*[mat.Rows];
for (int r = 0; r < mat.Rows; ... |
7,793,820 | 7,793,859 | struct members memory layout | If I have a struct like this:
struct S {
ANY_TYPE a;
ANY_TYPE b;
ANY_TYPE c;
} s;
Can I safely assume that the following assumptions will always be true on all platforms?
((char *)&s.a) < ((char *)&s.c)
((char *)&s.a + sizeof(s.a) + sizeof(s.b)) <= ((char *)&s.c)
In C++ too?
| Yes, in C at least. The compiler is free to insert padding after any structure member but it must not reorder the members.
It must also not insert padding before the first member.
From C99, 6.7.2.1:
13/ Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that in... |
7,793,860 | 7,793,885 | C++ Using a Class Within a Class | I have a basic question that has bothered me for sometime.
When using a Class within a Class I can define the header of the Class I want to use in the header file. I have seen two ways of doing this and would like to know the difference between the two methods?
ex1
#include "ClassA.h"
class ClassB {
public:
C... | The comlpete layout of the classA is known to the compiler when you include the class definition.
The second syntax is called Forward declaration and now classA is an Incomplete type for the compiler.
For an Incomplete type,
You can:
Declare a member to be a pointer or a reference to the incomplete type.
Decla... |
7,793,971 | 7,794,640 | How can you get the display adapter used for a particular monitor in Windows? | On a Mac, I can use the following to print out the adapter used for a particular monitor:
io_registry_entry_t dspPort = CGDisplayIOServicePort(displays[i]);
CFDataRef model_;
model_ = (CFDataRef)IORegistryEntrySearchCFProperty(dspPort,kIOServicePlane,CFSTR("model"),
k... | I can think of three approaches:
The EnumDisplayDevices documentation mentions that the dwFlags argument can be used to get a device ID which can be used with the SetupAPI functions. That API provide a whole range of functions to get device information. So maybe you can get the device ID from EnumDisplayDevices, stick... |
7,793,997 | 7,794,565 | How to quickly count bits into separate bins in a series of ints on Sandy Bridge? | Update: Please read the code, it is NOT about counting bits in one int
Is it possible to improve performance of the following code with some clever assembler?
uint bit_counter[64];
void Count(uint64 bits) {
bit_counter[0] += (bits >> 0) & 1;
bit_counter[1] += (bits >> 1) & 1;
// ..
bit_counter[63] += (bits >> ... | Maybe you can do 8 at once, by taking 8 bits spaced 8 apart and keeping 8 uint64's for the counts. That's only 1 byte per single counter though, so you can only accumulate 255 invocations of count before you'd have to unpack those uint64's.
|
7,794,096 | 7,794,135 | interlocked reading a 64-bit variable | I have this c++ code (VS 2008):
LONGLONG res = InterlockedIncrement64(&m_longlong);
running along it, I would like to be able to read from the same variable
LONGLONG res = InterlockedWHAT?64(&m_longlong)
Since this is a 64-bit variable, a simple read is not considered threadsafe, yet I cannot find the correct Interlo... | LONGLONG res = InterlockedCompareExchange64(&m_longlong, 0, 0);
|
7,794,207 | 7,794,315 | Double template<> statements | There is such function definition:
template<>
template<>
void object::test<1>()
{
}
What does it mean that there are double template<>?
EDIT:
I extracted code which is valid for this example:
#include <iostream>
template <class U>
class A {
template <int n>
void test() {
}
};
template <class T>
class B... | For example,
template<class T = int> // Default T is int
class object<T> {
template<int R> void test ();
};
Your code:
template<> // T is fixed
template<> // R is fixed
void object<>::test<1>() // T is default int, R is 1
{
}
is equivalent to:
template<> // T is fixed
template<> // R is fixed
void object<int>::tes... |
7,794,408 | 7,799,720 | MySQL++ SSL Support on Linux | I am attempting to get MySQL++ to work correctly on Debian 6 with SSL support. I have tested everything on Windows 7 and it works great. Everything is encrypted. I am having a little bit of trouble porting it to Debian though.
This is my error:
terminate called after throwing an instance of 'mysqlpp::BadOption'
what... | This bug is fixed in MySQL++ 3.2.0, released today.
In older versions, there's a bug in the test for mysql_ssl_set(). If you cannot use the current version but can patch your version's source code, this will fix it:
Index: config/mysql_ssl.m4
===================================================================
--- confi... |
7,794,487 | 7,797,324 | Firebreath project changes are not displayed | I installed firebreath in Mac os x. Also, I installed the plugin. My problem is that when I try to do some change in my project (OpenOnDesktopPluginAPI.cpp), the changes are not refreshed in my browser. For example, I modified this method:
std::string OpenOnDesktopPluginAPI::get_version()
{
//return "CURRENT_VERSIO... | did you:
Recompile the browser plugin?
Restart the browser (if you replace the plugin binary while the browser is running it won't reload it)
Reinstall the plugin (if you copied the plugin to Internet Plugins/ then you need to copy the new version; if you used a symlink this won't matter)
|
7,794,638 | 7,795,058 | To generate a subset of size n one by one to reduce the complexity? | void AlgoMMPCbar::subs(const std::vector<unsigned int>& org, const std::vector<unsigned int>& pre, size_t k, size_t n, SubSets& c){
if (n <= 1) {
for(size_t i = k; i < org.size(); i++){
std::vector<unsigned int> v(pre);// instead of printing...
v.push_back(org.at(i));
c.push_back(v);
... | say ind maintains the indexes for elements in the subset in an increasing order, i.e.
ind[0] < ind[1] < ... < ind[n-1]
find the smallest j such that
j == n-1 || ind[j] + 1 < ind[j+1]
you may go to the next subset by
ind[j]++
ind[0] = 0; ind[1] = 1; ... ind[j-1] = j-1
note that the new ind array is still sorted. You... |
7,794,964 | 7,795,104 | value_type for a map having pointers as key | For what I know, C++ defines map<a,b>::value_type as pair<const a,b>
What will happen if I use a pointer type as key type in map, i.e., is
std::map<const char*,int>::value_type::first_type = const char*
as I would expect from definition above or
std::map<const char*,int>::value_type::first_type = const char* const
as... | Your reasoning is correct, value_type::first would be char const * const.
There is a common source of confusion in thinking that const T when T is a type * is const type *, but that is not so. Unlike macros, typedefs are not text substitution, nor are template arguments. When you do const T, if T is a typedef or templ... |
7,795,182 | 7,795,210 | How to get user input in do/while loop? | I tried to use the do / while loop I asked about and fixed in my one function in int main to allow the entire program to be rerun if the user wants to, but it is rerunning the program without waiting for user input.
int main()
{
int spoolnumber = 0; // Number of spools to be ordered
float subtotalspool = 0;... | You haven't added any code to accept user input. At the bottom of your loop, trying reading a character from cin into type.
Also, you may need to flush the output of cout first, before accepting the user input from cin.
|
7,795,197 | 7,795,263 | Application crashes, because of a high input | My application is terminating with signal 11 - segmentation fault.
Core dump has been generated, and it say the following:
#0 Players::shareExperience (this=0x7fd3f8187600,
experience=401912970206.76483154296875, m=<value optimized out>,
multiplied=<value optimized out>) at players.cpp:130
130 ... | That fault is not from the large long double value, it is most likely from dereferencing an invalid iterator in it (or an iterator with an invalid pointer value).
|
7,795,503 | 7,795,532 | Point in circle algorithm? |
Possible Duplicate:
How do you test if a point is inside a circle?
I need a way to determine if point P is inside circle C defined by a center point and a radius.
Is there an algorithm for this?
Thanks
| Yes, and the algorithm is quite simple. Just check if the distance from the point P to the center of the circle C is less than the radius of the circle.
|
7,795,828 | 7,795,898 | No matching function for call | I've been getting this error, and I can't figure out how to fix it:
btree.tem:98: instantiated from 'std::pair<typename btree<T>::iterator, bool> btree<T>::insert(const T&) [with T = char]'
test.cpp:13: instantiated from here
btree.tem:37: error: no matching function for call to 'btree<char>::addElem(std::_List_ite... | The compiler is looking for:
btree<char>::addElem(std::_List_iterator<node<char>*>&, node<char>*&)
But it only found something for:
btree<char>::addElem(std::_List_iterator<node<char>*>&, node<char>&)
You're passing a pointer to your function. You've not defined an addElem that takes a pointer as its last argument.
|
7,795,982 | 7,796,025 | Infinite Recursion in Meta Integer Square Root | Good day,
A friend of mine is asking about transforming an integer square root function into a meta-function. Here is the original function:
unsigned isqrt(unsigned value)
{
unsigned sq = 1, dlt = 3;
while(sq<=value)
{
sq += dlt;
dlt += 2;
}
return (dlt>>1) - 1;
}
I wrote a meta ve... | Template evaluation isn't lazy by default.
static const std::size_t square_root =
sq <= value ?
isqrt_impl<value, sq+dlt, dlt+2>::square_root :
(dlt >> 1) - 1;
will always instantiate the template, no matter what the condition. You need boost::mpl::eval_if or something equivalent to get that solution to w... |
7,795,995 | 7,796,340 | Parsing a Wavefront .obj file using C++ | While trying to a parse a wavefront .obj file, I thought of two approaches:
Create an 2D array the size of the number of vertices. When a face uses a vertex, get it's coordinates from the array.
Get the starting position of the vertex list and then when a face uses a vertex, scan the lines until you reach the vertex.
... |
IMO, Option 1 will be very memory intensive, but much faster.
You must get those vertices into memory anyway. But there's no need for a 2D array, which BTW would cause two pointer indirections, thus a major performance hit. Just use a simple std::vector<Vertex> for your data, the vector index is the index for the acc... |
7,796,191 | 7,796,279 | Generating a square wave for DFT | I'm working on an assignment to perform a 200 point DFT at a sampling frequency of 20kHz on a square wave of frequency 500Hz whose amplitude alternates between 0 and 20.
I'm using C++ and I have figured how to code the DFT equation, my problem is I'm having trouble representing the square wave in code using a for loop.... | One cycle of your square wave will take 1/500 seconds. Each sample will be 1/20000 seconds. A simple division should tell you how many samples each square wave will be.
Another division will tell you how many of those waves will fit in your 200 point window.
|
7,796,311 | 7,796,351 | Prime factors generation C++ | Here is what I have so far:
//project Eular Problem 4: Prime Factors
#include<iostream>
#include<cmath>
typedef unsigned long long int uint_64;
using namespace std;
void storeFactors(uint_64 factors[], uint_64 num)
{
for(uint_64 i=0;i*i<num;i++
factors[i]=1; //assign 1 to all the values
for(uint... | The prime factors of 100 are the same as the prime factors of 10, only the multiplicity is different.
It appears that your representation doesn't have any way to store repeated factors.
|
7,796,670 | 7,796,724 | Is X const &x == X & const x? | I understand that X & const x is redundant. It is not ok! But I want to know what is the difference between X const &x and X & const x?
Is the first expression saying that x is a reference to a constant class X ?
| Read it from right to left : X& const x - x is a constant reference to object of type X which doesn't make sense, references are constant by definition. X const& x - x is a reference to constant of type X.
|
7,796,857 | 7,797,560 | Streaming into vector? | Have stumbled upon this code to insert the contents of a file into a vector. Seems like a useful thing to learn how to do:
#include <iostream>
#include <fstream>
#include <vector>
int main() {
typedef std::vector<char> fileContainer;
std::ifstream testFile("testfile.txt");
fileContainer container;
containe... | I'm not sure that there's a best way, but using the two iterator
constructor would be more idiomatic:
FileContainer container( (std::istreambuf_iterator<char>( testFile )),
(std::istreambuf_iterator<char>()) );
(I notice that you have the extra parentheses in your assign. They
aren't necessar... |
7,796,925 | 7,797,171 | Weirdness in C++03 seekoff() and seekpos() specification | I am creating my own streambuf subclass and using the C++03 spec (ISO/IEC 14882:2003) as a reference.
In section 27.5.2.4.2 [lib.streambuf.virt.buffer], the specifications for both basic_streambuf::seekoff() and basic_streambuf::seekpos() say:
Default behavior: Returns pos_type(off_type(-1)).
Now, I thought off_type ... | I believe that pos_type by default boils down to a std::streampos, which is typically defined like this:
typedef fpos<mbstate_t> streampos;
std::fpos is usually an offset combined with a multi-byte state object.
Additionally, off_type by default will boil down to a std::streamoff which is also a signed integral type (l... |
7,796,931 | 7,800,909 | OpenCV Error: Bad argument (Array should be CvMat or IplImage) in cvGetSize | I have successfully written a video processing program. I used ubuntu and Netbeans for programming. When I run this program on netbeans it runs perfectly and gives expected output.
I built executable file of this program both in debug and release mode and tried to run them in the command line. Now I get the following e... | Can you check if the input argument to cvGetSize is:
a NULL pointer? What is the result of querying/retrieving the frame?
a CvSeq?
a 1- or 3-dimensional array?
Usually it is the first.
That's the way OpenCV talks to you - it's more often the runtime exception than a compiler error.
|
7,796,935 | 7,796,957 | QScriptValue::toVariant but no fromVariant? | QScriptValue::toVariant can turn basic string and number types, as well as arrays and objects (associative arrays), into a QVariant.
There doesn't seem to be any corresponding way to construct a QScriptValue from a QVariant.
Is it hiding, or missing?
| http://qt-project.org/doc/qt-5/qscriptengine.html#newVariant
QScriptValue QScriptEngine::newVariant(const QVariant & value)
Creates a Qt Script object holding the given variant value.
If a default prototype has been registered with the meta type id of
value, then the prototype of the created object will be that
pr... |
7,796,936 | 7,796,966 | Why can't we have non-const class-level static variables? | Why does the Visual C++ compiler refuse to compile this code?
I obviously know that the error is:
Error C2864: Singleton<T>::p:
Only static const integral data members can be initialized within a class
but why? (i.e. is there a technical reason why it is not allowed?)
Is this compiler-specific behavior or is it m... | That's standard behavior. Only static const integral members can be initialized without a proper definition. All other types need to be defined somewhere, and the initialization is written at the point of definition:
template<typename T>
struct Singleton {
static T *p;
static T *getInstance() { /*...*/ return ... |
7,796,962 | 7,796,993 | C++ Sort Class Type Vector | I have a struct named Recipes.h and a vector called vector<Recipes> recipes. The vector contains 1 int, and 2 strings in each element (a string chef name and a string called instructions). However I want to sort the whole vector ONLY by the string chef_name. I tried doing something like this
sort(recipes.begin(),recipe... | From the very short snip of code you posted, it can be seen that you use recipes first as an object and then as a type. Your comparison function probably wants as parameters Recipes > const& instead. Note that if the operation does not depend on the Menu class it would be better to declare this function as a static mem... |
7,797,113 | 7,797,142 | Correct way to add a const to a class | This does not work. It gives an error regarding ISO C++ forbidding initialization.
class hash_map
{
private:
hash_entry **table;
const int TABLE_SIZE = 128;
public:
hash_map()
{
table = new hash_entry*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = NULL;
... | const int TABLE_SIZE = 128;
This is the cause of the compilation error. It is allowed in C++11 only, not in C++03 and C++98.
Either make it a static member of the class, OR initialize it in the constructor. Make use of member-initialization-list for it.
Apart from that dont forget to implement copy-semantics followin... |
7,797,202 | 7,797,330 | Netbeans "-O3" optimization for Qt projects | I'm coding Qt/C++ in Netbeans 7.0 and i want enable -O3 compiler switch for my project.
The default optimization level of building a project is -O2 in Netbeans.
I added -O3 in this way:
Properties > Build > Qt > Expert > Custom Definitions > Add QMAKE_CXXFLAGS += -O3.
but when rebuilding the project i see this for each... | I assume you need -O3 for release build only, right?
Then setting QMAKE_CXXFLAGS_RELEASE += -O3 puts -O3 ater -O2, at least in my command line build in Debian and MacOS X.
That would make sense, since -O2 is provided by QMAKE_CXXFLAGS_RELEASE in platform-specific mkspecs, so appending anything should work like this.
|
7,797,218 | 8,902,162 | Calculating optical flow with opencv | I am using the function:
cvCalcOpticalFlowBM
To calculate the optical flow.
The code is running, but the velocity matrices are zero (both x and y), although the input video clearly changes.
Does anyone have an idea why would the velocity matrices be zero (black)?
| This tutorial shows how to use optical flow in opencv from scratch. It explains how to draw velocity vectors etc.
http://robots.stanford.edu/cs223b05/notes/CS%20223-B%20T1%20stavens_opencv_optical_flow.pdf
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.