Instead of doing this for calloc:
TCHAR *sText = (TCHAR *) calloc(1024, sizeof(TCHAR));
I have this at the top of my C++ file:
#define tcalloc(nCharacters) (TCHAR*)calloc(nCharacters,sizeof(TCHAR))
so I can more easily write this:
TCHAR *sText = tcalloc(1024);
Now, how do I do a shorthand for my std::vector statement? This is my code:
std::vector <TCHAR>sText(1024,0);
maybe
typedef std::vector<TCHAR> tcVec;
#define init_1k_charVector tcVec(1024,0)
int main(int, char**)
{
tcVec sText(1024,0);
tcVec sText2 = init_1k_charVector;
...
}
Related
I was trying to use a for each [Modern c++ style] but the code is crashed each time!
It was something like :
for(auto &k:mimeData->formats())
{ ... }
And later out of my surprises I found that the QStringList returned by formats is either invalid or completely separate object though the internal data is ought to be same!
So I tried to figure out in more simple example :
#include <iostream>
#include <string>
#include <list>
#include <QCoreApplication>
#include <QMimeData>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
cout<<boolalpha;
list<string> ls;
cout<<(ls.begin() != ls.end())<<"\n";
QStringList qsl;
cout<<(qsl.begin() != qsl.end())<<"\n";
QMimeData qme;
cout<<(qme.formats().begin() != qme.formats().end())<<"\n";
cout<<"OMG! is it empty? -> "<<qme.formats().empty()<<"\n";
return a.exec();
}
The output is something like :
false
false
true
OMG! is it empty? -> true
Until or unless I take an rvalue reference I cant decide what is happening internally!
I really need a solution to use it with range based for loops, not Qt's foreach!
P.S. I dont want to copy it to avoid O(n).
Looking at the docs, there's no guarantee QMimeData class keeps QStringList of supported formats (http://doc.qt.io/qt-4.8/qmimedata.html#formats) as a field.
The source code supports that (Qt5.4/Src/qtbase/src/corelib/kernel/qmimedata.cpp:593):
QStringList QMimeData::formats() const
{
Q_D(const QMimeData);
QStringList list;
for (int i=0; i<d->dataList.size(); i++)
list += d->dataList.at(i).format;
return list;
}
Therefore this list is constructed on every call to formats(). Farther calls to it will always yield a separate container.
Since you do need to preserve it to traverse it, I'd recommend keeping a local copy of it. Do note that C++11 allows for it to be moved constructed (or in fact - optimized even better).
I'm trying to convert a C++ std::map to C#.
I know that there is a way to do this using std_map.i but it only seems to work if I write for every class a new template like
%template(String_Foo_Map) std::map<std::string, Foo>;
%template(String_Bar_Map) std::map<std::string, Bar>;
...
Is there a way to this is automatically, no matter what type is used? Something like
%template(String_T_Map) std::map<std::string, T>;
and it would create
String_Foo_Map
String_Bar_Map
...
You can define macros for SWIG similarly to how it is done for Numpy
Header file
#include <map>
#include <string>
class A {
public:
A() : m_a(1.0f) {}
float m_a;
};
class B {
public:
B() : m_b(2.0f) {}
float m_b;
};
SWIG interface file
%module test
%{
#include "test.h"
%}
%include "std_map.i"
%include "std_string.i"
%include "test.h"
%define %my_templates(DATA_TYPE)
%template(String_ ## DATA_TYPE ## Map) std::map<std::string, DATA_TYPE>;
%enddef
%my_templates(A)
%my_templates(B)
The example is now complete
I'm working on turning some MCMC software written in c++ into an R-package using Rcpp and modules. In this regard I need to maintain a pointer that is a global variable, and that points to the latest object of some class constructed.
Here is a very simple example in the form of an R-script:
require(Rcpp)
require(inline)
inc <- '
using namespace Rcpp;
class test;
test* glob; //global pointer
class test{
private:
double foo;
public:
test(double foo_) : foo(foo_) {
glob=this; // the line causes segfault
};
double get_foo(){return foo;};
};
RCPP_MODULE(test){
class_<test>("test")
.constructor<double>()
.property("foo",&test::get_foo)
;
}
'
fx <- cxxfunction(signature(),plugin="Rcpp",include=inc);
test_module <- Module("test",getDynLib(fx))
test <- test_module$test
t1 <- new(test,1.0)
What I'm trying to get at is something like the following (in c++):
#include<iostream>
class test;
test* glob;
class test{
private:
double foo;
public:
test(double foo_) : foo(foo_) {glob=this;};
double get_foo(){return foo;};
};
int main(){
test t1(1.0);
test t2(2.0);
std::cout << (*glob).get_foo() << std::endl;
}
Which compiles and runs as it should.
Thanks in advance,
Regards, Tore Kleppe
That seems like two unrelated and simple errors.
First off, you need to make that pointer static. Things then work.
Second, using Rcpp Module with inline is no
longer the easiest way around, and we generally recommend using a package -- or Rcpp Attributes as I do below.
Correct code, including explicit messaging to stdout in the constructor:
#include <Rcpp.h>
using namespace Rcpp;
class test;
static test* glob = NULL; //global pointer
class test{
private:
double foo;
public:
test(double foo_) : foo(foo_) {
Rcpp::Rcout << "Seeing foo_ of " << foo_ << " in ctor\n";
glob=this; // the line causes segfault
};
double get_foo(){return foo;};
};
RCPP_MODULE(test){
class_<test>("test")
.constructor<double>()
.property("foo",&test::get_foo)
;
}
Then simple use from the command-line (using littler; R or Rscript are equivalent):
$ r -lRcpp -e 'sourceCpp("/tmp/tore.cpp"); tt <- new(test, 1.23); print(tt$foo)'
Seeing foo_ of 1.23 in ctor
[1] 1.23
$
Note how we can skip all the Module instantiation etc.
I have a std::map called 'prompts' which is declared like this:
std::map<const int, wstring, std::less<int>, std::allocator<std::pair<const int, std::wstring> >> prompts;
and it stores int 'key' and wstring 'value' pairs. If I do this:
wcout << prompts[interpreter->get_state()];
The compiler (vc10) complains
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::basic_string<_Elem,_Traits,_Ax>' (or there is no acceptable conversion)
What do I have to do to get the wstring value returned from the map to print with wcout? Some sort of cast? Or...?
In the first line, you are missing an std::
std::map<const int,std::wstring, std::less<int>, std::allocator<std::pair<const int, std::wstring> >> prompts;
You should write std::wcout instead of wcout.
I just tried this code and it compiles.
#include <map>
#include <iostream>
#include <string>
int main()
{
std::map<const int, std::wstring, std::less<int>, std::allocator<std::pair<const int, std::wstring> >> prompts;
std::wcout << prompts[1];
return 0;
}
Is there any function or something like that by which I can create totally random strings or numbers?
You can create random numbers using qrand. If you need strings, you can convert the int to string. You could also check the QUuid class, which generates Universally Unique Identifiers. Those are not 'totally random', but they are unique.
int number;
int randomValue = qrand() % number;
returns a random number randomValue with 0 <= randomValue < number.
qrand() is declared in QtGlobal which is #included by many other Qt files.
int value;
QString aString = QString::number(value);
converts an integer to QString.
The following example generates alphabetic strings with capital letters from A to Z and length = len.
QString randString(int len)
{
QString str;
str.resize(len);
for (int s = 0; s < len ; ++s)
str[s] = QChar('A' + char(qrand() % ('Z' - 'A')));
return str;
}
This is not a very good method to generate random numbers within a given range. (In fact it's very very bad for most generators )
You are assuming that the low-order bits from the generator are uniformly distributed. This is not the case with most generators. In most generators the randomness occurs in the high order bits.
By using the remainder after divisions you are in effect throwing out the randomness.
You should scale using multiplication and division. Not using the modulo operator.
eg
my_numbe r= start_required + ( generator_output * range_required)/generator_maximum;
If generator_output is in [0, generator_maximum],
my_number will be in [start_required , start_required + range_required].
Use QUuid
#include <QUuid>
QString randomStr = QUuid::createUuid();
Works in Qt6
double value= QRandomGenerator::global()->bounded(0, 10);
Generate a double from 0 to 10
Here is the good answer using qrand(). The solution below uses QUuid, as already was suggested above, to generate random and unique ids (they are all hex numbers):
#include <QApplication>
#include <QDebug>
#include <QRegularExpression>
#include <QUuid>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// random hex string generator
for (int i = 0; i < 10; i++)
{
QString str = QUuid::createUuid().toString();
str.remove(QRegularExpression("{|}|-")); // if you want only hex numbers
qDebug() << str;
}
return a.exec();
}
Output
"479a494a852747fe90efe0dc0137d059"
"2cd7e3b404b54fad9154e46c527c368a"
"84e43735eacd4b8f8d733bf642476097"
"d7e824f920874f9d8b4264212f3bd385"
"40b1c6fa89254705801caefdab5edd96"
"b7067852cf9d45ca89dd7af6ffdcdd23"
"9a2e5e6b65c54bea8fb9e7e8e1676a1a"
"981fa826073947e68adc46ddf47e311c"
"129b0ec42aed47d78be4bfe279996990"
"818035b0e83f401d8a56f34122ba7990"