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 |
|---|---|---|---|---|
70,117,628 | 70,117,678 | How to pass array of arrays to a template class with non-type parameters | I would assume the below code would work to initialize the Matrix class, but for Matrix C I get the following:
error C2440: 'initializing': cannot convert from 'initializer list' to 'Math::Linear::Matrix<int,2,2>'
template<class T, unsigned int Rows, unsigned int Cols>
class Matrix
{
public:
Matrix(std::array<std::array<T,Cols>,Rows> ArrayArray)
{
}
}
std::array<std::array<int, 2>, 2> A = {{ {{1,1}} , {{1,1}} }};
Matrix<int, 2, 2> B = A;
Matrix<int, 2, 2> C = {{ {{1,1}} , {{1,1}} }};
| To use initializer list initialization, you need one more { }.
std::array<std::array<int, 2>, 2> A = {{ {{1,1}} , {{1,1}} }} ;
Matrix<int, 2, 2> C = { {{ {{1,1}} , {{1,1}} }} };
|
70,117,629 | 70,123,392 | is_base_of SFINAE toggle on class | I'm working on a template toolkit for declarative UI building. I have the templates compiling on Windows as expected but the GCC/clang compilers are taking issue with my SFINAE work.
I'm using Qt as the base, and I'm hoping to include QLayout and QWidget items in the wrapper structure while toggling on/off functions of the wrapper based on the object they represent.
They both derive from QObject which provides a ton of common ground, but I want to include their extended functionality.
On MSVC, the following works exceptionally well
// let cls be the input subclass of QWidget or
// QLayout which is passed to the owning wrapper template
template<typename = std::enable_if<std::is_base_of<QWidget, cls>::value == true>>
Wrapper &style() {
cast()->setStyleSheet(stylesheet);
return *this;
}
However GCC/clang don't agreed. I've tried using something akin to:
template<typename Empty = void,
typename = typename std::enable_if<
std::is_base_of<QWidget, cls>::value, Empty
>::type
>
Wrapper &style(const QString &stylesheet) {
cast()->setStyleSheet(stylesheet);
return *this;
}
But still get an error stating that QLayout subclasses don't have a member setStyleSheet. And while it doesn't, I was hoping to have the compiler skip over the function entirely as it does in MSVC.
I'm assuming I have a misunderstanding of the SFINAE system and need to either adjust my template declaration, or just suck it up and split the two items and repeat the code.
EDIT:
Reproduction of Issue:
https://gcc.godbolt.org/z/oGzsKhrn4
The top bits are just minimal reprs of Qt objects and it represents the same basic structure I'm after, you can mostly ignore them.
The macros are to ease the templating required for each class. If nothing else, I can always break it up and add additional macros to fill in QWidget vs. QLayout functionality, I just liked how clean it was for Windows.
| In your example, the behavior of style function body is not dependent on its template parameters and a compiler can check the correctness. I guess this is allowed by the standard in [temp.res#general]:
The program is ill-formed, no diagnostic required, if:
...
— a hypothetical instantiation of a template immediately following its definition would be ill-formed due to a construct that does not depend on a template parameter,
...
However, you can make QVBoxLayout a template default parameter as before (instead of Empty), but make the body dependent on this parameter too:
template<typename QVBoxLayout_ = QVBoxLayout,
typename = typename std::enable_if<
std::is_base_of<QWidget, QVBoxLayout_>::value, void
>::type
>
VLayout &style(const QString &stylesheet) {
QVBoxLayout_::cast()->setStyleSheet(stylesheet); // "shouldn't matter"
return *this;
}
But in this case we have an issue. Some user might accidentally pass this parameter and SFINAE will be broken, so I propose the following fix. Add a parameter pack as a first function template parameter. It will "eat" all accidentally passed parameters, so users won't be able to override the default parameters:
template<typename..., typename QVBoxLayout_ = QVBoxLayout...
And, of course, you can add an assertion that a user does not try to override these parameters unintentionally. In summary:
template<typename... ParameterGuard_,
typename QVBoxLayout_ = QVBoxLayout,
typename = typename std::enable_if<
std::is_base_of<QWidget, QVBoxLayout_>::value, void
>::type
>
VLayout &style(const QString &stylesheet) {
static_assert(sizeof...(ParameterGuard_) == 0,
"This function template is not intended to accept template parameters");
QVBoxLayout_::cast()->setStyleSheet(stylesheet); // "shouldn't matter"
return *this;
}
|
70,117,664 | 70,117,810 | How to Link .csv Files With the Release version of my Qt App? | My Qt Project uses .csv(not my choice) files to save and load data from ,as i am looking to deploy the app , how do i add these files into the release version and what changes to my code should i do ?
right now i am using QFile and giving it the full path to each file like so :
QFile Fich1("C:/Users/ahmed/Desktop/MyWork/QtProject/Bibliotheque/Arrays.csv");
| If you're looking to ship CSV files as part of your application, one good way to do it is to use Qt's resource-file system; then they will be compiled into your app so there's no chance of them getting lost/modified/moved.
OTOH if you want to ship CSV files with your app but as separate files (e.g. so that the user can see and load them using a file dialog), then you can package them together with the executable, and then use QCoreApplication::applicationDirPath() as the default directory for the QFileDialog to present to the user.
|
70,117,724 | 70,117,766 | When deleting array: "Process returned -1073740940 (0xC0000374)" Only with certain numbers | The program returns the user N number of odd squares starting from 1.
From numbers 5-10 and then 20, (I didn't go further) when deleting array A it crashes with the error message: "Process returned -1073740940 (0xC0000374)". Which is apparently a memory violation?
#include <iostream>
using namespace std;
int main(){
int ok;
int counter;
do {
int size;
while (true) {
cout << "Enter the number of perfect odd squares you want" << endl;
cin >> size;
if(size<1) {
cout << "Enter a valid number" << endl;
continue;
}
else break;
}
if (size%2==0) counter=size*2-1;
else counter=size*2;
int *A = new int[size];
for (int i=1; i<=counter; i=i+2){
A[i]=i*i;
cout<<A[i] << endl;
}
delete[]A;
cout << " Continue (1) or quit (0)?" << endl;
cin >> ok;
}while(ok==1);
}
| From the NTSTATUS reference:
0xC0000374 STATUS_HEAP_CORRUPTION - A heap has been corrupted
You appear to access A (a heap allocated object) out of bounds - A[0] through A[size-1] are valid elements to access but counter goes as high as 2*size. Any attempts to write to values past A[size-1] can corrupt the heap leading to this error.
Calculate counter first and use that as the allocation size.
|
70,117,922 | 70,118,293 | Passing a C-style array to `span<T>` | C++20 introduced std::span, which is a view-like object that can take in a continuous sequence, such as a C-style array, std::array, and std::vector. A common problem with a C-style array is it will decay to a pointer when passing to a function. Such a problem can be solved by using std::span:
size_t size(std::span<int> s)
{
return s.size();
}
int main()
{
std::array arr = {1,2,3,4,5};
std::vector vec = {1,2,3,4,5};
auto il = {1,2,3,4,5};
int c_arr[] = {1,2,3,4,5};
std::cout << size(arr) << size(vec) << size(il) << size(c_arr);
}
This would print 5555, as expected. However, size probably shouldn't take in only containers of int. Instead it should take in containers of any type. However, changing the size to a templated function, that takes in a std::span<T>, it can no longer substitute the C-style array successfully, while the others can:
template<typename T>
size_t size(std::span<T> s)
{
return s.size();
}
int main()
{
std::array arr = {1,2,3,4,5};
std::vector vec = {1,2,3,4,5};
auto il = {1,2,3,4,5};
int c_arr[] = {1,2,3,4,5};
std::cout << size(arr) << size(vec) << size(il) << size(c_arr);
^^^^^^^^^^^
// error: no matching function for call to 'size(int [5])'
// note: template argument deduction/substitution failed:
// note: mismatched types 'std::span<_Type, 18446744073709551615>' and 'int*'
}
Godbolt
Is this the correct behavior? If so, is there a way to accept a C-style array with span<T>?
| The question is not why this fails for int[], but why it works for all the other types! Unfortunately, you have fallen prey to ADL which is actually calling std::size instead of the size function you have written. This is because all overloads of your function fail, and so it looks in the namespace of the first argument for a matching function, where it finds std::size. Rerun your program with the function renamed to something else:
template<typename T>
size_t my_size(std::span<T> s)
{
return s.size();
}
And on GCC 12 I get
prog.cc:18:25: error: no matching function for call to 'my_size(std::array<int, 5>&)'
18 | std::cout << my_size(arr) << my_size(vec) << my_size(il) << my_size(c_arr);
| ~~~~~~~^~~~~
prog.cc:7:8: note: candidate: 'template<class T> size_t my_size(std::span<_Type, 18446744073709551615>)'
7 | size_t my_size(std::span<T> s)
| ^~~~~~~
prog.cc:7:8: note: template argument deduction/substitution failed:
prog.cc:18:25: note: 'std::array<int, 5>' is not derived from 'std::span<_Type, 18446744073709551615>'
18 | std::cout << my_size(arr) << my_size(vec) << my_size(il) << my_size(c_arr);
| ~~~~~~~^~~~~
plus similar errors for all the other types. If your question is why is this failing; then the short answer is that template type deduction is far more strict than regular type deduction and so unless you give it an exact match (more or less), it will fail. For a more detailed explanation, read a similar question such as this one which deals with something similar.
|
70,118,298 | 70,118,341 | Does cout treat bool as integer or integer as bool? | Why does this program
int a = 8;
cout << a && true ;
cout << typeid(a && true).name();
output
8bool
Frankly, I expected "truebool" or "8int".
Is operator << of cout object involved in this or is it a precedence issue?
Does it convert true to 1 as in the case when we cout << true;?
typeid(a && true) gives us bool, though the cout << a && true; is obviously a number?
| Indeed it is an operator precedence issue. << has a higher precedence than &&.
One shorthand trick you can use to interpret an integer value to bool is to double-NOT it:
cout << !!a;
This is a matter of style, which may be divisive within the C++ community. So, if you don't want to be controversial, then the following may be more acceptable:
cout << (a ? true : false);
cout << static_cast<bool>(a);
cout << (a != 0);
Personally, I think that (a && true) is somewhat ugly. But I'm sure there are some who would argue otherwise.
In the end, the compiler should be generating the same result no matter how you write it.
|
70,118,823 | 70,128,134 | format wstring with fmt fails: no matching function for call to 'format(const wchar_t [17], int)' | I am using fmt 8.0.1 with code blocks 20.03 and gcc 8.1.0 in windows 10, and when trying to compile this code
#include <fmt/format.h>
int main(){
std::wstring a = fmt::format(L"The answer is {}", 42);
}
I get the following errors
main.cpp: In function 'int main()':
main.cpp:4:57: error: no matching function for call to 'format(const wchar_t [17], int)'
std::wstring a = fmt::format(L"The answer is {}", 42);
^
In file included from D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/format.h:44,
from main.cpp:1:
D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/core.h:2885:17: note: candidate: 'std::__cxx11::string fmt::v8::format(fmt::v8::format_string<T ...>, T&& ...) [with T = {int}; std::__cxx11::string = std::__cxx11::basic_string<char>; fmt::v8::format_string<T ...> = fmt::v8::basic_format_string<char, int>]'
FMT_INLINE auto format(format_string<T...> fmt, T&&... args) -> std::string {
^~~~~~
D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/core.h:2885:17: note: no known conversion for argument 1 from 'const wchar_t [17]' to 'fmt::v8::format_string<int>' {aka 'fmt::v8::basic_format_string<char, int>'}
In file included from main.cpp:1:
D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/format.h:2784:13: note: candidate: 'template<class Locale, class ... T, typename std::enable_if<fmt::v8::detail::is_locale<Locale>::value, int>::type <anonymous> > std::__cxx11::string fmt::v8::format(const Locale&, fmt::v8::format_string<T ...>, T&& ...)'
inline auto format(const Locale& loc, format_string<T...> fmt, T&&... args)
^~~~~~
D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/format.h:2784:13: note: template argument deduction/substitution failed:
In file included from D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/format.h:44,
from main.cpp:1:
D:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/fmt/format.h:2783:11: error: no type named 'type' in 'struct std::enable_if<false, int>'
FMT_ENABLE_IF(detail::is_locale<Locale>::value)>
^~~~~~~~~~~~~
Compilation command:
g++ main.cpp "D:\descargas\fmt-8.0.1\fmt-8.0.1\build\libfmt.a"
| Per documentation you should include fmt/xchar.h for wchar_t support:
#include <fmt/xchar.h>
int main() {
std::wstring a = fmt::format(L"The answer is {}", 42);
}
godbolt
|
70,119,353 | 70,119,374 | Please explain the significance of []() in C++ | I am building some HTML forms handlers using ESP32 in Arduino.
In a lot of tutorials I see something like the following...
update_server.on("/", HTTP_GET, []() {
blah;
blah;
});
And here is another..
update_server.on("/update", HTTP_POST, []() {
blah;
blah;
}, []() {
more blah;
etc...
});
Can someone please explain to me the [] and the () parts?
I have some vague feeling about these representing function calls, but I am having trouble finding references to this particular syntax.
Thanks, Mark.
| Those are lambda functions. They are functions without a name basically.
You can read more about it here:
https://www.tutorialspoint.com/lambda-expression-in-cplusplus
|
70,119,551 | 70,119,561 | Problem accessing member of struct inside a class | I am making a battleship board game in c++ and have issues accessing the struct that I have declated inside one of my classes.
class Ship {
typedef struct {
int x;
int y;
}Start;
typedef struct {
int x;
int y;
}End;
bool isAfloat;
Start _start;
End _end;
public:
Ship(int start_x, int start_y, int end_x, int end_y);
I have tried to do in every thinkable way but I'm clearly missing something here.
Ship::Ship(int start_x, int start_y, int end_x, int end_y):
_start.x(start_x), //error, expected "(" where the "." is
_start.y(start_y),
_start.x(end_x),
_end.y(end_y)
{}
Any help appreciated.
| You need to initialize the whole object directly, not their members separately. E.g.
Ship::Ship(int start_x, int start_y, int end_x, int end_y):
isAfloat ( ...true_or_false... ), // better to initialize it too
_start {start_x, start_y},
_end {end_x, end_y}
{}
BTW: Since C++20 you can use designated initializers then you can specify members' name as:
Ship::Ship(int start_x, int start_y, int end_x, int end_y):
isAfloat ( ...true_or_false... ), // better to initialize it too
_start {.x = start_x, .y = start_y},
_end {.x = end_x, .y = end_y}
{}
|
70,120,158 | 70,124,104 | Mongocxx accessing Error from different cpp file | I have created a header mongo.h it contain
mongocxx::instance inst{};
mongocxx::uri uri{ "link*****" };
mongocxx::client client{ uri };
i accessed the mongodb from main.cpp by including this
mongo.h
but when including this header to other cpp file it return error.
Documents saying that the instance must create once .
i have read http://mongocxx.org/api/current/classmongocxx_1_1instance.html
not understand fully, i dont familiar with constructor and destructor ,,
Any body please help to access mongodb from every cpp file .
| This is a good example of where a singleton could help.
In mongo.h, put a single function declaration:
mongocxx::client& get_client();
In a single cpp file, define the function as follows:
mongocxx::instance inst{};
mongocxx::client& get_client() {
static mongocxx::client client{mongocxx::uri{ "link*****" };};
return client;
}
By putting this in a separate .cpp file, you ensure that inst is created some time before the main function starts. The static keyword in get_client ensures that the client is only ever created once, namely the first time get_client is called.
|
70,120,165 | 70,122,996 | In the constructor of WebRTC VideoSendStreamParameters, why is the config argument not passed by a reference? | In the constructor of WebRTC VideoSendStreamParameters, config argument is passed by a value(thus introducing a copy overhead), but options argument is passed by a reference.
Also the config member is initialized by std::move(config).
I want to know why they designed like this.
The followings are scraped from Chromium source.
namespace webrtc {
...
class VideoSendStream {
...
struct Config {
...
Config() = delete;
Config(Config&&);
... // It's followed by many data members.
};
...
};
...
}
namespace cricket {
...
class WebRtcVideoChannel ... {
...
class WebRtcVideoSendStream {
...
struct VideoSendStreamParameters {
VideoSendStreamParameters(
webrtc::VideoSendStream::Config config,
const VideoOptions& options, ...)
...
webrtc::VideoSendStream::Config config;
VideoOptions options;
...
};
VideoSendStreamParameters parameters_ ... ;
...
};
...
};
WebRtcVideoChannel::WebRtcVideoSendStream::VideoSendStreamParameters::
VideoSendStreamParameters(
webrtc::VideoSendStream::Config config,
const VideoOptions& options, ...)
: config(std::move(config)),
options(options), ... {}
WebRtcVideoChannel::WebRtcVideoSendStream::WebRtcVideoSendStream(
...
webrtc::VideoSendStream::Config config,
const VideoOptions& options, ...)
: ...,
parameters_(std::move(config), options, ...), ...
{
...
}
...
}
| Because the config is modified during the lifetime of the stream. Already in the stream constructor you have:
parameters_.config.rtp.max_packet_size =
std::min<size_t>(parameters_.config.rtp.max_packet_size, kVideoMtu);
And in SetSendParameters, for example:
parameters_.config.rtp.rtcp_mode = *params.rtcp_mode;
When a class "owns" the data, it is a usual pattern to pass it by value and initialize the member with std::move. This is sometimes referred to as sink argument.
EDIT
Sorry, I missed the part that VideoOptions is also stored by value and is also modified in SetVideoSend():
parameters_.options.SetAll(*options);
With that, another explanation why Config is being moved, is that Config is intended to be mostly move-only type. Its assign operator is deleted, copy constructor is private and Copy() function commented with:
Mostly used by tests. Avoid creating copies if you can.
Why is that? Can't really tell for sure. It was changed in cc168360f413 as part of Issue 5687: Refactor Encoder - MediaTransport layer to use rtc::VideoSink/Source interface.
|
70,120,176 | 70,122,584 | Weird character when displaying data from .dat file in c++ | I have an ipk.dat file containing student name and their GPA separated by semicolon. I'm trying to display the names of students who have a GPA greater than 3, but I get output with strange characters like this in the console.
Hidayat Sari 3.60
Susila Buana 3.27
Krisna Sari 3.66
Taufik Fatimah 3.38
Bachtiar Darma 3.70
Yohanes Anwar 3.93
Harun Ratna 3.48
Mega Zulfikar 3.32
Zulfikar Abdul 3.50
Rahman Nirmala 3.37
Amir Cinta 3.30
Firdaus Latifah 3.16
Annisa Ali 3.65
Eka Yuliana 3.14
This is my code:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main() {
ifstream inGPA;
string studentGPA;
string studentName;
inGPA.open("ipk.dat");
if (inGPA.is_open()) {
string line;
while (getline(inGPA, line)) {
stringstream ss(line);
getline(ss, studentName, ';');
getline(ss, studentGPA);
if ( stod(studentGPA) >= 3.0) {
cout << studentName << " \t" << studentGPA << endl;
}
}
}
return 0;
}
And this is the inside of the ipk.dat file.The encoding for this file is UTF-8.
How do i fix this weird character issue?
| The non-breaking space might be unwanted input, but if you have names with non-ASCII characters, you will have the same problem.
Part of the problem here is that your terminal doesn't know that you are sending UTF-8 encoded characters.
If you are on Windows you can refer to this question.
The basic idea is to set the terminal to understand UTF-8 first:
#include <Windows.h>
int main() {
SetConsoleOutputCP(CP_UTF8); // set output to UTF-8
// your code
}
This will print your non-breaking space characters normally.
Note: This change doesn't only last for the execution of your program.
If you run your unfixed program after your fixed one, the program will seemingly work, until you run it in a fresh terminal.
|
70,120,733 | 70,121,052 | Show error in function if some other function has not run before it | I have two functions in C library that I am making.
One is a setup function, other is a function that does some operations. I want the second operations function to print an error if the setup function has not run before it.
What would be the best way to do this?
Here is what I have in my mind, but I am not sure if that is how it is done.
The setup function:
void setup_function()
{
#ifndef FUNCTION_SETUP
#define FUNCTION_SETUP
a_init();
b_init();
c_init();
#endif
}
And the operations function:
bool operations()
{
#ifdef FUNCTION_SETUP
try
{
/* My code */
return true;
}
catch (...)
{
Serial.println("Error in operations");
return false;
}
#elif Serial.println("Function not setup. Please use setup_function() in void setup()");
#endif
}
| #ifndef only checks whether this function was defined somewhere for the compiler and won't affect runtime.
best way to do this is through use of a global variable that changes value once the setup function is executed. if you're defining these functions in classes you could use static data member and setup function
|
70,121,308 | 70,124,647 | Sending msg from RSU to vehicles in veins | I'm trying to implement a small example in veins: the RSU broadcasts its own ID and other information, and the vehicle receives the RSU'S ID and records it.
I have created a new msg file named BeaconRSU.msg, and the application layer's cc files of RSU and vehicle are shown below:
//MyVeinsAppRSU.cc
#include "veins/modules/application/traci/MyVeinsAppRSU.h"
#include "veins/modules/application/traci/BeaconRSU_m.h"
using namespace veins;
Define_Module(veins::MyVeinsAppRSU);
void MyVeinsAppRSU::initialize(int stage)
{
DemoBaseApplLayer::initialize(stage);
if (stage == 0) {
sendBeacon= new cMessage("send Beacon");
EV << "Initializing " << par("appName").stringValue() << std::endl;
}
else if (stage == 1) {
// Initializing members that require initialized other modules goes here
if (sendBeacon->isScheduled())
{
cancelEvent(sendBeacon);
}
scheduleAt(simTime()+5,sendBeacon);
}
}
void MyVeinsAppRSU::handleSelfMsg(cMessage* msg)
{
if (msg == sendBeacon){
BeaconRSU* rsuBeacon = new BeaconRSU();
rsuBeacon->setRSUId(this->getParentModule()->getIndex());
rsuBeacon->setMyDemoData("RSU message!!");
BaseFrame1609_4* WSM = new BaseFrame1609_4();
WSM->encapsulate(rsuBeacon);
populateWSM(WSM);
send(WSM,lowerLayerOut);
EV << "rsu send success" <<endl;
if (simTime() < 2000) {
scheduleAt(simTime()+1,sendBeacon);
}
return;
}
}
//MyVeinsAppCar.cc
#include "veins/modules/application/traci/MyVeinsAppCar.h"
#include "veins/modules/application/traci/BeaconRSU_m.h"
#include "veins/modules/application/traci/MyVeinsAppRSU.h"
using namespace veins;
Define_Module(veins::MyVeinsAppCar);
void MyVeinsAppCar::initialize(int stage)
{
DemoBaseApplLayer::initialize(stage);
if (stage == 0) {
// Initializing members and pointers of your application goes here
EV << "Initializing " << par("appName").stringValue() << std::endl;
int a = INT_MIN;
}
else if (stage == 1) {
// Initializing members that require initialized other modules goes here
RSUIndex.setName("test");
int a= INT_MIN;
EV << "MyVeinsAppCar is initializing" << std::endl;
}
}
void MyVeinsAppCar::handleLowerMsg(cMessage* msg)
{
BaseFrame1609_4* WSM = check_and_cast<BaseFrame1609_4*>(msg);
cPacket* enc = WSM->getEncapsulatedPacket();
BeaconRSU* bc = dynamic_cast<BeaconRSU*>(enc);
EV << "receive message !!!" << endl;
if(a!=bc->getRSUId())
{
RSUIndex.record(bc->getRSUId());
a=bc->getRSUId();
}
EV << "my message = " <<bc->getMyDemoData()<<endl;
EV <<"send message RSU id:" <<bc->getRSUId() << " Receive successfully !!!!!!!!!!!" << endl; }
When I run the simulation, I can see the msg sent from RSU successfully, but nodes cannot receive the msg (The contents in MyVeinsAppCar::handleLowerMsg(cMessage* msg) are not printed out).
And there some error in log:
enter image description here
Why did this happen? Is someone help me? Thank you in advance!
//BeaconRSU.msg
cplusplus{{
#import "veins/base/utils/Coord.h"
#import "veins/modules/utility/Consts80211p.h"
#include "veins/modules/messages/BaseFrame1609_4_m.h"
#include "veins/base/utils/SimpleAddress.h"
}};
namespace veins;
// TODO generated message class
class noncobject Coord;
class BaseFrame1609_4;
packet BeaconRSU extends BaseFrame1609_4
{
//id of the originator
int RSUId = 0;
Coord position[100];
double beaconrate[100];
string myDemoData;
Coord slotpos;
simtime_t timestamp=0;
}
Part of the debug mode log is shown below:
| You seem to be running your simulation in "release" mode, not "debug" mode. While this will let your simulation run much faster, it omits a lot of sanity checks and prints only minimal information about what is happening in your simulation. For all of these reasons, it is highly recommended to only run a simulation in "release" mode after it is completely finished.
For information on how to run a simulation in debug mode, see the Veins FAQ entry "How can I debug my OMNeT++ simulation models? How do I create a stack trace?" at http://veins.car2x.org/documentation/faq/
When running your simulation in debug mode, you should see a lot more log information that explains what is going on in the simulation. For example, the log output might look like this:
** Event #100 t=1 ...nic.phy80211p (PhyLayer80211p, id=1) on selfmsg (veins::AirFrame11p, id=1)
TRACE (PhyLayer80211p)...nic.phy80211p: Processing AirFrame...
TRACE (PhyLayer80211p)...nic.phy80211p: Packet has bit Errors. Lost
TRACE (PhyLayer80211p)...nic.phy80211p: packet was not received correctly, sending it as control message to upper layer
TRACE (PhyLayer80211p)...nic.phy80211p: Channel idle now!
TRACE (PhyLayer80211p)...nic.phy80211p: End of Airframe with ID 6.
** Event #101 t=2 ...nic.mac1609_4 (Mac1609_4, id=2) on Error (omnetpp::cMessage, id=1)
TRACE (Mac1609_4)RSUExampleScenario.node[27].nic.mac1609_4: A packet was not received due to biterrors
In this example, the debug message Packet has bit Errors. Lost (see https://github.com/sommer/veins/blob/veins-5.1/src/veins/modules/phy/Decider80211p.cc#L151) will tell you that decoding was attempted (that is, the signal was strong enough to be detected by the receiver), but decoding failed. The Phy layer model you are employing bases the decision whether a transmission is received okay on the SINR (the ratio of signal power to interference and noise power) (see https://github.com/sommer/veins/blob/veins-5.1/src/veins/modules/phy/Decider80211p.cc#L142) so this can have any one of two reasons: the signal might have been to weak (low transmission power, sender too far away) or interfering signals might have been too strong (somebody else was sending at the same time). If you are interested in which of the two was the case you can enable the parameter collectCollisionStatistics (see https://github.com/sommer/veins/blob/veins-5.1/src/veins/modules/phy/PhyLayer80211p.ned#L43) of the phy80211p module of a NIC. Instead of just Packet has bit Errors you will then see either Packet has bit Errors due to low power or Packet has bit Errors due to collision.
|
70,121,565 | 70,121,652 | Pointer to const object with emplace_back | I don't understand when we can use const variables/objects in collections (particularly with emplace). The below code works with const objects directly but not when using pointers to const objects.
#include <list>
class MyData { };
int main() {
std::list<std::pair<int, MyData>> collection1{};
std::list<std::pair<int, MyData*>> collection2{};
const MyData someData{};
const MyData* someDataPtr = &someData;
collection1.emplace_back(1, someData);
//collection2.emplace_back(1, someDataPtr); //Messy template error!
}
I assume there's not much advantage to using emplace_back over push_back for pointers, but I'm using std::pair to illustrate that the other part of the pair could be something big/costly.
Specifically, my question is why does emplace_back work with a const object but not a pointer to a const object? Is there a reasonable way to achieve the latter?
For anyone wondering about the use-case, I have a member function which is passed the constituents of the pair, does some processing (but should not change any data) and then emplaces the pair to the collection. Something like:
void add_to_schedule(const int id, const MyData* myData) {
//some processing
this->collection.emplace_back(id, myData);
}
| const MyData* can't be converted to MyData* implicitly. That means std::pair<int, MyData*> can't be constructed from {1, someDataPtr} while someDataPtr is a const MyData*.
Under the same logic,
MyData* p = someDataPtr; // fails
MyData m = someData; // fine
As the workaround, you can change someDataPtr to MyData*, or change the std::list to std::list<std::pair<int, const MyData*>>.
|
70,122,041 | 70,122,352 | Check if a struct is empty | I have an old piece of code with a big struct that looks like this:
typedef struct {
long test1;
char test2[10]
…
} teststruct;
This struct gets initialized like this:
memset(teststruct, 0, sizeof(teststruct0));
I must not change this code in any way. How do I efficiently check if the struct is empty, or has been modified after the memset()?
| It sounds like what you want is to find out if this struct has any non-zero values. As you can see in the comments, there are a couple exceptions you may want to consider, but for the simple solution we can copy this previous answer.
// Checks if all bytes in a teststruct are zero
bool is_empty(teststruct *data) {
unsigned char *mm = (unsigned char*) data;
return (*mm == 0) && memcmp(mm, mm + 1, sizeof(teststruct) - 1) == 0;
}
|
70,122,232 | 70,123,194 | Change the display of integer output | I am trying to create a maze and robot with vector of vector. However, I also want to use bool to display the wall so the robot cannot walk through it. And my vector display with 0 and 1 only.
I want to change from 0 to . without using char or changing any element in vector to another type. I remember there is a guy who changed it with ASCII and using library windown.h but I can't remember how to do it. Can anyone help?
000000000000
000000000000
000000000000
Should be
............
............
............
| If you gave us some more context it would be easier for us to help you, but in theory you should be able to display a '.' or ' ' character conditionally based on the boolean value. For instance, if the bool you want to print is in the variable cellIsWall then printing the expression (cellIsWall ? '.' : ' ') will print a dot if the value is true and a space if the value is empty.
Of course, this assumes you are using printf or std::cout or a similar function for printing your maze, if you are using an internal Windows API function which accepts an array of bools then you will need to give us more information.
|
70,122,423 | 70,122,447 | what is `typename...` syntax in C++ template? | Just found this piece of code in a Program(C++) file:
template <typename blah, typename... Args>
const <some-type> bof(<some-parameters>, Args&&... args) const
{
return breck(std::forward<Args>(args)...);
}
I am wondering:
what is the three dots after the typename?
Intuitively looks like in this way we can pass multiple arguments? Looking for some official term/reference for it?
| It is called parameter pack, you can read more here: https://en.cppreference.com/w/cpp/language/parameter_pack
Indeed, you can use Args... for unpacking multiple arguments in function or class templates, when you don't know ahead of time how many templated parameters there is going to be.
|
70,122,761 | 70,124,133 | Catch2 compile error (no such file or directory) | I've already used Catch2 for testing sucessfully, but this time a problem occurred. I am pushing Catch2 submodule to me project (this is not a -v2.x branch) and include "../Catch2/src/catch2/catch_all.hpp" to my test files. The problem is that in catch_all.hpp all of the included .hpp files (like <catch2/benchmark/catch_benchmark_all.hpp>, <catch2/catch_approx.hpp> and so on) are not found. I've checked paths but they seem to be fine. Any ideas what is wrong with it?
Here's an example of my code.
I am adding a Catch2 submodule with command
git submodule add https://github.com/catchorg/Catch2.git
CMakeFile.txt:
cmake_minimum_required(VERSION 3.20)
project(proj)
set(CMAKE_CXX_STANDARD 17)
set (sources
./main.cpp
./test_main.cpp
./test.cpp)
add_executable(mainApp ${sources})
target_compile_options(mainApp PRIVATE -Wall -pedantic -std=c++17)
target_link_libraries(mainApp)
set (tests
./test_main.cpp
./test.cpp)
add_subdirectory(Catch2)
add_executable(runTests ${tests})
target_compile_options(mainApp PRIVATE -g)
target_link_libraries(runTests PRIVATE Catch2::Catch2WithMain)
test_main.cpp:
#define CATCH_CONFIG_MAIN
#include"Catch2/src/catch2/catch_all.hpp"
test.cpp:
#include"Catch2/src/catch2/catch_all.hpp"
TEST_CASE("BasicTest_1", "FirstTest") {
REQUIRE(1 == 1);
}
main.cpp is just a simple helloworld for now.
TEST_CASE doesn't work either, it says "C++ requires a type specifier for all declarations".
| You are including test_main.cpp and test.cpp in mainApp.
Which means that files in mainApp try to #include"Catch2/src/catch2/catch_all.hpp" without linking to the Catch2 library and includes.
Remove the test files from the mainApp sources and try again.
|
70,122,920 | 70,123,113 | Maximum allowed value of the precision format specifier in the {fmt} library | Consider the following snippet1 (which is testable here):
#include <fmt/core.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
// Let's see how many digits we can print
void test(auto value, char const* fmt_str, auto std_manip, int precision)
{
std::ostringstream oss;
oss << std_manip << std::setprecision(precision) << value;
auto const std_out { oss.str() };
auto const fmt_out { fmt::format(fmt_str, value, precision) };
std::cout << std_out.size() << '\n' << std_out << '\n'
<< fmt_out.size() << '\n' << fmt_out << '\n';
}
int main()
{
auto const precision{ 1074 };
auto const denorm_min{ -0x0.0000000000001p-1022 };
// This is fine
test(denorm_min, "{:.{}g}", std::defaultfloat, precision);
// Here {fmt} stops at 770 chars
test(denorm_min, "{:.{}f}", std::fixed, precision);
}
According to the {fmt} library's documentation:
The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating-point value formatted with 'f' and 'F', or before and after the decimal point for a floating-point value formatted with 'g' or 'G'.
Is there a limit to this value?
In the corner case I've posted, std::setprecision seems to be able to output all of the
requested digits, while {fmt} seems to stop at 770 (a "reasonably" big enough value in most cases, to be fair). Is there a parameter we can set to modify this limit?
EDIT
I reported the issue to the library mantainers and it appears to have been fixed, now.
(1) If you are wondering where those particular values come from, I was playing with this Q&A:
What is the maximum length in chars needed to represent any double value?
| You're not far off, there is a hardcoded limit of 767 in the format-inl.h file (see here):
// Limit precision to the maximum possible number of significant digits in
// an IEEE754 double because we don't need to generate zeros.
const int max_double_digits = 767;
if (precision > max_double_digits) precision = max_double_digits;
|
70,123,352 | 70,123,454 | c++ Using class member as a parameter in constructor | I have a class where I need to use one of the members as a constructor parameter to initialize another const member of the same class.
class A
{
private:
M1Type m1;
const M2Type m2;
public:
A(x) : m1(x), m2(m1){}
};
is this a correct way to initialize m2? m1's construction is complete in the list initialization?
Update:
Sorry I missed the type for x (was more of a pseudocode). Assume any primitive type.
| Yes, "m1's construction is complete" when it's used to initialize m2 and if an M2Type can be constructed from an M1Type, this is fine - but x needs a type in A(x).
The order of initialization is the order in which you've defined the member variables in the class, not the order in which you use them in the member initializer list:
M1Type m1;
const M2Type m2;
A(M1Type x) : m2(m1), m1(x) {} // wrong order, but still ok
If the type of x can be used to construct both an M1Type and an M2Type and get the same result as if you construct an M2Type with an M1Type constructed from x, you might as well use x to construct both to not risk problems if you reorganize the member variables later on. That's not always possible though.
Example:
struct M1Type {
explicit M1Type(double) {};
};
struct M2Type {
explicit M2Type(M1Type) {}
};
class A {
public:
M1Type m1;
const M2Type m2;
public:
// error: no matching function for call to 'M2Type::M2Type(double&)':
// A(double x) : m1(x), m2(x) {}
A(double x) : m1(x), m2(m1) {} // OK
};
|
70,123,558 | 70,123,745 | How to convert unsigned char to unsigned int in c++? | I have the following piece of code:
const unsigned char *a = (const unsigned char *) input_items;
input_items is basically the contents of a binary file.
Now a[0] = 7, and i want to convert this value to unsigned int. But when I do the following:
unsigned int b = (unsigned int) a[0];
and print both of these values, I get:
a[0] = 7
b = 55
Why does b not contain 7 as well? How do I get b = 7?
| I think I see the problem now: You print the value of the character as a character:
unsigned char a = '7';
std::cout << a << '\n';
That will print the character '7', with the ASCII value 55.
If you want to get the corresponding integer value for the digit character, you can rely on that all digit characters must be consecutively encoded, starting with zero and ending with nine. Which means you can subtract '0' from any digit character to get its integer value:
unsigned char a = '7';
unsigned int b = a - '0';
Now b will be equal to the integer value 7.
|
70,123,672 | 70,123,981 | Optimize estimating Pi function C++ | I've wrote a program, that approximates Pi using the Monte-Carlo method. It is working fine, but I wonder if I can make it work better and faster, because when inserting something like ~n = 100000000 and bigger from that point, it takes some time to do the calculations and print the result.
I've imagined how I could try to approximate it better by doing a median for n results, but considering how slow my algorithm is for big numbers, I decided not doing so.
Basically, the question is: How can I make this function work faster?
Here is the code that I've got so far:
double estimate_pi(double n)
{
int i;
double x,y, distance;
srand( (unsigned)time(0));
double num_point_circle = 0;
double num_point_total = 0;
double final;
for (i=0; i<n; i++)
{
x = (double)rand()/RAND_MAX;
y = (double)rand()/RAND_MAX;
distance = sqrt(x*x + y*y);
if (distance <= 1)
{
num_point_circle+=1;
}
num_point_total+=1;
}
final = ((4 * num_point_circle) / num_point_total);
return final;
}
| An obvious (small) speedup is to get rid of the square root operation.
sqrt(x*x + y*y) is exactly smaller than 1, when x*x + y*y is also smaller than 1.
So you can just write:
double distance2 = x*x + y*y;
if (distance2 <= 1) {
...
}
That might gain something, as computing the square root is an expensive operation, and takes much more time (~4-20 times slower than one addition, depending on CPU, architecture, optimization level, ...).
You should also use integer values for variables where you count, like num_point_circle, n and num_point_total. Use int, long or long long for them.
The Monte Carlo algorithm is also embarrassingly parallel. So an idea to speed it up would be to run the algorithm with multiple threads, each one processes a fraction of n, and then at the end sum up the number of points that are inside the circle.
Additionally you could try to improve the speed with SIMD instructions.
And as last, there are much more efficient ways of computing Pi.
With the Monte Carlo method you can do millions of iterations, and only receive an accuracy of a couple of digits. With better algorithms its possible to compute thousands, millions or billions of digits.
E.g. you could read up on the on the website https://www.i4cy.com/pi/
|
70,123,742 | 70,123,780 | My Quicksort does not sort the input array | I tried to write quicksort by myself and faced with problem that my algorithm doesn't work.
This is my code:
#include <iostream>
#include <vector>
using namespace std;
void swap(int a, int b)
{
int tmp = a;
a = b;
b = tmp;
}
void qsort(vector <int> a, int first, int last)
{
int f = first, l = last;
int mid = a[(f + l) / 2];
do {
while (a[f] < mid) {
f++;
}
while (a[l] > mid) {
l--;
}
if (f <= l) {
swap(a[f], a[l]);
f++;
l--;
}
} while (f < l);
if (first < l) {
qsort(a, first, l);
}
if (f < last) {
qsort(a, f, last);
}
}
int main()
{
int n;
cin >> n;
vector <int> a;
a.resize(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
qsort(a, 0, n - 1);
for (int i = 0; i < n; i++) {
cout << a[i] << ' ';
}
return 0;
}
My sort is similar to other that described on the Internet and I can't find where I made a mistake.
Even when I change sort function, the problem was not solved.
| You don't pass qsort the array you want to sort, you pass it the value of that array. It modifies the value that was passed to it, but that has no effect on the array.
Imagine if you had this code:
void foo(int a)
{
a = a + 1;
}
Do you think if I call this like this foo(4); that foo is somehow going to turn that 4 into a 5? No. It's going to take the value 4 and turn it into the value 5 and then throw it away, since I didn't do anything with the modified value. Similarly:
int f = 4;
foo(f);
This will pass the value 4 to foo, which will increment it and then throw the incremented value away. The value f has after this will still be 4 since nothing ever changed f.
You meant this:
void qsort(vector <int>& a, int first, int last)
Your swap has the same problem. It swaps the values of a and b, but then never does anything with the value of a or b. So it has no effect. How could it? Would swap(3, 4); somehow change that 3 into a 4 and vice-versa? What would that even mean?
|
70,124,023 | 70,124,056 | In C++, is it good to pass a const long double by reference? | I am facing my colleague writing a function definition like this:
typedef long double Real;
void func(const Real& x, const Real &y);
I know it is somewhat bad to use pass-by-ref for primitive types, but what about long double? Its length is 80 bits, longer than a pointer of 64 bits on a regular machine nowadays. So maybe for long double, pass-by-ref is more efficient than pass-by-value?
| I'm hoping that your colleague has written it for another reason, that being that it stops any implicit conversions being made at the function calling site. It also prevents the parameter from being modified in the function body, which can help in the attainment of program stability, but that can be achieved by passing by const value.
Sometimes the overload resolution mechanism can be harmful, especially when introducing new overloads.
If it's there as a micro-optimisation strategy then that's a silly thing to do. If you can micro-optimise then so can the compiler. And writing typedef long double Real; is sillier still as (i) you've exchanged a standard term for a proprietary one and, (ii) Real implies there are no gaps in the representable numbers which we know is not the case. If a compiler with optimisations turned up to maximum produces code that runs faster if the long doubles are passed by reference, then consider switching your toolchain.
(I have worked with a 128 bit long double and always pass it by value.)
|
70,124,226 | 70,124,387 | Reference list element then popping it, is it undefined behaviour? | I have this piece of code and I wonder if it is valid or can cause undefined behaviour:
#include <list>
#include <utility>
void myFunction(std::list<std::pair<int, int>> foo)
{
while (foo.size())
{
std::pair<int, int> const &bar = foo.front();
//work with bar
foo.pop_front();
}
}
I am using a reference to avoid duplicating the already existing pair.
On one side, I think this could be an undefined behaviour because I am removing a referenced element but, on the other side, I am not accessing the reference after removing it.
Is it valid?
| So long as you don't attempt to use the bar reference after the foo.pop_front(); statement, then you won't get undefined behaviour, because that reference remains valid until the referred-to element is removed from the container.
In your case, the pop appears to be the very last statement in the scope of the reference (a new one will be created/formed on each iteration of the while loop), so that doesn't appear to be an issue.
|
70,125,011 | 70,125,077 | Error: terminate called after throwing an instance of 'std::out_of_range | When I typed this code
#include <iostream>
#include <string>
class binary
{
std::string s;
public:
void read();
void check_format();
};
void binary::read()
{
std::cout << "Enter a number\n";
std::cin >> s;
}
void binary ::check_format()
{
for (int i = 1; i <= s.length(); i++)
{
if (s.at(i) != '0' && s.at(i) != '1')
{
std::cout << "Incorrect format\n";
exit(0);
}
}
};
int main()
{
binary num;
num.read();
num.check_format();
return 0;
}
I was getting the correct output for the oneswith no '1' and '0' in them like 44, but for the numbers with '1' and '0' in them I got this error
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at: __n (which is 2) >= this->size() (which is 2)
Please help in fixing this.
| C++ strings indexes are zero-based. That means if a string has a size of n. its indexes are from 0 to n - 1.
For example:
#include <iostream>
#include <string>
int main()
{
std::string s {"Hello World!"} // s has a size of 12.
std::cout << s.size() << '\n'; // as shown
std::cout << s.at(0); << '\n' // print the first character, 'H'
std::cout << s.at(11); << '\n' // print the last character, '!'
}
But you are looping from 1 to n. When i == n, s.at(i) become out-of-bounds, and because of that, it throws an std::out_of_range error
Change your loop to:
void binary::check_format()
{
for (int i = 0; i < s.length(); i++)
{
if (s[i] != '0' && s[i] != '1') // at() does bounds checking, [] is faster
{
std::cout << "Incorrect format\n";
exit(0);
}
}
}
Or better:
void binary::check_format()
{
for(const auto &i : s)
{
if (i != '0' && i != '1')
{
std::cout << "Incorrect format\n";
exit(0);
}
}
}
|
70,125,640 | 70,125,752 | Why does a for loop invoke a warning when using identical code? | I think that following two codes are identical. but upper one has C4715 "not all control paths return a value" problem and other doesn't.
Why this warning happens?
int func(int n){
for(int i=0; i<1; i++){
if(n == 0){
return 0;
}
else {
return -1;
}
}
}
int func(int n){
if(n == 0){
return 0;
}
else {
return -1;
}
}
| The compiler is trying to be helpful, and failing. Pretend for a moment that the code inside the loop was just if (n == 0) return 0;. Clearly, when n is not 0, the loop will execute once and then execution will move on to the next statement after the loop. There's no return statement there, and that's what the compiler is warning you about. It just isn't smart enough to see that the code inside the loop always returns.
So, possibly, add a return 0; statement after the loop. That might make the compiler happy. But it also might make the compiler (or some other compiler) give a different warning about "unreachable code", because that new return statement can't actually be reached. This stuff is hard to analyze, and compilers often get it wrong.
|
70,125,684 | 70,125,887 | Static_cast and templated conversion function | I have a class that wraps some type and attaches a Dimension. It should be convertible to the underlying type, but only if Dim=0. The conversion operator should not be callable in other cases (so a static_assert in the function would not work for me).
The following code works, if the enable_if-construction is deleted, but not in this form.
template<class T, int Dim>
class Unit {
public:
explicit Unit(T const& value): _value(value) {}
template<int D = Dim, typename = typename std::enable_if<D == 0>::type>
operator T() { return _value; }
private:
T _value;
};
auto main() -> int
{
auto a = double{0};
auto u = Unit<double, 0>{a};
auto i = static_cast<int>(u);
return i;
}
What is the reason for this and is there a work around to allow the cast, but also restrict the conversion?
| As I understand, you want:
template <class T, int Dim>
class Unit {
public:
explicit Unit(T const& value): _value(value) {}
template <typename U, int D = Dim,
std::enable_if_t<D == 0 && std::is_convertible_v<T, U>, int> = 0>
operator U() { return _value; }
private:
T _value;
};
Demo
And in C++20, look nicer
template<class T, int Dim>
class Unit {
public:
explicit Unit(T const& value): _value(value) {}
template <typename U>
requires(Dim == 0 && std::is_convertible_v<T, U>)
operator U() const { return _value; }
private:
T _value;
};
Demo
|
70,125,891 | 70,125,948 | prevent multi-thread application from termination when one of its thread performs an illegal operation | Is it possible to prevent a multi-thread application from getting terminated when one of its thread performs an illegal operation like integer divide by zero operation. This is a sample code:
#include <iostream>
#include <thread>
#include <chrono>
void thread1() {
std::this_thread::sleep_for(std::chrono::seconds(2));
for (int i = 3; i >= 0; --i)
std::cout << (3 / i) << std::endl;
std::cout << "thread end" << std::endl;
}
int main() {
std::thread t(thread1);
t.detach();
std::cout << "before sleep\n";
std::this_thread::sleep_for(std::chrono::seconds(5));
//t.join();
std::cout << "after sleep\n";
}
In the above code I'm trying a integer divide by zero operation in a thread which is causing the whole program from getting terminated.
| No, in general that isn't possible; all threads in a process share the same memory space, which means that a fatal error in any one thread might have corrupted the data structures of anything else in the process, therefore the whole process is terminated.
If you really need your program to be able to survive a fatal error, then the problematic code needs to be executed inside a separate child process, so that when it crashes, the parent process can survive (and maybe re-launch a new child process, or whatever is appropriate). But in general the preferred approach is simply to make sure that your code doesn't contain any bugs that would lead to crashes.
|
70,126,043 | 70,126,400 | Writing results to multiple txt files in C++ | I have the following code:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream os;
char fileName[] = "0.txt";
for(int i = '1'; i <= '5'; i++)
{
fileName[0] = i;
os.open(fileName);
os << "Hello" << "\n";
os.close();
}
return 0;
}
The aim is to write my code output into multiple .txt files up to, say 64 different times. When I change this loop to run more than 10, that is
for(int i = '1'; i <= '10'; i++)
I get the following error:
warning: character constant too long for its type
Any ideas how to write to more than 10 files? Moreover, how do I write a number after each "Hello", e.g. "Hello1 ... Hello10"?
Cheers.
| I believe the reason you receive that warning is because you're attempting to assign two chars into one slot of the char array:
fileName[0] = i;
because when i = 10;, it's no longer a single character.
#include <fstream>
#include <iostream>
#include <string>//I included string so that we can use std::to_string
using namespace std;
int main() {
ofstream os;
string filename;//instead of using a char array, we'll use a string
for (int i = 1; i <= 10; i++)
{
filename = to_string(i) + ".txt";//now, for each i value, we can represent a unique filename
os.open(filename);
os << "Hello" << std::to_string(i) << "\n";//as for writing a number that differs in each file, we can simply convert i to a string
os.close();
}
return 0;
}
Hopefully this resolved the issues in a manner that you're satisfied with; let me know if you need any further clarification! (:
|
70,126,065 | 70,127,088 | C++ OOP Abstract Class - Access violation writing location | I have an UserAcount class that has an abstract class ContBancar, and other class Banca which reads some users from a file (with method void Banca::citire_conturi()). When it reads the users, I get an error "Access violation writing location" in ContBancar at void setBal(double bal) { _balanta = bal; }. Thx for help !
PS : The file has only one line : 1CBS Dragos 0 dragos12! Gzpvia01= .
Also, i want to make a bank account system, with an user class that has an bank account class which inherits 3 types of a bank accounts, and a bank class which reads some users from a file or put them on it.
class UserAccount
{
private:
std::string _nume, _user, _pass;
std::string _cod_us;
std::shared_ptr <ContBancar> _cont;
public:
void setUser(std::string user) { _user = user; }
void setPass(std::string pass) { _pass = pass; }
void setNume(std::string nume) { _nume = nume; }
void setCodUs(std::string cod) { _cod_us = cod; }
void setContBal(double balanta) { (*_cont).setBal(balanta); }
std::string getUser() const { return _user; }
std::string getPass() const { return _pass; }
std::string getNume() const { return _nume; }
std::string getCodUs() const { return _cod_us; }
double getContBal() const { return (*_cont).getBal(); }
void setContBancar();
};
void UserAccount::setContBancar()
{
if (_cod_us == "1CBS")
_cont.reset(new ContBancarSilver());
else if (_cod_us == "2CBG")
_cont.reset(new ContBancarGold());
else
_cont.reset(new ContBancarDiamond());
}
class ContBancar
{
protected:
double _balanta;
public:
void setBal(double bal) { _balanta = bal; }
double getBal() { return _balanta; }
virtual bool depozitare(unsigned int) = 0;
virtual bool retragere(unsigned int) = 0;
};
class Banca
{
private:
std::vector<UserAccount> vec;
public:
void citire_conturi();
};
void Banca::citire_conturi()
{
std::ifstream file;
file.open("Baza_Date.txt");
UserAccount temp;
std::string cod, nume, user, pass;
double balanta;
while (file >> cod >> nume >> balanta >> user >> pass)
{
temp.setCodUs(cod);
temp.setNume(nume);
temp.setContBal(balanta);
temp.setUser(user);
temp.setPass(pass);
vec.push_back(temp);
}
file.close();
}
class ContBancarSilver : public ContBancar
{
private:
static constexpr unsigned int max_balanta = 5000;
static constexpr unsigned int max_depozitare = 2500;
static constexpr unsigned int max_retragere = 1000;
static constexpr double tax_retragere = 0.08;
static constexpr double bonus_depunere = 0.03;
static constexpr double bonus_tax_retragere = 0.05;
static constexpr unsigned int max_depozitari = 1;
static constexpr unsigned int max_retrageri = 1;
public:
virtual bool depozitare(unsigned int) override;
virtual bool retragere(unsigned int) override;
};
| Based on available informationyou should fix your code like this:
class UserAccount
{
.....
void setCodUs(std::string cod) {
_cod_us = cod;
setContBancar();
}
void setContBal(double balanta) {
if (!_cont) setContBancar(); // lazy initialization
_cont->setBal(balanta);
}
...
};
void UserAccount::setContBancar()
{
if (_cod_us == "1CBS")
_cont = std::make_shared<ContBancarSilver>();
else if (_cod_us == "2CBG")
_cont = std::make_shared<ContBancarGold>();
else
_cont = std::make_shared<ContBancarDiamond>();
}
Note I do not understand what kind of logic you are implementing. This changes just ensured that _cont is initialized and up to date with _cod_us.
Please stop use explicitly new and delete. Everything can be created by std::make_shared and std::make_unique and containers like std::vector.
|
70,126,172 | 70,127,386 | Translating a function from Python to C++ | Im struggling with a certain function in Python, it's nothing complicated but i need to "translate" it to C++ with very limited prior knowledge.
def BuildCommandList(commands : list, filepath : str):
commands.clear()
try:
file = open(filepath, 'r')
except FileNotFoundError:
return False
for line in file:
line = line.replace('\n','')
if len(line) != 0:
line = line.split()
commands.append(line)
file.close()
return True
Above is the function in Python, below is my current attempt at the same thing in C++
bool BuildCommandList(std::vector<std::vector<std::string>>& commandList, std::string filepath)
{
std::ifstream test(filepath);
test.open(filepath);
if (test.is_open())
{
std::string line, text;
while (std::getline(test, line))
{
if (!line.empty() || line.find_first_not_of(' ') == std::string::npos)
{
text += line + "\n";
}
if (len(line) != 0); //Obviusly doesn't work
{
}
}
}
else
{
return false;
}
return true;
}
Any and all help is appreciated
| The natural equivalent to Python's len is std::size, or equivalently the size member of std::string. However you might prefer the empty member of std::string for your condition.
You then need to split your string. This can be done with a std::stringstream and std::istream_iterator to construct a std::vector<std::string> (overload 5) in place.
Note that getline doesn't include the \n, so you don't need to modify line before splitting it.
bool BuildCommandList(std::vector<std::vector<std::string>>& commandList, std::string filepath)
{
commandList.clear();
std::ifstream test(filepath);
if (!test)
{
return false;
}
for (std::string line; std::getline(test, line); )
{
if (!line.empty())
{
using iterator = std::istream_iterator<std::string>;
commandList.emplace_back(iterator{std::stringstream{line}}, iterator{});
}
}
return true;
}
|
70,126,319 | 70,126,600 | C++20 Member Initialization List Clang++ vs G++ | Currently using Clang++ 13.0.0 and GCC G++ 11.2.0.
The code below has been simplified for context. When I run the code using g++, it runs without any warnings or errors. When I run the code using Clang, I get the following error:
field 'cat' is uninitialized when used here [-Werror,-Wuninitialized]
Is there any way to resolve this?
Code:
struct Bar {
Object *ptr;
int y;
};
struct Foo {
Object *ptr;
Bar cat;
};
class Test {
Foo animal;
Test()
: animal{
generateObject(),
{
animal.ptr,
0
}
}
{}
};
| One possible approach:
class Test {
private:
explicit Test(Object* ptr)
: animal{ptr, {ptr, 0}} {}
public:
Test() : Test(generateObject()) {}
};
|
70,126,350 | 70,134,444 | OpenMP incredibly slow when another process is running | When trying to use OpenMP in a C++ application I ran into severe performance issues where the multi-threaded performance could be up to 1000x worse compared to single threaded. This only happens if at least one core is maxed out by another process.
After some digging I could isolate the issue to a small example, I hope someone can shed some light on this issue!
Minimal example
Here is a minimal example which illustrates the problem:
#include <iostream>
int main() {
int sum = 0;
for (size_t i = 0; i < 1000; i++) {
#pragma omp parallel for reduction(+:sum)
for (size_t j = 0; j < 100; j++) {
sum += i;
}
}
std::cout << "Sum was: " << sum << std::endl;
}
I need the OpenMP directive to be inside the outer for-loop since my real code is looping over timesteps which are dependent on one another.
My setup
I ran the example on Ubuntu 21.04 with an AMD Ryzen 9 5900X (12 cores, 24 threads), and compiled it with G++ 10.3.0 using g++ -fopenmp example.cc.
Benchmarking
If you run this program with nothing else in the background it terminates quickly:
> time ./a.out
Sum was: 999000
real 0m0,006s
user 0m0,098s
sys 0m0,000s
But if a single core is used by another process it runs incredibly slowly. In this case I ran stress -c 1 to simulate another process fully using a core in the background.
> time ./a.out
Sum was: 999000
real 0m8,060s
user 3m2,535s
sys 0m0,076s
This is a slowdown by 1300x. My machine has 24 parallel threads so the theoretical slowdown should only be around 4% when one is busy and 23 others are available.
Findings
The problem seems to be related to how OpenMP allocates/assigns the threads.
If I move the omp-directive to the outer loop the issue goes away
If I explicitly set the thread count to 23 the issue goes away (num_threads(23))
If I explicitly set the thread count to 24 the issue remains
How long it takes for the process to terminate varies from 1-8 seconds
The program constantly uses as much of the cpu as possible when it's running, I assume most of the OpenMP threads are in spinlocks
From these findings it would seem like OpenMP assigns the jobs to all cores, including the one that is already maxed out, and then somehow forcing each individual core to finish its tasks and not allowing them to be redistributed when other cores are done.
I have tried changing the scheduling to dynamic but that didn't help either.
I would be very helpful for any suggestions, I'm new to OpenMP so it's possible that I've made a mistake. What do you make of this?
| So here is what I could figure out:
Run the program with OMP_DISPLAY_ENV=verbose (see https://www.openmp.org/spec-html/5.0/openmpch6.html for a list of environment variables)
The verbose setting will show you OMP_WAIT_POLICY = 'PASSIVE' and GOMP_SPINCOUNT = '300000'. In other words, when a thread has to wait, it will spin for some time before going to sleep, consuming CPU time and blocking one CPU. This will happen each time the thread reaches the end of the loop or before the the master thread distributes the for loop, or maybe even before the parallel section starts.
Because GCC's libgomp does not use pthread_yield, this effectively blocks one CPU thread. Because you have more running software threads than CPU threads, one will not be running, causing all others to busy-wait until the kernel scheduler reassigns the CPU.
If you call your program with OMP_WAIT_POLICY=passive, GCC will set GOMP_SPINCOUNT = '0'. Then the kernel will immediately put waiting threads to sleep and allow the others to run. Now your performance will be much better.
Interestingly enough OMP_PROC_BIND=true also helps. I assume immovable threads affect the kernel scheduler in some way that benefits us but I'm not sure.
Clang's OpenMP implementation does not suffer from this performance degradation because it uses pthread_yield. Of course this has its own drawbacks if syscall overhead is large and in most computing environments, it should be unnecessary because you are not supposed to overcommit CPUs.
|
70,126,417 | 70,130,563 | Z3: using comparison operators (<,<=,...) on z3::expr | I store numbers as z3::expr and want to compare them. I tried the following:
z3::context c;
z3::expr a = c.real_val("0");
z3::expr b = c.real_val("1");
z3::expr comp = (a < b);
std::cout << comp.is_bool() << std::endl;
std::cout << comp.bool_value() << std::endl;
I am a bit confused, why is comp.bool_value() false?
If I use a solver everything works as expected:
z3::solver s(c);
s.add(comp);
std::cout << s.check() << std::endl;
I have to compare z3::exprs relatively often, what would be the fasted method to do so? Using a solver seems to me like a lot of overhead.
| The < operator (and pretty much all other operators) simply pushes the decision to the solver: That is, it is a symbolic-expression that does not "evaluate" while it runs, but rather creates the expression that will do the comparison when the solver is invoked, over arbitrary expressions.
Having said that, you can use the simplifier to achieve what you want in certain cases. If you try:
z3::expr simpComp = comp.simplify();
std::cout << simpComp.bool_value() << std::endl;
you'll see that it'll print 1 for you. However, you shouldn't count on the simplifier to be able to reduce arbitrary expressions like this. For the simplest cases it'll do the job, but it'll give up if you have more complicated expressions.
In general, once you construct an expression you have to wait till the solver is called, and inspect the resulting model, if there is any.
Side note You can build your own functions to do some constant-folding yourself, in certain cases. This will be possible for Bool values, for instance (since they can be represented fully in C++), and bit-vectors of various sizes (upto your machine word-size), floats etc. But not for reals (because z3 reals are infinite precision, and you cannot represent those in C++ directly), and integers (because they're unbounded.) But this is not a trivial thing to do, and unless you're intimately familiar with the internals of z3, I'd recommend not going down that route.
Bottom line: If you have a lot of these sorts of constants folding around: See if you can re-architect your program so you don't create real_val in the first place; and keep them as constants, and only convert them to z3-expressions when you no longer can keep them as such. You can rely on simplify in certain cases, though don't expect it to be very performant either.
|
70,126,442 | 70,126,537 | Random syntax error on SQLite3 INSERT query | I'm doing an insertion query using SQLite3 with Spatialite on Qt and sometimes it just fails returning random syntax errors.
If I run the queries on SpatialiteGUI it never fails.
I'm using SQLite3 version 3.27.2.
The method that builds and runs the query:
bool DatabaseManager::insertPolygons(QList<QList<QGeoCoordinate>> polygons, int workId)
{
sqlite3_stmt *dbStatement = nullptr;
QString strQuery = "INSERT INTO \"WORK_" + QString::number(workId) + "\" (Geometry) VALUES ";
bool inserted = false;
for(int i = 0; i < polygons.size(); i++) {
strQuery += "(GeomFromText('POLYGON((";
foreach (QGeoCoordinate coordinate, polygons[i]) {
strQuery += QString::number(coordinate.longitude(), 'f', 10) + " " +
QString::number(coordinate.latitude(), 'f', 10) + ",";
}
strQuery = strQuery.left(strQuery.size() - 1) + "))', 4326)),";
}
strQuery = strQuery.left(strQuery.size() - 1) + ";";
char *query = strQuery.toLatin1().data();
int status = sqlite3_prepare_v2(database, query, strQuery.toLatin1().size(), &dbStatement, 0);
if(status == SQLITE_OK) {
int status = 0;
status = sqlite3_step(dbStatement);
if(status == SQLITE_DONE)
inserted = true;
}else
qDebug().noquote() << "status:" << status << "error:" << sqlite3_errmsg(database);
sqlite3_finalize(dbStatement);
return inserted;
}
Some queries examples:
INSERT INTO "WORK_264" (Geometry) VALUES
(GeomFromText('POLYGON((-52.3855298461 -28.2283621371,-52.3855220463 -28.2283563298,-52.3855103297 -28.2283685464,-52.3855181295 -28.2283743537,-52.3855298461 -28.2283621371))', 4326)),
(GeomFromText('POLYGON((-52.3855454459 -28.2283737516,-52.3855376460 -28.2283679443,-52.3855259294 -28.2283801609,-52.3855337292 -28.2283859682,-52.3855454459 -28.2283737516))', 4326)),
(GeomFromText('POLYGON((-52.3855610456 -28.2283853661,-52.3855532457 -28.2283795588,-52.3855415291 -28.2283917755,-52.3855493289 -28.2283975828,-52.3855610456 -28.2283853661))', 4326)),
(GeomFromText('POLYGON((-52.3855766453 -28.2283969805,-52.3855688455 -28.2283911733,-52.3855571288 -28.2284033900,-52.3855649286 -28.2284091973,-52.3855766453 -28.2283969805))', 4326));
INSERT INTO "WORK_264" (Geometry) VALUES
(GeomFromText('POLYGON((-52.3868293314 -28.2269741900,-52.3868371280 -28.2269800006,-52.3868488522 -28.2269677737,-52.3868410531 -28.2269619658,-52.3868293314 -28.2269741900))', 4326)),
(GeomFromText('POLYGON((-52.3868137382 -28.2269625689,-52.3868215348 -28.2269683795,-52.3868332540 -28.2269561579,-52.3868254549 -28.2269503500,-52.3868137382 -28.2269625689))', 4326)),
(GeomFromText('POLYGON((-52.3867981450 -28.2269509478,-52.3868059416 -28.2269567584,-52.3868176557 -28.2269445420,-52.3868098566 -28.2269387341,-52.3867981450 -28.2269509478))', 4326)),
(GeomFromText('POLYGON((-52.3867825518 -28.2269393267,-52.3867903484 -28.2269451373,-52.3868020575 -28.2269329262,-52.3867942584 -28.2269271183,-52.3867825518 -28.2269393267))', 4326));
Output:
status: 1 error: near "database": syntax error
status: 1 error: near "�": syntax error
| strQuery.toLatin1() is a temporary value, and .data() grabs a pointer within that value. This is effectively a dangling pointer.
Add an intermediate holding variable: (and use UTF8 instead of Latin1 while you're at it)
auto queryBA = strQuery.toUtf8();
int status = sqlite3_prepare_v2(database, queryBA.data(), queryBA.size(), &dbStatement, 0);
|
70,126,517 | 70,126,965 | Can't find qml module related to vlc | I cloned the vlc repository and I'm trying to modify the qt interface.
I stumbled upon this file MainInterface.qml which has a particular line:
import org.videolan.vlc 0.1
I can't help finding this module. I understood it's related to some other qmldir file but I don't understand where it might be.
Qt Creator doesn't show me the design panel because it can't find the module.
So, where do I find this module? Am I supposed to download some package?
(Working on Ubuntu 20.04 LTS)
| the module is defined in on the C++ side, it contains type registration for various models and types used in the QML interface
the module definition is here:
https://code.videolan.org/videolan/vlc/-/blob/4955734f1c3559a2a1315fc674a1d094c04d9692/modules/gui/qt/maininterface/mainui.cpp#L173
|
70,126,690 | 70,161,818 | Write binary file to disk super fast in MEX | I need to write a large array of data to disk as fast as possible. From MATLAB I can do that with fwrite:
function writeBinaryFileMatlab(data)
fid = fopen('file_matlab.bin', 'w');
fwrite(fid, data, class(data));
fclose(fid);
end
Now I have to do the same, but from a MEX file called by MATLAB. So I setup a MEX function that can write to file using either fstream or fopen (Inspired by the results of this SO post). This is however much slower than calling fwrite from MATLAB, as you can see below. Why is this the case, and what can I do to increase my write speed from the MEX function.
#include "mex.h"
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std;
void writeBinFile(int16_t *data, size_t size)
{
FILE *fID;
fID = fopen("file_fopen.bin", "wb");
fwrite(data, sizeof(int16_t), size, fID);
fclose(fID);
}
void writeBinFileFast(int16_t *data, size_t size)
{
ofstream file("file_ostream.bin", std::ios::out | std::ios::binary);
file.write((char *)&data[0], size * sizeof(int16_t));
file.close();
}
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
const mxArray *mxPtr = prhs[0];
size_t nelems = mxGetNumberOfElements(mxPtr);
int16_t *ptr = (int16_t *)mxGetData(mxPtr);
#ifdef USE_OFSTREAM
writeBinFileFast(ptr, nelems);
#else
writeBinFile(ptr, nelems);
#endif
}
Then I check the performance using the following script:
mex -R2018a -Iinclude CXXFLAGS="$CXXFLAGS -O3" -DUSE_OFSTREAM main.cpp -output writefast_ofstream
mex -R2018a -Iinclude CXXFLAGS="$CXXFLAGS -O3" main.cpp -output writefast_fwrite
for k = 1:10
sizeBytes = 2^k * 1024 * 1024;
fprintf('Generating data of size %i MB\n', sizeBytes / 2^20)
M = sizeBytes / 2; % 2 bytes for an int16
sizeMB(k) = sizeBytes / 2^20;
data = int16(rand(M, 1) * 100);
fprintf('TESTING: write matlab\n')
t_matlab(k) = timeit(@() writeBinaryFileMatlab(data));
fprintf('TESTING: write ofstream\n')
t_ofstream(k) = timeit(@() writefast_ofstream(data), 0);
fprintf('TESTING: write fwrite\n')
t_fwrite(k) = timeit(@() writefast_fwrite(data), 0);
end
% and plot result
figure(14); clf;
plot((sizeMB), t_matlab)
hold on
plot((sizeMB), t_ofstream)
plot((sizeMB), t_fwrite)
legend('Matlab', 'ofstream', 'fwrite')
xticks(sizeMB)
Which gives me the plot below. Why is calling fwrite from MATLAB so much faster than doing it from MEX? How can I reach the same speed in my MEX function?
I am using Windows 10. Laptop with Core i7, SSD.
UPDATE
I have tried various suggestions in the comments, but still do not reach MATLAB's fwrite performance. See the repo with the source code here: https://github.com/rick3rt/saveBinaryDataMex
This is the result with MSVC 2017, incorporating the suggestion of rahnema1:
UPDATE 2
Wow I finally got something that's faster than MATLAB! Rahnema1's answer did the trick :)
Here the figures with all suggested methods combined (complete src can be found on Github).
| As indicated in some posts very large buffers tend to decrease performance. So the buffer is written to the file part by part. For me 8 MiB gives the best performance.
void writeBinFilePartByPart(int16_t *int_data, size_t size)
{
size_t part = 8 * 1024 * 1024;
size = size * sizeof(int16_t);
char *data = reinterpret_cast<char *> (int_data);
HANDLE file = CreateFileA (
"windows_test.bin",
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
// Expand file size
SetFilePointer (file, size, NULL, FILE_BEGIN);
SetEndOfFile (file);
SetFilePointer (file, 0, NULL, FILE_BEGIN);
DWORD written;
if (size < part)
{
WriteFile (file, data, size, &written, NULL);
CloseHandle (file);
return;
}
size_t rem = size % part;
for (size_t i = 0; i < size-rem; i += part)
{
WriteFile (file, data+i, part, &written, NULL);
}
if (rem)
WriteFile (file, data+size-rem, rem, &written, NULL);
CloseHandle (file);
}
The output is compared to C++ Std lib method that is mentioned by @Cris Luengo :
|
70,126,763 | 70,126,904 | Change a bunch of numbers into corresponding alphabets | There are five types of bit encoding: 11, 10, 01, 001, 000.The corresponding message for each bit encoding is
11 -> A
10 -> B
01 -> C
001 -> D
000 -> E
The compile result will look like this:
Enter a sequence of bits: 01100001100110
CBEADB
I've wrote this but it can't work.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int A, B, C, D, E ;
string code;
cout << "Enter a sequence of bits: ";
cin >> code;
int i = 0;
while (i < code.length())
{
if( code[i]== 1 && code[i + 1]== 1 )
{
cout << 'A';
i += 2;
}
else if ( code[i]== 1 && code[i + 1]== 0)
{
cout << 'B';
i += 2;
}
else if ( code[i]== 0 && code[i + 1]== 1)
{
cout << 'C';
i += 2;
}
else if ( code[i]== 0 && code[i + 1]== 0 && code[ i + 2]== 1)
{
cout << 'D';
i += 3;
}
else if ( code[i]== 0 && code[i + 1]== 0 && code[ i + 2]== 0)
{
cout << 'E';
i += 3;
}
}
cout << endl;
return 0;
}
| Your input is a String not numbers, therefore you have to check for characters. Instead of using something like == 0, you should be using something like == '0'. Also, you may want to make sure that the input has the right format and you don't run into an infinite loop (by running the while forever without updating i) or buffer overflow (aka. index out of range, by checking code[i] with i >= code.length()). You can do something like:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int A, B, C, D, E ;
string code;
cout << "Enter a sequence of bits: ";
cin >> code;
int i = 0;
while (i+1 < code.length())
{
if( code[i]== '1' && code[i + 1]== '1' )
{
cout << 'A';
i += 2;
}
else if ( code[i]== '1' && code[i + 1]== '0')
{
cout << 'B';
i += 2;
}
else if ( code[i]== '0' && code[i + 1]== '1')
{
cout << 'C';
i += 2;
}
else if (i+2 < code.length())
{
if (code[i]== '0' && code[i + 1]== '0' && code[ i + 2]== '1')
{
cout << 'D';
i += 3;
}
else if ( code[i]== '0' && code[i + 1]== '0' && code[ i + 2]== '0')
{
cout << 'E';
i += 3;
}
else
{
return 1;
}
}
else
{
return 1;
}
}
if (i < code.length()) {
return 1;
}
cout << endl;
return 0;
}
You can try it out here.
|
70,126,882 | 70,128,752 | C++ header dependency propagation - how to limit it? | I have a repeating dilemma while constructing a class in C++. I'd like to construct the class without propagating its internal dependencies outside.
I know I have options like:
Use pimpl idiom
Use forward declaration and only reference or smart pointers in header
// header
class Forwarded; // I don't want to include Forwarded.h to not propagete it
class MyNewClass {
private:
std::unique_ptr<Forwarded> mForwareded;
void method1UsesForwarded();
void method2UsesForwarded();
public:
void doSomeAction();
};
// cpp
#include "Forwarded.h"
void MyNewClass::doSomeAction() {
method1UsesForwarded();
method2UsesForwarded();
}
void MyNewClass::method1UsesForwarded() { /* implementation */ }
void MyNewClass::method2UsesForwarded() { /* implementation */ }
Create another class or helper file which uses those files which I don't want to propagate further
// header
class MyNewClass {
public:
void doSomeAction();
};
// cpp
#include "helper.h"
void MyNewClass::doSomeAction() {
Forwarded f;
method1UsesForwarded(f);
method2UsesForwarded(f);
}
// helper.h
#include "Forwarded.h"
void method1UsesForwarded(Forwarded & f);
void method2UsesForwarded(Forwarded & f);
// helper.cpp
#include "helper.h"
void method1UsesForwarded(Forwarded & f) {
//implemntation
}
void method2UsesForwarded(Forwarded & f) {
//implemntation
}
Is there any other option? I don't like any of the above solutions because they provide some additional complication. The best option for me would be creation of Forwarded as normal private member and somehow not propagate it further :-)
| The underlying issue is that the consumers of MyNewClass need to know how big it is (e.g. if it needs to be allocated on the stack), so all members need to be known to be able to correctly calculate the size.
I'll not address the patterns you already described. There are a few more that could be helpful, depending on your use-case.
1. Interfaces
Create a class with only the exposed methods and a factory function to create an instance.
Upsides:
Completely hides all private members
Downsides:
requires heap allocation
lots of virtual function calls
Header:
class MyClass {
public:
static MyClass* create();
virtual ~MyClass() = default;
virtual void doSomeAction() = 0;
};
Source:
class MyClassImpl : public MyClass {
public:
void doSomeAction() override { /* ... */ }
private:
void method1UsesForwarded() { /* ... */ }
void method2UsesForwarded() { /* ... */ }
Forwarded f;
};
MyClass* MyClass::create() {
return new MyClassImpl();
}
2. Subclass Implementation
This is somewhat similar to the Interfaces one, with the upside that it gets rid of the virtual functions.
Upsides:
Completely hides all private members
Downsides:
requires heap allocation
Header:
class MyClass {
public:
static MyClass* create();
// only the destructor needs to be virtual now
virtual ~MyClass() = default;
void doSomeAction();
private:
MyClass() = default;
};
Source:
class MyClassImpl : public MyClass {
public:
void method1UsesForwarded() { /* ... */ }
void method2UsesForwarded() { /* ... */ }
Forwarded f;
};
void MyClass::doSomeAction() {
// e.g.:
static_cast<MyClassImpl*>(this)->method1UsesForwarded();
// ...
}
MyClass* MyClass::create() {
return new MyClassImpl();
}
3. Pre-allocating space for private members
If you don't mind a bit of manual work you can calculate how much space the private members will need and just provide a large enough buffer for that in the base class.
Upsides:
Completely hides all private members
Does not require a heap allocation
Downsides:
You need to manually check how large a buffer you need
Required size might change when using different compilers / different compiler versions
Header:
class MyClass {
public:
MyClass();
~MyClass();
void doSomeAction();
private:
void method1UsesForwarded();
void method2UsesForwarded();
struct MyClassMembers* getMembers();
/*
here you need to enter the size and alignment requirements
of your private data buffer.
*/
std::aligned_storage_t<8, 4> m_members;
};
Source:
struct MyClassMembers {
int i = 0;
int j = 0;
};
MyClass::MyClass() {
static_assert(sizeof(m_members) >= sizeof(MyClassMembers), "size too small!");
static_assert(alignof(m_members) >= alignof(MyClassMembers), "alignment too small!");
new (&m_members) MyClassMembers();
}
MyClass::~MyClass() {
getMembers()->~MyClassMembers();
}
MyClassMembers* MyClass::getMembers() {
return std::launder(reinterpret_cast<MyClassMembers*>(&m_members));
}
void MyClass::doSomeAction() {
method1UsesForwarded();
/* ... */
}
void MyClass::method1UsesForwarded() {
/* ... */
std::cout << getMembers()->i << std::endl;
}
void MyClass::method2UsesForwarded() {
/* ... */
}
One gotcha of this approach is that you need to provide the correct size & alignment for your data struct (in this case MyClassMembers).
You can either eyeball it (the static_asserts ensure that it won't compile if the requirements are not met) by trying to compile with different values until it works, or write a short function that prints out the correct values for you:
struct MyClassMembers {
int i;
int j;
};
int main(int argc, char* argv[]) {
std::cout << sizeof(MyClassMembers) << std::endl;
std::cout << alignof(MyClassMembers) << std::endl;
}
|
70,127,129 | 70,133,868 | What should I install to use namespace Windows::Devices in c++? | Now I am going to connect to device using bluetooth, so I have got some source code.
It uses namespace Windows::Devices, but my visual studio gives me compile error.
using namespace Windows::Devices;
I guess I have to install some packages additionally, but I am not sure what I have to install.
If anyone knows, please help me.
| Since the question is tagged c++ I'm going to assume that that's the programming language you are using. The most convenient way to consume Windows Runtime types from C++ is through C++/WinRT. It consists of both a base library as well as a code generator. The code generator is responsible for providing the "projected types" (see Consume APIs with C++/WinRT), generated into namespaces such as Windows::Devices.
It's common for a project to generate the headers containing the projected types on the fly, that can then be included like any other header. A project created using the C++/WinRT VSIX extension does that. Those projects have a reference to the Microsoft.Windows.CppWinRT NuGet package that contains the code generator, as well as project properties to drive it during a build.
Previously, the header files containing the projected C++/WinRT types had been delivered through the Windows SDK. They are still part of the SDK, and can be used by client code, even though it's preferable to use the NuGet package instead. You'll find the Windows.Devices.h header file under %WindowsSdkDir%Include<WindowsTargetPlatformVersion>\cppwinrt\winrt, so to use this namespace, that's the file you'll need to include.
|
70,127,146 | 70,127,399 | warning C5246: the initialization of a subobject should be wrapped in braces | The latest Visual Studio 2019 compiling the following code with /Wall command-line switch (which enables all warnings):
struct A{};
void f( const std::array<A, 2> & ) {}
int main() {
A x, y;
f( { x, y } );
}
prints the warning:
warning C5246: 'std::array<A,2>::_Elems': the initialization of a subobject should be wrapped in braces
however both GCC and Clang accepts the code with the most pedantic error checking, demo: https://gcc.godbolt.org/z/Ps6K6jK1G
Indeed, all compilers accept the call f( { { x, y } } );
Is MSVC right in suggesting it in favor of the simpler form without extra braces?
| Visual Studio 2019 has the CWG defect #1270 and offers the old initialization behaviour.
std::array is defined as an aggregate that contains another aggregate.
C++ 17 Standard (11.6.1 Aggregates)
12 Braces can be elided in an initializer-list as follows. If the initializer-list begins with a left brace, then the succeeding comma-separated list of initializer-clauses initializes the elements of a subaggregate; it is erroneous for there to be more initializer-clauses than elements. If, however, the initializer-list for a subaggregate does not begin with a left brace, then only enough initializer-clauses from the list are taken to initialize the elements of the subaggregate; any remaining initializer-clauses are left to initialize the next element of the aggregate of which the current subaggregate is an element.
You may imagine std::array<A, 2> as
struct Array {
A sub[2];
};
According to the quote Array a {{x, y}} is correct, but obsolete, the inner braces is aggregate initialization of the enclosed array.
Useful thread Why is the C++ initializer_list behavior for std::vector and std::array different?.
|
70,127,777 | 70,128,103 | Creating unordered map in C++ for counting the pairs | So let's say I have an array, 1 2 1 2 3 4 2 1 and I want to store all the (arr[i], arr[i-1) such that arr[i] != arr[i-1] as a pair in unordered_map for counting these pairs.
For e.g.
(1, 2) -> 2
(2, 3) -> 1
(3, 4) -> 1
(4, 2) -> 1
(2, 1) -> 1
So the syntax I tried,
unordered_map<pair<int, int>, int> umap;
int temp;
cin>>temp;
arr[i]=temp;
for (int i=1; i< n; i++){
cin>>temp;
arr[i]=temp;
umap[(arr[i-1], arr[i])]++;
}
Next thing, I also tried with proper definition.
unordered_map<pair<int, int>, int> umap;
cin>>temp;
arr[i]=temp;
for (int i=1; i< n; i++){
cin>>temp;
arr[i]=temp;
pair<int, int> p(arr[i-1], arr[i]);
umap[p]++;
}
Can anybody please help me get the right syntax?
| You can't just use unordered_map with a pair because there is no default hash implemented.
You can however use map which should work fine for your purpose because pair does implement <.
See Why can't I compile an unordered_map with a pair as key? when you really want unordered_map.
You can construct pair with curly braces like this
umap[{arr[i-1], arr[i]}]++;
I think from C++11 onward, but it might be C++14 or even C++17
|
70,127,899 | 70,185,303 | librdkafka custom logger, function signature | I'm using the librdkafka c++ API and I would like to change the default behavior of the logger.
In the c API there is this function rd_kafka_conf_set_log_cb() to set the log callback. It takes a function with the signature:
void(*)(const rd_kafka_t *rk, int level, const char *fac, const char *buf)
However I can't figure out what const char *fac does in the function signature. I can see that strings such as "FAIL" or "BGQUEUE" are passed when using it, but I can't find any documentation on what they mean or how to use them.
What is the const char *fac used for, and are there docs on its use or a dictionary for their definitions?
| The facility string is a semi-unique name for the context where the log is emitted. It is mainly there to help librdkafka maintainers identify the source of a log line, but can also be used for filtering purposes.
It was originally inspired by Cisco IOS like system logs which came in the form of:
FAC-LVL-SUBFAC: Message...
The librdkafka counterpart would be:
RDKAFKA-7-JOIN: Joining consumer group xyx
where JOIN is the librdkafka logging facility.
|
70,128,344 | 70,128,443 | Can multiple parameter packs be expanded in a single expression? | I want to get a matrix from two parameter packs like the following:
template < typename T1, typename T2 > struct Multi{};
template < int ... n > struct N{};
void Print( int n ){ std::cout << n << std::endl; }
template < int ... n1, int ... n2 >
struct Multi< N<n1...>, N<n2...>>
{
Multi()
{
using expander = int[];
// No idea which syntax should be used here:
expander{ 0,((void)Print(n1...*n2),0)... };
}
};
int main()
{
Multi< N<1,2,3,4>, N< 10,20> >{};
}
The result should be
10 20 30 40 20 40 60 80
How can I do this?
| No need to use the dummy arrays when you have fold expressions.
The naive (Print(n1 * n2), ...); wouldn't work (it expects the packs to have the same size, and would print N numbers instead of N2).
You need two nested fold expressions. In the inner one, you can prevent one of the packs from being expanded by passing it as a lambda parameter.
([](int n){(Print(n1 * n), ...);}(n2), ...);
|
70,128,458 | 70,136,444 | Using shared C++ library in Idris | I want to FFI to a third-party C++ library from Idris but I'm getting "undefined symbol". I'm new to C/C++ compilation.
I'm doing this by wrapping the C++ in a pure C layer which I call from Idris. The C++ code is provided as a bunch of .h headers and a single .so shared library. At the moment I only have one C file, but I may have more later.
Here's the C++ library header include/foo.h
#include <some/other/library/header.h>
namespace mynamespace {
class Foo {
public:
Foo();
}
}
and the C wrapper wrapper.cpp
#include <foo.h>
extern "C" {
struct cFoo;
using namespace mynamespace;
struct cFoo* cFoo_new() {
return reinterpret_cast<cFoo*>(new Foo());
}
}
The shared library is lib/libfoo_ext.so and I'm compiling these with
g++ -shared -Iinclude -Llib -lfoo_ext -o libfoo.so wrapper.cpp
That runs without errors. Meanwhile, the Idris code is
module Foo
import System.FFI
export
Foo : Type
Foo = Struct "cFoo" []
%foreign "C:cFoo_new,libfoo"
export
mkFoo : Foo
and I'm calling mkFoo in a test file. When I do this I get
Exception: (while loading libfoo.so) .../build/exec/_tmpchez_app/libfoo.so: undefined symbol: _ZN17mynamespace6FooC1Ev
| This command:
g++ -shared -Iinclude -Llib -lfoo_ext -o libfoo.so wrapper.cpp
is incorrect. Assuming libfoo_ext is the 3rd party library which implements mynamespace::Foo::Foo(), the link command should be:
g++ -shared -Iinclude -Llib -o libfoo.so wrapper.cpp -lfoo_ext
The order of libraries and sources on the link line matters, yours is wrong.
|
70,129,810 | 70,129,873 | Is changing the std::string value through it's address is valid? | I was wondering if we can modify std::string value through a pointer to it. Please consider the following example.
#include <iostream>
void func(std::string *ptr) {
*ptr = "modified_string_in_func";
}
int main()
{
std::string str = "Original string";
func(&str);
std::cout << "str = " << str << std::endl;
return 0;
}
I tried GCC, Clang & Visual C++. All are modifying the string valirable str without any warning or error but I'm not very sure if it's legal to do so.
Please clarify.
| That is legal.
You are assigning a new value to the string but are using a pointer to refer to the original string; this is no more illegal then not using a pointer to refer to the original string i.e.
std::string foo = "foo";
foo = "bar";
// is pretty much the same thing as
std::string* foo_ptr = &foo;
*foo_ptr = "bar";
// which is what you are doing.
|
70,129,833 | 70,129,874 | Cpp/C++ Assign Default value to default constructor | This seems like a really easy question but I can't find a working solution(maybe it is the rest of the code too).
So basically how do you assign a value to an object created with the default constructor, when the custom constructor has that variable as a parameter? (hopefully this is understandable)
Maybe clearer:
The code below only works if I write foo ex2(2) instead of foo ex2() inside the main function. So how do I assign a default value to x if the object is created with the default constructor
class foo {
public:
int y;
int x;
static int counter;
foo()
{
y = counter;
counter++;
x = 1;
};
foo(int xi)
{
y = counter;
counter++;
x = xi;
};
};
int foo::counter = 0;
int main()
{
foo ex1(1);
foo ex2();
std::cout << ex1.y << "\t" << ex1.x << "\n";
std::cout << ex2.y << "\t" << ex2.x << "\n";
std::cin.get();
};
| This record
foo ex2();
is not an object declaration of the class foo.
It is a function declaration that has the return type foo and no parameters.
You need to write
foo ex2;
or
foo ( ex2 );
or
foo ex2 {};
or
foo ex2 = {};
|
70,129,964 | 70,133,294 | Choosing collisions of hash functions | According to the condition of the problem, it is necessary to "break" the standard hash "gcc". It is necessary for the program to run for more than 1.5 seconds according to the input data. 15000 string with up to 15 characters 0-9A-Za-z_ is appended to unordered_set.
If I understand correctly, it is necessary to choose such strings, the hash of which will be the same, but it is not clear how
auto users_list = getUsers( 15'000u );
auto start_time = std::clock();
for( const auto& user : users_list ) {
users.insert( user );
}
auto end_time = std::clock();
double spent = static_cast<double>( end_time - start_time ) / CLOCKS_PER_SEC;
The code of the program to be "broken" (does not change):
https://github.com/NikitaChampion/data-structures/blob/main/contest/hacks/bad-hash-gcc.cpp
| In order to make the program slow, you'd need to find 15000 strings (15 chars or less) with an identical hash. That will degrade the performance of insertion on unordered_set to be equivalent to searching within a linked list for a duplicate and appending the new string at the end.
If your code is running in the 32-bit space, a brute force attack on std::hash<std::string> is feasible to find 15000 strings with the same hash.
Each string is at most 15 characters long. Each character is one of 63 different values (A-Z, a-z, 0-9, or _). For a 15 character string, that's 63¹⁵ possible combinations. But... std::hash returns a size_t value. And sizeof(size_t) == 4 on 32-bit machines. Intuitively thinking... if you hash 4 billion unique strings, you should find at least one pair of strings with identical hashes. And 63¹⁵ divided by 2³² is in the neighborhood of 227 quadrillion string with matching hashes for any given 15 character string in your allowed char set. We only need 15000. And we don't necessarily need a 15 character string either.
So if we hash all strings from "AAAAAAAAAAAAAAAAA" to "ZZZZZZZZZZZZZZZ" to find a given hash, we'll eventually find 15000 unique strings that have the same hash. We can use a shorter string size too to reduce the complexity of hashing.
Basically the algorithm is this:
hash<string> hasher;
size_t targetHash = hasher("AAAAAAAAAAAAAAA"); // find all strings with identical hashes as AAAAAAAAAAAAAAA
uint64_t i = 0;
while (true)
{
string s = generateString(i);
if (hasher(s) == targetHash))
{
cout << s << std::endl;
}
}
Where generateString is a function that generates the Nth sequential string in the series. (e.g. generateString(0) => "AAAAAAAAAAAAAAA" and generateString(1) => "AAAAAAAAAAAAAAB" )
After I upgraded the code with a few optimizations and to using multiple threads to run in parallel, I was able find identical hashes for the 10 character string "AAAAAAAAAA" approximately every 6 seconds or 10 per minute. Hence, in about 62 hours, we'd have 15000 unique strings computed.
Shove those 15000 strings into a text file and use that as redirected input into your program.
Doing some quick math, you probably don't need as many as 15000 duplicate strings to break the running time of the program to run longer than 1.5 seconds to that many inserts. You probably only need a fraction of that amount (like 1000 - 5000) to make the program run slow enough. 1000 duplicate strings would generate at least a half-million string comparisons for the insert operations to complete.
On 64-bit architectures, none of this feasible on conventional PC hardware. The chances of collisions are far less since the size_t returned by std::hash is a 64-bit value. Duplicate hash collisions will be much harder to fine via brute force. You'd have to reverse engineer the std::hash code.
|
70,130,300 | 70,134,389 | Antlr4: Can't understand why breaking something out into a subrule doesn't work | I'm still new at Antlr4, and I have what is probably a really stupid problem.
Here's a fragment from my .g4 file:
assignStatement
: VariableName '=' expression ';'
;
expression
: (value | VariableName)
| bin_op='(' expression ')'
| expression UNARY_PRE_OR_POST
| (UNARY_PRE_OR_POST | '+' | '-' | '!' | '~' | type_cast) expression
| expression MUL_DIV_MOD expression
| expression ADD_SUB expression
;
VariableName
: ( [a-z] [A-Za-z0-9_]* )
;
// Pre or post increment/decrement
UNARY_PRE_OR_POST
: '++' | '--'
;
// multiply, divide, modulus
MUL_DIV_MOD
: '*' | '/' | '%'
;
// Add, subtract
ADD_SUB
: '+' | '-'
;
And my sample input:
myInt = 10 + 5;
myInt = 10 - 5;
myInt = 1 + 2 + 3;
myInt = 1 + (2 + 3);
myInt = 1 + 2 * 3;
myInt = ++yourInt;
yourInt = (10 - 5)--;
The first sample line myInt = 10 + 5; line produces this error:
line 22:11 mismatched input '+' expecting ';'
line 22:14 extraneous input ';' expecting {<EOF>, 'class', '{', 'interface', 'import', 'print', '[', '_', ClassName, VariableName, LITERAL, STRING, NUMBER, NUMERIC_LITERAL, SYMBOL}
I get similar issues with each of the lines.
If I make one change, a whole bunch of errors disappear:
| expression ADD_SUB expression
change it to this:
| expression ('+' | '-') expression
I've tried a bunch of things. I've tried using both lexer and parser rules (that is, calling it add_sub or ADD_SUB). I've tried a variety of combinations of parenthesis.
I tried:
ADD_SUB: [+-];
What's annoying is the pre- and post-increment lines produce no errors as long as I don't have errors due to +-*. Yet they rely on UNARY_PRE_OR_POST. Of course, maybe it's not really using that and it's using something else that just isn't clear to me.
For now, I'm just eliminating the subrule syntax and will embed everything in the main rule. But I'd like to understand what's going on.
So... what is the proper way to do this:
| Do not use literal tokens inside parser rules (unless you know what you're doing).
For the grammar:
expression
: '+' expression
| ...
;
ADD_SUB
: '+' | '-'
;
ANTLR will create a lexer rules for the literal '+', making the grammar really look like this:
expression
: T__0 expression
| ...
;
T__0 : '+';
ADD_SUB
: '+' | '-'
;
causing the input + to never become a ADD_SUB token because T__0 will always match it first. That is simply how the lexer operates: try to match as much characters as possible for every lexer rule, and when 2 (or more) match the same amount of characters, let the one defined first "win".
Do something like this instead:
expression
: value
| '(' expression ')'
| expression UNARY_PRE_OR_POST
| (UNARY_PRE_OR_POST | ADD | SUB | EXCL | TILDE | type_cast) expression
| expression (MUL | DIV | MOD) expression
| expression (ADD | SUB) expression
;
value
: ...
| VariableName
;
VariableName
: [a-z] [A-Za-z0-9_]*
;
UNARY_PRE_OR_POST
: '++' | '--'
;
MUL : '*';
DIV : '/';
MOD : '%';
ADD : '+';
SUB : '-';
EXCL : '!';
TILDE : '~';
|
70,130,328 | 70,131,057 | overflow when attempting to push_back randomly generated numbers in a vector | my code is shown here:
#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
using std::string;
using std::endl;
using std::cout;
using std::cin;
struct funcs
{
std::vector<int> values;
int sum;
void createVectorValues(){
while(values.size() < 100)
{
int x = rand() % 100;
values.push_back(x);
}
for(int& a : values)
{
sum += 1;
}
cout << sum;
}
};
int main()
{
srand;
funcs myFunct;
myFunct.createVectorValues();
}
the following code results in a large value such as -858993360
How can I change this code so that it can function properly
|
You didn't define a constructor for funcs, so you get the default constructor, which invokes the default constructor of each member. This means the int member sum is left with an indeterminate value. See Does the default constructor initialize built-in types?. You probably want to write a constructor that initializes sum to 0.
srand; isn't a function call. It's valid syntax, because srand evaluates to a pointer to the srand function, but it's an expression with no side effects, so it does nothing. Much as if you had written 3;. To call the function, you need srand(arg), where arg is an appropriate integer. Or, switch to the C++11 random number generation features, which are much more powerful and usually have better randomness.
|
70,130,468 | 70,130,686 | How can I create different types from uint32_t that are statically different? | I want to create different types that are uint32_t but are different from compilers perspective -- they can only be compared and assigned to a value of the exact same type. Here is a sample code that I want to achieve:
TextureResourceId t1 = 1000, t2 = 2000;
PipelineResourceId p1 = 1000, p2 = 2000;
BufferResourceId b1 = 1000, b2 = 1000;
if (t1 == t2) // OK!
if (t1 == p1) // Compiler error!
if (t1 == b1) // Compiler error!
I know that I can do some preprocessor magic to achieve this:
#define CREATE_RESOURCE_ID(NAME) \
class NAME { \
public: \
NAME(uint32_t value_): value(value_) {} \
bool operator==(const NAME &rhs) { return value == rhs.value; } \
private: \
uint32_t value; \
};
CREATE_RESOURCE_ID(TextureResourceId);
CREATE_RESOURCE_ID(BufferResourceId);
CREATE_RESOURCE_ID(PipelineResourceId);
int main() {
TextureResourceId tex1(1000), tex2(2000);
BufferResourceId buf1(1000);
PipelineResourceId pip1(1000);
if (tex1 == tex2) {}
if (buf1 == tex1) {}
if (tex1 == pip1) {}
return 0;
}
But I would like to know if there is a more C++'y way of doing this (e.g with inheritance or some kind of syntax with enum classes)
| Since you only seem to need to check identity, an enum should be the natural choice and as you mention, enum class can be used to ensure the underlying type is uint32_t:
enum class TextureResourceId: uint32_t
{
id1 = 1000,
id2 = 2000
};
enum class PipelineResource: uint32_t
{
id1 = 1000,
id2 = 2000
};
enum class BufferResourceId: uint32_t
{
id1 = 1000,
id2 = 2000
};
With values initialized as in the example:
TextureResourceId t1 = TextureResourceId::id1, t2 = TextureResourceId::id2;
PipelineResourceId p1 = PipelineResourceId::id1, p2 = PipelineResourceId::id2;
BufferResourceId b1 = BufferResourceId::id1, b2 = BufferResourceId::id2;
The compiler should behave as specified, i.e. allow IDs to be compared within the same class, but not across different classes.
Note: if you do not want to explicitly declare all possible identities in the enum classes, identities can also be constructed from integers, e.g. TextureResourceId(1000).
|
70,130,644 | 70,130,677 | QTCreator 5.0.2, parallel run of two window, C++ | I went throught suggested "questions" about my problem. However neither does not solve it.
I program two windows. The second window is opening from first window. I need active the both windows, however to start the first window(MainWindow) I use:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowModality(Qt::NonModal);
return a.exec();
}
As was mentioned, the second window is started from pushButton, which is situated in first window(MainWindow) by same way.
void MainWindow::on_pushButton_2_clicked()
{
Graphics gr;
gr.setWindowModality(Qt::NonModal);
gr.exec();
}
I changed modality to NonModal,however the problem is without change. The Non-Modal mean:"The window is not modal and does not block input to other windows." <- from documentation
By documentation is recommended to avoid used .exec(). The alternatives are .show() and open(), which i tried. After the modification, the second window is shut down immediately after opening. after open immediately shut down.
Do you have any idea, how to solve that?
| Graphics gr; defines a local variable, so the object is destructed as soon as it goes out of scope (at the end of your function).
In Qt, the typical approach is to work with pointers to Qt widgets (and, more generally, QObjects), but have a parent for each – the parent will clean it up.
Try this instead:
auto gr = new Graphics(this);
gr->setWindowModality(Qt::NonModal); // this is the default, no need for this call
gr->show();
This way the window will survive until your main window is destructed. In Qt there is also a mechanism for widgets/objects to self-destruct:
this->deleteLater();
So for example if you want to close and cleanup gr you can use that mechanism (you could also store gr as a member and call gr->deleteLater().
|
70,130,735 | 70,130,881 | C++ concept to check for derived from template specialization | In this SO answer and this proposal we can see an implementation (included below for convenience) for std::is_specialization_of, which can detect if a type is a specialization of a given template.
template< class T, template<class...> class Primary >
struct is_specialization_of : std::false_type {};
template< template<class...> class Primary, class... Args >
struct is_specialization_of< Primary<Args...>, Primary> : std::true_type {};
The proposal explicitly says that this type trait is not affected by inheritance:
The proposed trait considers only specialization. Since specialization is unrelated to inheritance, the trait’s result is unaffected when any template argument happens to be defined via inheritance.
template< class > struct B { };
template< class T > struct D : B<T> { };
static_assert( is_specialization_of_v< B<int>, B> );
static_assert( is_specialization_of_v< D<int>, D> );
static_assert( not is_specialization_of_v< B<int>, D> );
static_assert( not is_specialization_of_v< D<int>, B> );
Is there a way to implement something that does take inheritance into consideration, behaving like std::derived_from but where the Base could be any specialization of a given template? Something like, say std::derived_from_specialization_of:
template<class> struct A {};
template<class T> struct B : A<T> {};
template<class T> struct C : B<T> {};
static_assert(derived_from_specialization_of< A<int>, A>);
static_assert(derived_from_specialization_of< B<int>, B>);
static_assert(derived_from_specialization_of< C<int>, C>);
static_assert(derived_from_specialization_of< B<int>, A>);
static_assert(derived_from_specialization_of< C<int>, B>);
static_assert(derived_from_specialization_of< C<int>, A>);
It should also support templates with multiple parameters, and/or parameter packs:
template<class, class> struct A{};
template<typename...> struct B{};
| De-_Ugly-fied rom MSVCSTL:
template <template <class...> class Template, class... Args>
void derived_from_specialization_impl(const Template<Args...>&);
template <class T, template <class...> class Template>
concept derived_from_specialization_of = requires(const T& t) {
derived_from_specialization_impl<Template>(t);
};
which we use to implement the exposition-only type trait is-derived-from-view-interface from [range.view]/6.
Note that this has the same limitation as the is_specialization_of trait cited in the OP: it works only with templates that have all type parameters.
[DEMO]
|
70,130,786 | 70,130,814 | How do I consicely express the templated dereferenced Iterator type as a template parameter | Lets say I'm rewriting std::min_element for c++17.
https://en.cppreference.com/w/cpp/algorithm/min_element
I'm unhappy with all the overloads. I'd very much like it if (1) and (3) could be expressed in terms of default arguments.
So (3) could replace (1) with
template< class ForwardIt, class Compare = typename std::less< ??? > >
ForwardIt min_element( ForwardIt first, ForwardIt last, Compare comp = Compare{});
My problem is ??? involves
std::remove_reference<decltype((*first){})>.type
My intent is to have a specialized std::less<MyType> working for any iterator dereferencing to MyType and any range using MyType*.
With the overload it just becomes
template<typename It>
It min_element(It first, It last){
{ auto e = *first;
return min_element(first, last, std::less<decltype(e)>());
}
calling the
template<typename It, typename Comp>
It min_element(It first, It last, Comp c){
{ // it probably needs to be something here, maybe returning an It
}
Is there a concise way to remove the overload with default arguments?
Also I imagine my version to be very buggy.
| std::less<void> does work for any type, because its operator() is a template and the actual type to be compared is deduced when the operator is called. It was introduced in C++14.
|
70,130,824 | 70,131,242 | With std::optional, what does it mean to "remove the move constructor from overload resolution"? | I'm creating an implementation of std::optional in C++14. However, I'm slightly confused with how the move constructor is specified. Here's what I'm referring to (emphasis mine):
The expression inside noexcept is equivalent to is_nothrow_move_constructible_v<T>.
This constructor shall not participate in overload resolution unless is_move_constructible_v<T> is true. If is_trivially_move_constructible_v<T> is true, this constructor shall be a constexpr
constructor.
What does it mean to remove the move constructor from overload resolution? Deletion and SFINAE don't seem to work for this scenario.
| Yes, SFINAE does not work for constructors, use base classes forcing the compiler to do the right thing.
It means it is not defined and the class cannot be move constructed. More interesting question is why is it needed?
I am not 100% sure I have the right answer to that.
TL;DR Returning std::optional<NonMoveable> generates compiler errors if the move constructor of optional is present. On the other hand, returning NonMoveable directly fallbacks to copy constructor.
First, the constraint does not break anything. The constructor cannot be implemented if T cannot be move constructed.
Second, all methods of std::optional are very tricky due to std::optional<std::optional<T>> issue which could easily lead to ambiguous calls if proper constraints are not taken, optional(U&& value) is really susceptible to this.
The main reason is, I believe, because we want optional<T> to act as T whenever possible and there is one edge case, that I am aware of, when the existence of std::optional's move constructor for non-moveable T leads to unnecessary compiler errors. Coincidentally, it is the case of returning std::optional by value from functions, something I do very often.
For a variable x of type T, return x in a function T foo() calls move constructor if it accessible, copy if not.
Take these simple definitions:
#include <utility>
struct CopyOnly {
CopyOnly() = default;
CopyOnly(const CopyOnly &) = default;
CopyOnly(CopyOnly &&) = delete;
CopyOnly &operator=(const CopyOnly &) = default;
CopyOnly &operator=(CopyOnly &&) = delete;
~CopyOnly() = default;
};
template <typename T> struct Opt {
Opt() = default;
Opt(const Opt &other) : m_value(other.m_value) {}
Opt(Opt &&other) : m_value(std::move(other.m_value)) {
// Ordinary move ctor.
// Same as =default, just writing for clarity.
}
// Ignore how `T` is actually stored to be "optional".
T m_value;
};
and this example
template <typename T> T foo(const T &t) {
auto x = t;
return x;
}
int main() {
Opt<int> opt_int;
CopyOnly copy;
Opt<CopyOnly> opt_copy;
foo(opt_int);//#1
foo(copy);//#2
foo(opt_copy);//#3
}
return x:
Calls move constructor because opt_int can be moved.
Calls copy constructor as a fallback because it cannot be moved.
Compiler error because Opt<CopyOnly> has accessible move constructor so it is chosen, but its instantiation leads to an error due m_value(std::move(other.m_value)) trying to explicitly calls deleted move ctor.
If one disables the move constructor, copy constructor is chosen and the code is identical to #2.
|
70,131,467 | 70,132,547 | How to compute hash of std::weak_ptr? | So I have code that uses std::weak_ptr and maintains them in an std::set, and that works just fine -- and has worked for the last 5 or 7 years. Recently I thought I'd fiddle with using them in an std::unordered_set (well, actually in an f14::F14ValueSet) and for that, I would need a hash of it. As of now, there is no std::hash<std::weak_ptr>, so what should I do instead?
The answer seems to be "just hash the control block", as implied by this question and reply: Why was std::hash not defined for std::weak_ptr in C++0x?, but how do I get access to the control block? In glibc, it's located at __weak_ptr<>::_M_refcount._M_pi-> but that's private (and implementation specific). What else can I do?
One answer is "just wait": maybe someday there will be a standard owner_hash() for std::weak_ptr, but I'd prefer something available now.
| Make your own augmented weak ptr.
It stores a hash value, and supports == based off owner_before().
You must make these from shared_ptrs, as a weak ptr with no strong references cannot be hashed to match its owner; this could create two augmented weak ptrs that compare equal but hash differently.
template<class T>
struct my_weak_ptr {
// weak ptr API clone goes here. lock() etc.
// different ctor:
my_weak_ptr(std::shared_ptr<T>const& sp){
if(!sp) return;
ptr=sp;
hash = std::hash<T*>{}(sp.get());
}
std::size_t getHash()const{return hash;}
friend bool operator<(my_weak_ptr const& lhs, my_weak_ptr const& rhs){
return lhs.owner_before(rhs);
}
friend bool operator!=(my_weak_ptr const& lhs, my_weak_ptr const& rhs){
return lhs<rhs || rhs<lhs;
}
friend bool operator==(my_weak_ptr const& lhs, my_weak_ptr const& rhs){
return !(lhs!=rhs);
}
private:
std::weak_ptr<T> ptr;
std::size_t hash=0;
};
these have stable, sensible hashes. While a recycled object pointer results in a hash collision, so long as they don't share control blocks they won't be equal.
namespace std{template<class T>struct hash<some_ns::my_weak_ptr<T>>{
std::size_t operator()(my_weak_ptr<T> const& wp)const{return wp.getHash();}
};}
One warning: Use of aliasing constructor could result in pathological results. As equality is based on control block equality, not pointer value.
|
70,131,609 | 70,131,961 | OpenGL: glVertexAttribFormat.attribindex vs GLSL vertex shader location | Does the attribindex in glVertexAttribFormat correspond with the layout location in my GLSL vertex shader?
i.e. if I write
glVertexAttribFormat(0, 3, GL_FLOAT, GL_FALSE, offsetof(Vertex, position));
That 0 would correspond with this line in my shader?
layout (location = 0) in vec3 inPos;
| Yup. Otherwise without a location specifier you have to query the attribute location via glGetAttribLocation() after program linking or set it before program linking via glBindAttribLocation().
|
70,131,610 | 70,131,630 | Can't display the entire string when translating CHAR to INT | In my intro class, I'm tasked with translating a phone number that may have letters in it, back to a pre-determined list of numbers (like 1-800-COLLECT would display as 1-800-2655328) and currently, I can translate the letters to numbers but for whatever reason, the non-letters in the phone numbers arent being translated. This is the main function:
int main()
{
string original;
cout << "Please enter a phone number with letters: ";
getline(cin, original);
cout << "This is your number without letters: ";
for (int i = 0; i < original.length(); i++)
{
if (original[i] < 0 || original[i] > 9)
{
translate(original[i]);
}
else
cout << original[i];
}
}
The translate function simply takes whatever element its fed and, if it falls between Aa - Zz it will display a predetermined number. (Aa - Cc would display the number 2, etc) So far it works for translating, as when I put in "1800GOTJUNK" it returns "4685865" fine, but won't acknowledge the "1800" before it, I think there's something wrong with how I'm structuring the if and for statements to display everything correctly, can someone give me some advice?
| This:
if (original[i] < 0 || original[i] > 9)
Is comparing against the ASCII codes 0 and 9, not the actual characters.
It should be:
if (original[i] < '0' || original[i] > '9')
|
70,131,705 | 70,131,744 | OpenGL: What's the point of the "named" buffer functions if you have to bind a target anyway? | e.g. when I do
glBindBuffer(GL_ARRAY_BUFFER, _id);
glNamedBufferData(_id, size, data, static_cast<GLenum>(usage));
then program works as expected. But if I delete that first line, my program crashes and prints:
ERROR 1282 in glNamedBufferData
Likewise, if I do
glBindVertexArray(_id);
GLuint attribIndex = 0;
GLuint offset = 0;
for(const GlslType type : layout) {
const auto& attrib = GLSL_TYPES.at(type);
glVertexArrayAttribFormat(_id, attribIndex, attrib.size, static_cast<GLenum>(attrib.type), GL_FALSE, offset);
glEnableVertexArrayAttrib(_id, attribIndex);
glVertexArrayAttribBinding(_id, attribIndex, 0);
offset += attrib.size_bytes();
}
It works fine, but if I delete the glBindVertexArray then it doesn't work and prints:
ERROR 1282 in glVertexArrayAttribFormat
ERROR 1282 in glEnableVertexArrayAttrib
ERROR 1282 in glVertexArrayAttribBinding
I figured that by "naming" the VBO or VAO when calling those functions then I wouldn't have to bind it beforehand. But if I have to bind regardless, what's the benefit of these functions that require the extra name argument?
| The glGen* functions create a integer name representing an object, but they don't create the object state itself (well, most of them don't). It is only when you bind those objects do they gain their state, and only after they have state can any function be called which requires them to have state. In particular, the direct state access functions.
This is why ARB_direct_state_access also includes the glCreate* functions. These functions create an integer name and the state data for objects. Therefore, you don't have to bind anything to manipulate direct state access functions, so long as you properly created the object beforehand.
|
70,131,727 | 70,136,816 | LLD undefined symbol when attempting to link glfw | I've been trying to get an LLVM toolchain setup on my Windows 10 machine. I gave up on building from source and have the MSYS2 mingw-w64-clang-x86_64-toolchain package installed (clang version 13.0.0).
I can compile simple code that uses the C++ standard library. I'm using clang to compile, lld to link, and I should be using libc++.
To test linking an additional library, I'm using glfw:
#include <iostream>
#include <vector>
#include "glfw3.h"
int main(int argc, char **argv) {
glfwInit();
std::vector<int> testVector = {4, 5, 6, 7, 2};
testVector.push_back(23);
std::cout << testVector[1] << std::endl;
return 0;
}
This compiles and runs fine if I comment out the glfwInit(); line and use this command :
clang++ -Iinclude\ -Llib\ -lglfw3 -v .\main.cpp
So it seems lld is finding the libglfw3.a library file I placed in the lib\ directory.
But if glfwInit(); is uncommented, with the same command I get a lot of unresolved symbol errors:
ld.lld: error: undefined symbol: __declspec(dllimport) CreateDIBSection
>>> referenced by libglfw3.a(win32_window.c.obj):(createIcon)
ld.lld: error: undefined symbol: __declspec(dllimport) CreateBitmap
>>> referenced by libglfw3.a(win32_window.c.obj):(createIcon)
ld.lld: error: undefined symbol: __declspec(dllimport) DeleteObject
>>> referenced by libglfw3.a(win32_window.c.obj):(createIcon)
>>> referenced by libglfw3.a(win32_window.c.obj):(createIcon)
>>> referenced by libglfw3.a(win32_window.c.obj):(updateFramebufferTransparency)
..and so on.
I built the glfw library from the glfw source code using CMake, Ninja, and Clang.
The win32_window.c.obj file and all others referenced by these errors are a couple directories deeper in the lib\ directory, but I can't seem to get clang/lld to find them.
What argument am I missing here?
Edit: I ran this
clang++ -### -Iinclude\ -Llib\ -lglfw3 -v .\main.cpp
And got these two lines:
"C:/msys64/clang64/bin/clang++.exe" "-cc1" "-triple" "x86_64-w64-windows-gnu" "-emit-obj" "-mrelax-all" "--mrelax-relocations" "-disable-free"
"-disable-llvm-verifier" "-discard-value-names" "-main-file-name" "main.cpp" "-mrelocation-model" "pic" "-pic-level" "2" "-mframe-pointer=none"
"-fmath-errno" "-fno-rounding-math" "-mconstructor-aliases" "-mms-bitfields" "-munwind-tables" "-target-cpu" "x86-64" "-tune-cpu" "generic"
"-debugger-tuning=gdb" "-v" "-fcoverage-compilation-dir=C:\\Users\\gcvan\\testProgram" "-resource-dir" "C:/msys64/clang64/lib/clang/13.0.0"
"-I" "include\\" "-internal-isystem" "C:/msys64/clang64/x86_64-w64-mingw32/include/c++/v1" "-internal-isystem" "C:/msys64/clang64/include/c++/v1"
"-internal-isystem" "C:/msys64/clang64/lib/clang/13.0.0/include" "-internal-isystem" "C:/msys64/clang64/x86_64-w64-mingw32/include"
"-internal-isystem" "C:/msys64/clang64/include" "-fdeprecated-macro" "-fdebug-compilation-dir=C:\\Users\\gcvan\\testProgram" "-ferror-limit"
"19" "-fmessage-length=120" "-fno-use-cxa-atexit" "-fgnuc-version=4.2.1" "-fcxx-exceptions" "-fexceptions" "-exception-model=seh"
"-fcolor-diagnostics" "-faddrsig" "-o" "C:/Users/gcvan/AppData/Local/Temp/main-c1d43f.o" "-x" "c++" ".\\main.cpp"
"C:/msys64/clang64/bin/ld.lld" "-m" "i386pep" "-Bdynamic" "-o" "a.exe" "C:/msys64/clang64/x86_64-w64-mingw32/lib/crt2.o"
"C:/msys64/clang64/x86_64-w64-mingw32/lib/crtbegin.o" "-Llib\\" "-LC:/msys64/clang64/x86_64-w64-mingw32/lib" "-LC:/msys64/clang64/lib"
"-LC:/msys64/clang64/x86_64-w64-mingw32/sys-root/mingw/lib" "-LC:/msys64/clang64/lib/clang/13.0.0/lib/windows" "-LC:\\cppLibraries" "-lglfw3"
"C:/Users/gcvan/AppData/Local/Temp/main-c1d43f.o" "-lc++" "-lmingw32" "C:/msys64/clang64/lib/clang/13.0.0/lib/windows/libclang_rt.builtins-x86_64.a"
"-lunwind" "-lmoldname" "-lmingwex" "-lmsvcrt" "-ladvapi32" "-lshell32" "-luser32" "-lkernel32" "-lmingw32"
"C:/msys64/clang64/lib/clang/13.0.0/lib/windows/libclang_rt.builtins-x86_64.a" "-lunwind" "-lmoldname" "-lmingwex" "-lmsvcrt" "-lkernel32"
"C:/msys64/clang64/x86_64-w64-mingw32/lib/crtend.o"
| Well, it seems I have a lot to learn about command line compiling/linking.
I fixed it by adding -lgdi32 to the compile tags:
clang++ -Iinclude\ -Llib\ -lglfw3 -lgdi32 -v .\main.cpp
Got the idea from this thread: https://github.com/ziglang/zig/issues/3319
From the thread, near the bottom, there is some good advice:
When you see undefined symbol: __imp_CreateDCW the trick is to look up what DLL that is in. A duck duck go search lands us at https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-createdcw which says at the bottom it is in Gdi32.dll. So you need addSystemLibrary("Gdi32").
For some reason I assumed all the undefined function calls were from glfw, but they aren't, they are from the GDI32 Win32 library.
Just goes to show, for anyone at my experience level, you should probably make sure to google ALL relevant text from your errors and don't make assumptions about the provenance of things..
|
70,132,122 | 70,140,174 | Merge Sort on Doubly Linked List | How do I merge 2 given DLists without having to sort them first?
My Sort function doesn't seem to work (it doesn't merge items) when I display on screen
DoublyLinkedList MergeSort(DoublyLinkedList &ls1, DoublyLinkedList &ls2)
{
DoublyLinkedList ls;
Initial(ls);
if(isEmpty(ls1))
return ls2;
if(isEmpty(ls2))
return ls1;
if(ls1.head->data <= ls2.head->data)
{
InsertLast(ls, ls1.head->data);
RemoveFirst(ls1);
}
else
{
InsertLast(ls, ls2.head->data);
RemoveFirst(ls2);
}
ls = MergeSort(ls1, ls2);
return ls;
}
Here my main
int main()
{
DoublyLinkedList ls1,ls2,ls;
Initial(ls1);
Initial(ls2);
Initial(ls);
InsertLast(ls1, 9);
InsertLast(ls1, 5);
InsertLast(ls1, 1);
InsertLast(ls1, 4);
InsertLast(ls1, 3);
InsertLast(ls2, 12);
InsertLast(ls2, 6);
InsertLast(ls2, 2);
ls=MergeSort(ls1, ls2);
Print(ls);
return 0;
}
Outptut: 9 5 1 4 3 12 6 2
| After consulting the comments I've fixed the function. Reusing QSort to sort the given lists
DoublyLinkedList MergeSort(DoublyLinkedList &ls1, DoublyLinkedList &ls2)
{
DoublyLinkedList ls;
Initial(ls);
if(isEmpty(ls1))
return ls2;
else if(isEmpty(ls2))
return ls1;
QuickSort(ls1);
QuickSort(ls2);
Node *p = ls1.head;
Node *q = ls2.head;
while(p != NULL && q != NULL)
{
if(p->data <= q->data)
{
InsertLast(ls, p->data);
p = p->next;
}
else
{
InsertLast(ls, q->data);
q = q->next;
}
}
while(p != NULL)
{
InsertLast(ls, p->data);
p = p->next;
}
while(q != NULL)
{
InsertLast(ls, q->data);
q = q->next;
}
return ls;
}
Here my sub function(InsertLast)
void InsertLast(DoublyLinkedList &ls, int data)
{
Node *p = CreateNode(data);
if(p == NULL)
return;
if(isEmpty(ls))
{
ls.head = ls.tail = p;
}
else
{
ls.tail->next = p;
p->prev = ls.tail;
ls.tail = p;
}
}
|
70,132,700 | 70,132,794 | Is it possible that we can call the parent's class method through a child class in main method? | I have created a program in which there are two classes i.e., mother and daughter. Daughter class have inherited from mother class. Both classes has same method name but they print different data. Now in main method I have created an object of daughter class and called the display() through daughter's object and it is overriding mother's display() method.
Now I want to call mother's display() method in main method through daughter's object, So how can we do this? Is it possible to do this?
I have tried to do that but it is showing an Error (see that in last 3rd line of code)
#include <iostream>
using namespace std;
class mother{
public:
void display(){
cout<<"Mother"<<endl;
}
};
class daughter : public mother{
public:
void display(){
cout<<"Daughter"<<endl;
}
};
int main(){
daughter rita;
mother mother;
rita.display();
mother::rita.display(); //error
return 0;
}
| You were very close.
rita.mother::display();
https://ideone.com/WZ7j8C
|
70,132,769 | 70,132,928 | when I build and execute code the console is shutting immediately on codeblock C++ | I tried some solves that system("pause") / adding getcha() but none of them worked.
#include <iostream>
using namespace std;
int main() {
cout << "hello world" << endl;
return 0;
}
What should I do?
| Your code is most definitely valid. The reason it's shutting down is just the way Code::Blocks is set up.
You can follow the instructions here to make the console stay open after executing the program.
|
70,133,089 | 70,133,151 | Why do we have to use int a[][10] when passing 2d arrays to functions? | I want to pass a 2d array to a function, and I know how to do it
int function(int a[][10])
The problem is, I dont like working with stuff I dont understand, so I would like to understand why do we have to use "int a[][10]" instead of "int a[10][10]".
| First the function parameter a is a pointer to an array of size 10 having elements of type int. That is, the parameter a is not an array as you might be thinking.
This is called type decay as quoted below:
Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.
You asked
why do we have to use "int a[][10]" instead of "int a[10][10]".
It doesn't matter if you use int a[][10] or int a[10][10] because in both cases the parameter a is a pointer to an array of size 10 having elements of type int.
If you want to pass a 1D array of int elements you can use templates as shown below in version 1:
Version 1: Pass 1D array by reference
#include <iostream>
template<int N>
int function(int (&a)[N])// a is a reference to a 1D array of size N having elements of type int
{
return 5; //return something according to your needs
}
int main()
{
int arr[3] = {0};
function(arr);
return 0;
}
Version 2: Pass a 2D array by reference
#include <iostream>
template<int N, int M>
int function(int (&a)[N][M])// a is a reference to a 2D array
{
return 5; //return something according to your needs
}
int main()
{
int arr[10][10];
function(arr);
return 0;
}
|
70,133,131 | 70,133,219 | How to read a single character from stdin | I need to make a program that will write A+B if the symbol is +, A-B if the symbol is -, but I dont know how to declare a variable that is + or -. Thanks in advance!
| strangely enough I can't find a proper duplicate.
#include <iostream>
int main(int argc, char **argv)
{
char c;
std::cin >> c;
std::cout << "this is the char I got: " << c << "\n";
return 0;
}
compile your program with
$ g++ main.cpp -o main
and then run it:
$ ./main
+
this is the char I got: +
|
70,133,171 | 70,133,218 | When I am pass the array as arguments then I am faceing this error invalid types 'int[int]' in c++ | I am new to c++. can anyone guide me on how I can pass the array in functions?
basically, I am trying to find a number with a linear search and print the index of that number in c++
// linear search
#include <iostream>
using namespace std;
int search(int arr, int n, int x)
{
int i=0;
for (i = 0; i < n; i++){
if (arr[i] == x){
return i;}
}
return -1;
}
// Driver code
int main(void)
{
int size;
int temp;
cout << "Enter Size of Arry";
cin >> size;
int arr[size];
for(int i=0;i<size;i++){
cout << "Enter a " << i << "Element of your arry : ";
cin >> temp;
arr[i]=temp;
}
cout << "Enter the number that you will find index";
int x;
cin >> x;
// Function call
int result = search(arr, size, x);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
this is the error
Q1.cpp: In function 'int search(int, int, int)':
Q1.cpp:9:12: error: invalid types 'int[int]' for array subscript
if (arr[i] == x){
^
Q1.cpp: In function 'int main()':
Q1.cpp:35:34: error: invalid conversion from 'int*' to 'int' [-fpermissive]
int result = search(arr, size, x);
^
| For starters variable length arrays like this
int arr[size];
is not a standard C++ feature. Instead it would be much better to use the standard container std::vector<int> in a C++ program.
Secondly the function declaration is incorrect. The first parameter is declared as having the type int.
int search(int arr, int n, int x)
You need to declare the function the following way
int search(int arr[], int n, int x)
or equivalently
int search(int *arr, int n, int x)
Pay attention to that there is standard algorithm std::find in C++ that performs searching an element in a container.
|
70,133,448 | 70,134,605 | Reference to a Structure | I read this portion from a book called C++ Primer Plus (Page no. 400. Chapter:8 - Adventures in Functions)
A second method is to use new to create new storage. You've already seen examples in which new creates space for a string and the function returns a pointer to that space.
Here's how you chould do something similar with a referece:
const free_throws & clone(free_throw & ft)
{
free_throws * ptr;
*ptr = ft;
return *ptr;
}
The first statement creates a nameless free_throw structure. The pointer ptr points to the structure, so *ptr is the structure. The code appears to return the structure , but the function declaration indicates that the function really reutrns a reference to this structure. You could use this function this way:
free_throw & jolly = clone(three);
This makes jolly a reference to the new structure. There is a problem with this approach: YOu should use delete to free memory allocated by new when the memory is no longer needed. A call to clone() conceals the call to new, making it simpler to forget to use delete later.
My doubts:
As far as I know for best practices you should never dereference a pointer without initializing it and declaring a pointer to certain structure will only allocate space for the pointer only not for the whole structure, you must allocate space separately for the structure.
According to this book the declaring a pointer automatically allocates space to the whole structure and the pointer is dereferenced without initializing.
How the new operator is automatically called when calling the function ?
|
As far as I know for best practices you should never dereference a pointer without initializing it
That's not just a "best practice", but it's absolutely mandatory to not do so. You must never indirect through an uninitiliased pointer.
How the new operator is automatically called when calling the function ?
new operator isn't called.
free_throws * ptr;
The first statement creates a nameless free_throw structure.
This is completely wrong. The first statement creates a pointer, and no instance of a structure at all. The quoted text doesn't match the code.
free_throw & jolly = clone(three);
This makes jolly a reference to the new structure.
This is also wrong. clone returns a reference to const, and the reference to non-const jolly cannot be bound to it. This initialisation is ill-formed.
I would assume that the code is a mistake, and there was an intention to use new in there, but the author forgot. Most important part to understand is in the third quote that explains that the function has a problem; As such, the function is useless even if it were "fixed" to use new as was probably intended.
|
70,133,575 | 70,133,883 | OpenMP nested loop task parallelism, counter not giving correct result | I am pretty new in openMP. I am trying to parallelize the nested loop using tasking but it didn't give me the correct counter output. Sequential output is "Total pixel = 100000000". Can anyone help me with that?
Note: I have done this using #pragma omp parallel for reduction (+:pixels_inside) private(i,j). This works fine now I want to use tasking.
what I have try so far:
#include<iostream>
#include<omp.h>
using namespace std;
int main(){
int total_steps = 10000;
int i,j;
int pixels_inside=0;
omp_set_num_threads(4);
//#pragma omp parallel for reduction (+:pixels_inside) private(i,j)
#pragma omp parallel
#pragma omp single private(i)
for(i = 0; i < total_steps; i++){
#pragma omp task private(j)
for(j = 0; j < total_steps; j++){
pixels_inside++;
}
}
cout<<"Total pixel = "<<pixels_inside<<endl;
return 0;
}
| First of all you need to declare for OpenMP what variables you are using and what protection do they have. Generally speaking your code has default(shared) as you didn't specified otherwise. This makes all variables accessible with same memory location for all threads.
You should use something like this:
#pragma omp parallel default(none) shared(total_steps, pixels_inside)
[...]
#pragma omp task private(j) default(none) shared(total_steps, pixels_inside)
Now, only what is necessary will be used by threads.
Secondly the main problem is that you don't have critical section protection. What this means, that when threads are running they may wish to use shared variable and race condition happens. For example, you have thread A and B with variable x accessible to both (a.k.a. shared memory variable). Now lets say A adds 2 and B adds 3 to the variable. Threads aren't same speed so this may happen, A takes x=0, B takes x=0, A adds 0+2, B adds 0+3, B returns data to memory location x=3, A returns data to memory location x=2. In end x = 2. The same happens with pixels_inside, as thread takes variable, adds 1 and returns it back from where it got it. To overcome this you use measurements to insure critical section protection:
#pragma omp critical
{
//Code with shared memory
pixels_inside++;
}
You didn't needed critical section protection in reduction as variables in recution parameters have this protection.
Now your code should look like this:
#include <iostream>
#include <omp.h>
using namespace std;
int main() {
int total_steps = 10000;
int i,j;
int pixels_inside=0;
omp_set_num_threads(4);
//#pragma omp parallel for reduction (+:pixels_inside) private(i,j)
#pragma omp parallel default(none) shared(total_steps, pixels_inside)
#pragma omp single private(i)
for(i = 0; i < total_steps; i++){
#pragma omp task private(j) default(none) shared(total_steps, pixels_inside)
for(j = 0; j < total_steps; j++){
#pragma omp critical
{
pixels_inside++;
}
}
}
cout<<"Total pixel = "<<pixels_inside<<endl;
return 0;
}
Although I would suggest using reduction as it has better performance and methods to optimize that kind of calculations.
|
70,133,808 | 70,134,381 | SFML slow when drawing more than 500 shapes | I am new to SFML and I would like to implement a fluid boids simulation. However, I realized that when more than 500 shapes are drawn at the same time, the fps drop quickly.
How can I improve the code below to make it much faster to run?
#include <SFML/Graphics.hpp>
#include <vector>
#include <iostream>
sf::ConvexShape newShape() {
sf::ConvexShape shape(3);
shape.setPoint(0, sf::Vector2f(0, 0));
shape.setPoint(1, sf::Vector2f(-7, 20));
shape.setPoint(2, sf::Vector2f(7, 20));
shape.setOrigin(0, 10);
shape.setFillColor(sf::Color(49, 102, 156, 150));
shape.setOutlineColor(sf::Color(125, 164, 202, 150));
shape.setOutlineThickness(1);
shape.setPosition(rand() % 800, rand() % 600);
shape.setRotation(rand() % 360);
return shape;
}
int main() {
sf::Clock dtClock, fpsTimer;
sf::RenderWindow window(sf::VideoMode(800, 600), "Too Slow");
std::vector<sf::ConvexShape> shapes;
for (int i = 0; i < 1000; i++) shapes.push_back(newShape());
while (window.isOpen()) {
window.clear(sf::Color(50, 50, 50));
for (auto &shape : shapes) { shape.rotate(0.5); window.draw(shape); }
window.display();
float dt = dtClock.restart().asSeconds();
if (fpsTimer.getElapsedTime().asSeconds() > 1) {
fpsTimer.restart();
std::cout << ((1.0 / dt > 60) ? 60 : (1.0 / dt)) << std::endl;
}
}
}
I have the following performance:
Shapes FPS
10 60
100 60
500 60
600 60
700 55
800 50
900 45
1000 21
My goal is to have about 5k boids on the screen.
EDIT
I am building the project on Windows 11 under WSL2 with vGPU enabled. When testing natively on Windows 11 with Visual Studio I get much better performance (I can run 5k boids at 60 FPS)
| The problems are a lot of draw calls. That is slow part of this program. In order to fix this, we can put all triangles into single vertex array and call draw upon only that array. That way we will speed up program. Problem with it is that you must implement your own rotate method. I implemented the method below and edited so the function returns triangles in single vertex array.
#include <SFML/Graphics.hpp>
#include <iostream>
//This function returns vertex array by given number of triangles
sf::VertexArray newShape(int numberOfTriangles) {
sf::VertexArray shape(sf::Triangles);
//we are going trough every point in each triangle
for (int i=0;i<3*numberOfTriangles;i++){
//creating points of triangles as vertexes 1, 2 and 3
sf::Vertex v1(sf::Vector2f(rand() % 800, rand() % 600));
sf::Vertex v2(sf::Vector2f(v1.position.x - 7, v1.position.y - 20));
sf::Vertex v3(sf::Vector2f(v1.position.x + 7, v1.position.y - 20));
//setting color
v1.color = v2.color = v3.color = sf::Color(49, 102, 156, 150);
//rotating for random angle
sf::Transform transform;
transform.rotate(rand()%90, (v2.position.x + v3.position.x) / 2,v1.position.y - 10);
v1.position = transform.transformPoint(v1.position);
v2.position = transform.transformPoint(v2.position);
v3.position = transform.transformPoint(v3.position);
//appending them into vertex array
shape.append(v1);
shape.append(v2);
shape.append(v3);
}
return shape;
}
//rotate function finds the middle of 3 vertexes and rotates them
void rotate(sf::VertexArray& array, double angle){
for (int i=0;i<array.getVertexCount();i+=3){
sf::Transform transform;
transform.rotate(angle, (array[i+1].position.x + array[i+2].position.x) / 2, (array[i].position.y + array[i+1].position.y)/2);
array[i].position = transform.transformPoint(array[i].position);
array[i+1].position = transform.transformPoint(array[i+1].position);
array[i+2].position = transform.transformPoint(array[i+2].position);
}
}
int main() {
sf::Clock dtClock, fpsTimer;
sf::RenderWindow window(sf::VideoMode(800, 600), "Too Slow");
//creating new array with 30000 triangles
sf::VertexArray shapes = newShape(30000);
window.setFramerateLimit(60);
while (window.isOpen()) {
//event to close window on close button
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear(sf::Color(50, 50, 50));
//no need for for now, as you can rotate them all in function and draw them together
rotate(shapes,5);
window.draw(shapes);
window.display();
float dt = dtClock.restart().asSeconds();
if (fpsTimer.getElapsedTime().asSeconds() > 1) {
fpsTimer.restart();
std::cout << ((1.0 / dt > 60) ? 60 : (1.0 / dt)) << std::endl;
}
}
}
The bottleneck now is not drawing but rotating, i tested this code with 100000 triangles and im getting around 45 fps. With 1000000 i am getting bad framerate because of rotation.
|
70,133,836 | 70,133,972 | Why doesn't Code::Blocks build my .exe file? | I have just installed a fresh Code::Blocks instance, however the build button doesn't work: I have pressed it many time to build the .exe file, but when I try to run it asks me to build it again.
The "Yes" button on the pop-up dialog that asks me to build doesn't do anything.
My complier's installation directory is C:\Program Files\CodeBlocks\MinGW
I'm using Code::Blocks 20.03 with MinGW installation pack
| If you have a version of GCC as compiler (such as MingW for Windows), chances are it will come with support for the most recent version of C++ disabled by default. This can be explicitly enabled by going to Settings->Compiler
Example
And here, within Global compiler settings, in Compiler settings tab, check the box Have g++ follow the C++11 ISO C++ language standard
Example
|
70,134,773 | 70,135,161 | Custom stream manipulator that passes a character to operator overload | I'm toying around with shift/io stream operator overloads and I was wondering if there is a way to pass additional arguments to the function, while still defining a default value for simpler syntax?
Considering the simple example:
#include <vector>
#include <iostream>
inline std::ostream& operator<<(std::ostream& ostream, const std::vector< int >& data) {
ostream << data[0];
for (int idx = 1; idx < data.size(); idx++) {
ostream << "," << data[idx]; // pass ',' as argument?
}
return ostream;
}
I'm looking to pass the delimiter character , to the function e.g. perhaps through a stream modifier:
std::cout << std::vector<int>(3, 15) << std::endl; // 15,15,15
std::cout << delimiter(;) << std::vector<int>(3,15) << std::endl; // 15;15;15
I've written a simple class that does this, but the resulting syntax is not very clean (requires forcing member operator overload to be called first):
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
class formatted{
public:
explicit formatted(const std::string& sequence = ",") : delimiter(sequence) { }
template < typename T >
std::string operator<<(const T& src) const {
std::stringstream out;
if (src.size()) {
out << src[0];
for (int i = 1; i < src.size(); i++) {
out << delimiter << src[i];
}
}
return out.str();
}
protected:
std::string delimiter;
};
template < typename T >
inline std::ostream& operator<<(std::ostream& ostream, const std::vector< T >& data) {
ostream << (formatted() << data);
return ostream;
}
int main(int argc, char const *argv[]) {
std::vector< int > data(10, 5);
std::cout << data << std::endl; // 5,5,5...5,5
std::cout << (formatted("/") << data) << std::endl; // 5/5/5...5/5
return 0;
}
Is there a way to simplify this, without the need of a helper class, or through the use of conventional stream manipulators?
| Minor improvements of the current design
What you are doing is possible and can't be simplified much further. If you want to stick to your current implementation, I recommend fixing the following issues:
Unnecessary copy of entire string
Use
return std::move(out).str();
to prevent copying the entire string in the stringstream at the end (since C++20).
Signed/unsigned comparison
for (int i = 1; i < data.size(); ...)
results in a comparison between signed and unsigned, which results in compiler warnings at a sufficient warning level.
Prefer std::size_t i.
Unconstrained stream insertion operator
operator<<(const T&)
is not constrained and would accept any type, even though it only works for vectors.
Prefer:
operator<<(const std::vector<T>&)
Using std::string instead of std::string_view
const std::string& sequence = ","
results in the creation of an unnecessary string, possibly involving heap allocation, even when we use a string literal such as ",".
Normally we would prefer std::string_view, but here, you are storing this sequence in the class. This can create problems because std::string_view has no ownership over the string, so the lifetime of the string could expire before you use the view.
This problem is inherent to your design and can not be easily resolved.
Alternative design
Calling formatted a stream manipulator would be inaccurate, because stream manipulators are functions which accept and return a basic_ios (or derived type). Your formatted type is just some type with an operator overload for <<, but you could just as well do:
std::cout << vector_to_string(data, "/");
where "/" would default to "," if no argument is provided.
The problem is that we are still not using the stream for outputting the characters, but we first have to create a string, write the vector contents to it, and then write the string into the stream.
Instead, we can make a function that accepts the stream as its first parameter and writes directly to it.
The advantages include:
dropping #include <sstream>, potentially just including <iosfwd>
performance improvement
possibly no heap allocations
no unnecessary string copy (before C++20)
overall shorter code
This design as a regular function has precedent in the standard library as well. A classic examples is std::getline with the signature:
template < class CharT, ...>
std::basic_istream<CharT, ...>& getline( std::basic_istream<CharT, ...>& input,
std::basic_string<CharT, ...>& str,
CharT delim );
With this design, we can create much more concise code, which also resolves the issues of:
being unable to use std::string_view
having to use a std::string to store the whole printed vector
#include <string>
#include <vector>
#include <iostream>
template < typename T >
std::ostream& print(std::ostream& ostream,
const std::vector< T >& data,
std::string_view delimiter = ",")
{
if (not data.empty()) {
ostream << data.front();
for (std::size_t i = 1; i < data.size(); i++) {
ostream << delimiter << data[i];
}
}
return ostream;
}
int main(int argc, char const *argv[])
{
std::vector< int > data(10, 5);
print(std::cout, data) << std::endl;
print(std::cout, data, "/") << std::endl;
}
Further generalization for any range
We can generalize this code so that it works for any range that provides an input iterator, not just std::vector.
This means that we can use it for types such as std::array, std::string, std::vector, std::list, etc.
template <typename Range>
std::ostream& print(std::ostream& ostream,
const Range& range,
std::string_view delimiter = ",")
{
auto begin = range.begin();
auto end = range.end();
if (begin != end) {
ostream << *begin;
while (++begin != end) {
ostream << delimiter << *begin;
}
}
return ostream;
}
|
70,134,955 | 70,135,239 | Get SDL2 Mouse Position | How would I get the position of the mouse in c++ SDL2? I found this wiki however I'm not really sure what it means and how would I get the x and y in int form?
https://wiki.libsdl.org/SDL_GetMouseState
| Call the function described at the link you found; with pointers to the two int variables which you want to receive the coordinates.
Simplified, the function works like this one:
void SetXto5(int* x)
{*x = 5;}
i.e. the variable which your parameter points to will receive a value.
(This skips the check for NULL pointer, which is implied in the documentation.)
This does of course require the SDL environment to be correctly set up and initialised. I assume from your comments that you do not ask about that background part.
|
70,135,118 | 70,162,787 | How to rotate a QGraphicsPixmap around a point according to mouseMoveEvent? | I want rotate a QGraphicsPixmapItem around a point according to mouse position.
So i tried this:
void Game::mouseMoveEvent(QMouseEvent* e){
setMouseTracking(true);
QPoint midPos((sceneRect().width() / 2), 0), currPos;
currPos = QPoint(mapToScene(e->pos()).x(), mapToScene(e->pos()).y());
QPoint itemPos((midPos.x() - cannon->scenePos().x()), (midPos.y() - cannon->scenePos().y()));
double angle = atan2(currPos.y(), midPos.x()) - atan2(midPos.y(), currPos.x());
cannon->setTransformOriginPoint(itemPos);
cannon->setRotation(angle); }
But the pixmap moves a few of pixels.
I want a result like this:
| Besides the mixup of degrees and radians that @rafix07 pointed out there is a bug in the angle calculation. You basically need the angle of the line from midPos to currPos which you calculate by
double angle = atan2(currPos.y() - midPos.y(), currPos.x() - midPos.x());
Additionally the calculation of the transformation origin assumes the wrong coordinate system. The origin must be given in the coordinate system of the item in question (see QGraphicsItem::setTransformOriginPoint), not in scene coordinates. Since you want to rotate around the center of that item it would just be:
QPointF itemPos(cannon->boundingRect().center());
Then there is the question whether midPos is actually the point highlighted in your image in the middle of the canon. The y-coordinate is set to 0 which would normally be the edge of the screen, but your coordinate system may be different.
I would assume the itemPos calculated above is just the right point, you only need to map it to scene coordinates (cannon->mapToScene(itemPos)).
Lastly I would strongly advise against rounding scene coordinates (which are doubles) to ints as it is done in the code by forcing it to QPoints instead of QPointFs. Just use QPointF whenever you are dealing with scene coordinates.
|
70,135,192 | 70,135,370 | C++ macro time arithmetic | I'm working on a wgl loader and typedef'd each openGL function that I use like this:
/*Let's say I'm defining n functions*/
typedef return_t (*f1)(params)
f1 _glFunc1;
#define glFunc1(params) _glFunc1(params)
...
typedef return_t (*fn)(params)
fn _glFuncn;
#define glFuncn(params) _glFuncn(params)
Then to get the definitions of these functions I have to use wglGetProcAddress or GetProcAddress and then cast the result to f1, f2 ...
I tried to automate the casting with this macro:
#define GetFuncDef(glFunc) _##glFunc = (f##(__LINE__ - startingLineNumber + 1))GetProcAddress(#glFunc)
Where startingLineNumber is the first line that I use this macro in(in my case it's 22),
but the preprocessor does not compute __LINE__ - startingLineNumber.
Is there some way to force it to do so?
EDIT:
startingLineNumber isn't a variable, macro etc. It's written out as a literal number in my code. like this:
#define GetFuncDef(glFunc) _##glFunc = (f##(__LINE__ - 22 + 1))GetProcAddress(#glFunc), where 22 would be startingLineNumber
| Similar to C Preprocessor output int at Build first you have to implement operations:
typedef return_t (*f1)(params)
typedef return_t (*f2)(params)
void *GetProcAddress(charr *);
#define SUB_10_0 10
#define SUB_10_1 9
#define SUB_10_2 8
// etc. for each each possible combination, 1000 of lines ...
#define SUB_21_20 1
// etc. for each each possible combination, 1000 of lines ...
#define SUB_IN(a, b) SUB_##a##_##b
#define SUB(a, b) SUB_IN(a, b)
#define CONCAT_IN(a, b) a##b
#define CONCAT(a, b) CONCAT_IN(a, b)
#define startingLineNumber 20
#define GetFuncDef(glFunc) (CONCAT(f, SUB(__LINE__, startingLineNumber)))GetProcAddress(#glFunc)
int main() {
f1 a = GetFuncDef();
}
Then gcc -E outputs:
typedef return_t (*f1)(params)
typedef return_t (*f2)(params)
void *GetProcAddress(charr *);
int main() {
f1 a = (f1)GetProcAddress("");
}
In a similar fashion mentioned here Boost and P99 libraries can be used.
|
70,135,306 | 70,135,397 | Problem about c++ pointers assigning values | I have a confusion about the pointers. as the code shows below, CreditCard is a class defined in the head file, and we're defining a vector that contains 10 CreditCard pointers. After defining, we assign 3 new cards to the vector. It is clear that the vector's elements should be type pointer to CreditCard, however we actually assign CredicCard objects rather than pointers to it. Besides, what is "new" infront of each CreditCard? Could anyone explain it to me? Thank you!
( the code is from Data Structures and Algorithms in C++ 2nd Edition by Michael T. Goodrich (Author), Roberto Tamassia (Author), David M. Mount (Author) )
vector<CreditCard*> wallet(10); // vector of 10 CreditCard pointers
// allocate 3 new cards
wallet[0] = new CreditCard("5391 0375 9387 5309", "John Bowman", 2500);
wallet[1] = new CreditCard("3485 0399 3395 1954", "John Bowman", 3500);
wallet[2] = new CreditCard("6011 4902 3294 2994", "John Bowman", 5000);
|
After defining, we assign 3 new cards to the vector. It is clear that the vector's elements should be type pointer to CreditCard, however we actually assign CredicCard objects rather than pointers to it.
No we are not assigning 3 new cards to the vector. Instead we are assigning the pointers to CreditCard objects created on heap. Take the below example into consideration:
Case I
new CreditCard("5391 0375 9387 5309", "John Bowman", 2500);
The above statement does two things:
creates a CreditCard object on the heap
returns a pointer to that created object
Case II
Now lets take a look at the statement in your code snippet:
wallet[0] = new CreditCard("5391 0375 9387 5309", "John Bowman", 2500);
This statement does three things:
creates a CreditCard object on the heap
returns a pointer to that created object
assign the pointer that was returned in step 2 to wallet[0]
Case III
Similarly,
wallet[1] = new CreditCard("3485 0399 3395 1954", "John Bowman", 3500);
involves 3 things:
creates a CreditCard object on the heap
returns a pointer to that created object
assign the pointer that was returned in step 2 to wallet[1]
You can check out Objects on a stack vs Objects on a heap in C++ for more about heap and stack.
Also, note that when you're creating objects on the heap and not using smart pointers, then you must free the memory using delete.
More Examples
Creating Objects on Stack
//create a vector of CreditCard objects instead of creating a vector pointers to CreditCard objects
std::vector<CreditCard> wallet(10); //create a vector of size 10 of CreditCard objects
wallet[0] = CreditCard("5391 0375 9387 5309", "John Bowman", 2500);
wallet[1] = CreditCard("3485 0399 3395 1954", "John Bowman", 3500);
wallet[2] = CreditCard("6011 4902 3294 2994", "John Bowman", 5000);
Note in the above code snippet i have not used the keyword new. So we create 3 CreditCard objects and then assign those objects to wallet[0], wallet[1], wallet[2].
Creating objects on Heap
//create a vector of pointers to CreditCard objects instead of creating a vector of CreditCard objects
vector<CreditCard*> wallet(10); // vector of 10 CreditCard pointers
// Create 3 CreditCard objects on heap and then assign the pointer returned to them to the left hand side`
wallet[0] = new CreditCard("5391 0375 9387 5309", "John Bowman", 2500);
wallet[1] = new CreditCard("3485 0399 3395 1954", "John Bowman", 3500);
wallet[2] = new CreditCard("6011 4902 3294 2994", "John Bowman", 5000);
In the above code snippet, the we have used the keyword new(unlike last example). The effect of using the keyword new is that we create an object on the heap and then a pointer to that object is returned which is assigned to wallet[0], wallet[1], wallet[2].
|
70,135,490 | 70,142,236 | How can i combine multiple variadic templates or split parameter pack? | I am currently trying to define a generic multiplication operator for std::functions. I want to do this using multiple variadic templates. The partial specializations look as follows:
template <typename... _Type> using op_Type = typename std::function<u64(u64, _Type...)>;
inline auto operator*(const op_Type<>& f, const op_Type<>& g) -> op_Type<> {
return [f, g](u64 num) {
return f(g(num));
};
}
template <typename _Ty1, typename _Ty2>
inline auto operator*(const op_Type<_Ty1>& f, const typename op_Type<_Ty2>& g)
-> op_Type<_Ty1, _Ty2> {
return [f, g](u64 num, _Ty1 arg1, _Ty2 arg2) {
return f(g(num, arg2), arg1);
};
}
template <typename _Tyf1, typename _Tyf2, typename _Tyg1, typename _Tyg2>
inline auto operator*(const op_Type<_Tyf1, _Tyf2>& f,
const typename op_Type<_Tyg1, _Tyg2>& g)
-> op_Type<_Tyf1, _Tyf2, _Tyg1, _Tyg2> {
return [f, g](u64 num, _Tyf1 argF1, _Tyf2 argF2, _Tyg1 argG1, _Tyg2 argG2) {
return f(g(num, argG1, argG2), argF1, argF2);
};
}
But what I would need is the same behavior for any generic std::functions taking an u64 value and any number of other arguments, which should look as follows:
template <typename... _Ty1, template <typename...> class op1
, typename... _Ty2, template <typename...> class op2
, typename... _RetTy, template<typename...> class opRet>
inline auto operator*(const op1<_Ty1...>& f, const op2<_Ty2...> g) -> opRet<_RetTy...> {
const int size1 = sizeof...(_Ty1);
const int size2 = sizeof...(_Ty2);
return [f, g](u64 num, _Ty1 args1..., _Ty2 args2...) {
auto tmp = g(num, std::forward<_Ty1>(args1)...);
return f(tmp, std::forward<_Ty2>(args2)...);
};
}
I also would want to drop the added class templates, but it might not be possible then to use multiple variadic templates, because the compiler don't know when the variadic template ends, right?
I suppose a good workaround would be to split the parameter pack such that:
template <typename... _Ty1, , typename... _Ty2>
inline auto operator*(const op_type<_Ty1...>& f, const op_type<_Ty2...> g) -> opRet<_Ty1...,_Ty2...> {
const int size1 = sizeof...(_Ty1);
const int size2 = sizeof...(_Ty2);
return [f, g](u64 num, variadic template args...) {
auto tmp = g(num, split_args(args, 0, size1 - 1));
return f(tmp, split_args(args, remaining_arguments);
};
}
where split_args returns the arguments between the input indices, but I'm not sure how to implement that, any ideas?
I found a solution like this:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0535r0.html
but I'm not sure if there is an open source code available
EDIT:
IN conclusion I would need a function which looks like:
template <typename... _Ty1, typename... _Ty2>
inline auto operator*(const op_type<_Ty1...>& f, const op_type<_Ty2...> g) -> op_type<_Ty1...,_Ty2...> {
return [f, g](u64 num, _Ty1 args1..., _Ty2 args2...) {
auto tmp = g(num, std::forward<_Ty1>(args1)...);
return f(tmp, std::forward<_Ty2>(args2)...);
};
}
EDIT2:
Usage:
Suppose i have two functions:
auto f(u64 num, int i, int j) -> u64{
return num + (i - j)^i;
}
and
auto g(u64 num, double x){
return num - int(num / x);
}
then the multiplication operator h = f*g should return h as:
auto h(u64 num, int i, int j, double x) -> u64{
num + (i - j)^i - int(num / x);
}
| In hope I got your wishes...
template< typename PACK1, typename PACK2 > struct Combined;
template < typename ... PACK1, typename ... PACK2 >
struct Combined< std::function< uint64_t( uint64_t, PACK1... )>, std::function< uint64_t(uint64_t, PACK2...) > >
{
using OP_TYPE1 = std::function< uint64_t( uint64_t, PACK1... )>;
using OP_TYPE2 = std::function< uint64_t( uint64_t, PACK2... )>;
OP_TYPE1 op1;
OP_TYPE2 op2;
Combined( OP_TYPE1 op1_, OP_TYPE2 op2_ ): op1{ op1_}, op2{ op2_}{}
auto operator( )(uint64_t p1, PACK1... args1, PACK2... args2)
{
return op2( op1( p1, args1...), args2...);
}
};
template < typename OP_TYPE1, typename OP_TYPE2> auto operator*(OP_TYPE1, OP_TYPE2);
template < typename ... PACK1, typename ... PACK2 >
auto operator* ( std::function< uint64_t( uint64_t, PACK1... )> op1, std::function< uint64_t(uint64_t, PACK2...) > op2 )
{
return Combined< std::function< uint64_t( uint64_t, PACK1... )>, std::function< uint64_t(uint64_t, PACK2...)>>{ op1, op2 };
}
// Example funcs
auto f(uint64_t num, int i, int j) -> uint64_t{
return num + ((i - j)^i);
}
uint64_t g(uint64_t num, double x){
return num - int(num / x);
}
int main()
{
std::function fobject = f;
std::function gobject = g;
auto fg = fobject*gobject;
std::cout << fg( 1, 2, 3, 6.66 ) << std::endl;
}
The exmaple misses all what can be optimized with forwarding arguments, moving and so on. It is only for you to catch signatures and taking params from template arguments and so on.
|
70,135,569 | 70,136,598 | c++ std::unordered_map singleton access violation error | template <typename T> class singleton
{
public:
static T* ms_singleton;
singleton()
{
assert(!ms_singleton);
long offset = (long)(T*)1 - (long)(singleton <T>*) (T*) 1;
ms_singleton = (T*)((long)this + offset);
}
virtual ~singleton()
{
assert(ms_singleton);
ms_singleton = 0;
}
static T& Instance()
{
assert(ms_singleton);
return (*ms_singleton);
}
static T* instance_ptr()
{
return (ms_singleton);
}
};
class Test
{
private:
DWORD X;
}
typedef Test* LPTEST;
class TestManager : public singleton<TestManager>
{
public:
TestManager();
virtual ~TestManager();
LPTEST CreateTest(DWORD id);
protected:
private:
std::unordered_map<DWORD, LPTEST> test_map;
};
LPTEST TestManager::CreateTest(DWORD id)
{
LPTEST test = new Test;
if (id)
{
test_map.insert(std::make_pair(id, test));
}
return (test);
}
I created a code similar to this.
when i run the below function.
LPTEST Tested = TestManager::Instance().CreateTest(61);
but "test_map.insert" gives an access violation error.
test_map.insert -> If I turn off the function it works fine.
all codes are normal. why am I having such a problem with std:map like codes.
I would be glad if you help.
| by changing the Singleton code as follows. I solved the problem.
template <typename T> class singleton
{
public:
singleton() {}
~singleton() {}
static T& Instance()
{
static T instance;
return instance;
}
singleton(const singleton&) = delete;
singleton& operator=(const singleton&) = delete;
};
@drescherjm , @UnholySheep
Thanks for your help.
Do you think there is a code in this code that will cause trouble later?
Could this code be better? How?
|
70,135,737 | 70,136,095 | visual studio can't apply clang-format 13 | I'm expecting to use AlignArrayOfStructures, however it's only available in clang-format 13. So I set Custom clang-format.exe to C:/Program Files/LLVM/bin/clang-format.exe.
PS C:\Program Files\LLVM\bin> .\clang-format.exe --version
clang-format version 13.0.0
But I still got a error, it says
| Reading the manual carefully.
AIAS_Right (in configuration: Right)
AIAS_Right is the enum value, corresponding name in the config is Right. Use
AlignArrayOfStructures: Right
|
70,136,031 | 70,136,105 | C++ call a member function of an anonymous object instance? | I have the following piece of code:
map<int, set<int>> my_map;
int my_int1, my_int2;
// some code
set<int> temp;
temp.insert(my_int2);
my_map.insert(make_pair(my_int1, temp));
Is there some way to avoid using the temp (at least just for the code to look nicer, not necessarily for performance) and use an anonymous object? Something like:
my_map.insert(make_pair(my_int1, (set<int>{}).insert(my_int2)));
Except, the above line doesn't compile.
| Not tested but try something like this:
my_map.insert({my_int1, {my_int2}});
Ok, let's sumarize. There is an important thing to know about insert: the insert doesn't insert if key already exists.
//create and initialise inline a map with int keys and string values
map<int, string> x {
{10, "hello"},
{123, "bye"},
{234, "world"}
};
x.insert({567, "alien"}); //inserts an element initialised inline
x.insert({567, "bar"}); //does nothing, according to specs
x[124] = "buzz"; //inserts an element
x[567] = "bar"; //modifies the element with key 567
//create and initialise inline a map with int keys and int values
map<int, string> y {
{10, 1},
{123, 2},
{234, 3}
};
y.insert({567, 4}); //insert an element initialised inline
z[124] = 5; //inserts
z[124] = 6; //modifies the above element
z[125]++; //inserts and modifies, now z[125] is 1
z[125]++; //modifies the above element to 2
It is very flexible. If you create a map of containers
//create and initialise inline a map with int keys and set values
map<int, set<int>> x {
{10, {1, 2, 3}},
{123, {2, 3}},
{234, {1, 2, 3}}}
};
//calling insert on map:
y.insert({567, {4, 5, 6}}); //element 567 has the value {4, 5, 6}
//now this calls insert in the set:
y[567].insert(7); //element 567 exists, so it is modified to {4, 5, 6, 7}
y[568].insert(7); //element 569 doesn't exist, so it is created first
//assign
y[235] = {4, 5, 6}; //element 235 has the value {4, 5, 6}
y[235] = {7, 8, 9}; //element 235 has the value {7, 8, 9}
y[235].insert(10); //element 235 has the value {7, 8, 9, 10}
|
70,136,487 | 70,136,860 | Instantiate an object and pass its name to constructor using c++ macro | Let's say
class A {
A(string name) {
//....
}
}
So when the object is created:
A* objectNumber324 = new A("objectNumber324");
A* objectNumber325 = new A("objectNumber325");
In my case as the object names are pretty long, I am looking for macro to simplify that code to:
CreateA(objectNumber325);
There is some discussion how to pass variable name to a function here. But that is not quite the same thing, as I want to create the object and pass its name to constructor.
| #include <string>
#include <iostream>
#define CreateA(name) \
A* name = new A(#name)
// With type
#define CREATE_WITH_TYPE(type, name) \
type* name = new type(#name)
// With name decoration
#define CREATE_WITH_DECO(type, name) \
type* my_##name = new type(#name)
class A {
public:
A(std::string name){
std::cout << name << " created.\n";
}
};
int main() {
// example
CreateA(objectNumber325);
CREATE_WITH_TYPE(A, objectNumber324);
CREATE_WITH_DECO(std::string, a_string);
delete objectNumber324;
delete objectNumber325;
delete my_a_string;
}
|
70,136,586 | 70,407,297 | Will std::sort always compare equal values? | I am doing the following problem on leetcode: https://leetcode.com/problems/contains-duplicate/
Given an integer array nums, return true if any value appears at least
twice in the array, and return false if every element is distinct.
The solution I came up to the problem is the following:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
try {
std::sort(nums.begin(), nums.end(), [](int a, int b) {
if (a == b) {
throw std::runtime_error("found duplicate");
}
return a < b;
});
} catch (const std::runtime_error& e) {
return true;
}
return false;
}
};
It was accepted on leetcode but I am still not sure if it will always work. The idea is to start sorting nums array and interrupt as soon as duplicate values are found inside comparator. Sorting algorithm can compare elements in many ways. I expect that equal elements will be always compared but I am not sure about this. Will std::sort always compare equal values or sometimes it can skip comparing them and therefore duplicate values will not be found?
|
Will std::sort always compare equal values or sometimes it can skip comparing them and therefore duplicate values will not be found?
Yes, some equal value elements will always be compared if duplicates do exist.
Let us assume the opposite: initial array of elements {e} for sorting contains a subset of elements having the same value and a valid sorting algorithm does not call comparison operator < for any pair of the elements from the subset.
Then we construct same sized array of tuples {e,k}, with the first tuple value from the initial array and arbitrary selected second tuple value k, and apply the same sorting algorithm using the lexicographic comparison operator for the tuples. The order of tuples after sorting can deviate from the order of sorted elements {e} only for same value elements, where in the case of array of tuples it will depend on second tuple value k.
Since we assumed that the sorting algorithm does not compare any pair of same value elements, then it will not compare the tuples with the same first tuple value, so the algorithm will be unable to sort them properly. This contradicts our assumptions and proves that some equal value elements (if they exist in the array) will always be compared during sorting.
|
70,136,614 | 73,967,696 | FrameBuffer.insert() will result in a access violation during loading of EXR image | I have the following function to load a OpenEXR image, which is basically just copied from their examples:
void HDrRenderer::ReadExrImage(
const char fileName[],
Imf::Array2D<half>& rPixels,
Imf::Array2D<half>& gPixels,
Imf::Array2D<float>& zPixels,
int& width, int& height)
{
Imf::InputFile file(fileName);
auto header = file.header();
Imath::Box2i dw = header.dataWindow();
width = dw.max.x - dw.min.x + 1;
height = dw.max.y - dw.min.y + 1;
rPixels.resizeErase(height, width);
gPixels.resizeErase(height, width);
zPixels.resizeErase(height, width);
Imf::FrameBuffer frameBuffer;
frameBuffer.insert("R",
Imf::Slice(Imf::HALF,
(char*)(&rPixels[0][0] - dw.min.x - dw.min.y * width),
sizeof(rPixels[0][0]) * 1,
sizeof(rPixels[0][0]) * width,
1, 1, 0.0));
frameBuffer.insert("G",
Imf::Slice(Imf::HALF,
(char*)(&gPixels[0][0] - dw.min.x - dw.min.y * width),
sizeof(gPixels[0][0]) * 1,
sizeof(gPixels[0][0]) * width,
1, 1, 0.0));
frameBuffer.insert("Z",
Imf::Slice(Imf::FLOAT,
(char*)(&zPixels[0][0] - dw.min.x - dw.min.y * width),
sizeof(zPixels[0][0]) * 1,
sizeof(zPixels[0][0]) * width,
1, 1, FLT_MAX));
file.setFrameBuffer(frameBuffer);
file.readPixels(dw.min.y, dw.max.y);
}
My problem is rather straight forward: Any of the FrameBuffer.insert() methods will crash the program with the following message:
Exception thrown at 0x00007FFDE6BFC1AE (OpenEXR-3_1.dll) in MyAwesomeProgram.exe: 0xC0000005: Access violation reading location 0x0000000000000019.
I have already tried to separate the Slice -> the problem really is somewhere in the insert() method. I'm curious what the reason could be, how to find it and how to solve the issue.
| I had the same problem - and I keep stumbling on it every time I come back to C++ after a break. In visual studio, you cannot run an application in debug mode while using dlls compiled in release mode. Other way is okay. Compile the OpenEXR library in debug mode, debug your app, then compile both in release. Hope this helps someone avoid a couple of days of teeth-gnashing!
Cheers!
|
70,136,711 | 70,484,103 | GSL ODE solver returns -nan although same ODE with same parameters is being solved in python | I use python to solve ODEs using scipy.integrate.odeint. Currently, I am working on a small project where I am using gsl in C++ to solve ODEs. I am trying to solve an ODE but the solver is returning -nan for each time point. Following is my code:
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv2.h>
struct param_type {
double k;
double n;
double m;
double s;
};
int func (double t, const double y[], double f[], void *params)
{
(void)(t); /* avoid unused parameter warning */
struct param_type *my_params_pointer = (param_type *)params;
double k = my_params_pointer->k;
double n = my_params_pointer->n;
double m = my_params_pointer->m;
double s = my_params_pointer->s;
f[0] = m*k*pow(s,n)*pow((y[0]/(k*pow(s,n))),(m-1)/m);
return GSL_SUCCESS;
}
int * jac;
int main ()
{
struct param_type mu = {1e-07, 1.5, 0.3, 250};
gsl_odeiv2_system sys = {func, NULL, 1, &mu};
gsl_odeiv2_driver * d = gsl_odeiv2_driver_alloc_y_new (&sys, gsl_odeiv2_step_rk8pd, 1e-6, 1e-6, 0.0);
int i;
double t = 0.0, t1 = 10.0;
double step_size = 0.1;
double y[1] = { 1e-06 };
gsl_vector *time = gsl_vector_alloc ((t1 / step_size) + 1);
gsl_vector *fun_val = gsl_vector_alloc ((t1 / step_size) + 1);
for (i = 1; i <= t1/step_size; i++)
{
double ti = i * t1 / (t1 / step_size);
int status = gsl_odeiv2_driver_apply (d, &t, ti, y);
if (status != GSL_SUCCESS)
{
printf ("error, return value=%d\n", status);
break;
}
printf ("%.5e %.5e\n", t, y[0]);
gsl_vector_set (time, i, t);
gsl_vector_set (fun_val, i, y[0]);
}
gsl_vector_add(time, fun_val);
{
FILE * f = fopen ("test.dat", "w");
gsl_vector_fprintf (f, time, "%.5g");
fclose (f);
}
gsl_odeiv2_driver_free (d);
gsl_vector_free (time);
gsl_vector_free (fun_val);
return 0;
}
As mentioned here, I don't need jacobian for an explicit solver that's why I passed NULL pointer for the jac function.
When I run the above code, I get -nan values at all time points.
To cross-check, I wrote the program in python which has the same function and same parameters, solved using scipy.integrate.odeint. It runs and provides a plausible answer.
Following my python code:
import numpy as np
from scipy.integrate import odeint
def nb(y, t, *args):
k = args[0]
n = args[1]
m = args[2]
s = args[3]
return m*k*s**n*(y/(k*s**n))**((m-1)/m)
t = np.linspace(0,10,int(10/0.1))
y0 = 1e-06
k = 1e-07
n = 1.5
m = 0.3
s = 250
res = odeint(nb, y0, t, args=(k,n,m,s)).flatten()
print(res)
Could anyone please help me figure out, what I am doing wrong in the C++ code using GSL for solving the ODE?
| Your problem is here:
f[0] = m*k*pow(s,n)*pow((y[0]/(k*pow(s,n))),(m-1)/m);
As the solver proceeds, it may want to sample negative values of y[0]. In Python this makes no problem, in C++ it produces NANs.
To handle this, you can mimic Python's behavior:
auto sign = (y[0] < 0) ? -1.0 : 1.0;
f[0] = sign*m*k*pow(s,n)*pow((std::abs(y[0])/(k*pow(s,n))),(m-1)/m);
or even set sign effectively to 1:
f[0] = m*k*pow(s,n)*pow((std::abs(y[0])/(k*pow(s,n))),(m-1)/m);
After all, raising negative values to noninteger powers is an error unless one considers complex numbers, which is not the case.
Please notice that y[0] was secured with std::abs.
|
70,136,904 | 70,143,344 | How to use curl_blob in libcurl/ c++? | I am trying to use libcurl with c++ and to make requests with mTLS (mutual TLS/ Two Way TLS). Passing the certificates as file paths works. But I would like to use embeded certificates in the source code and not external files. I discovered BLOB options in the curl lib website (example)
There is also an example on the website where curl_blob struct has been used:
CURL *curl = curl_easy_init();
if(curl) {
struct curl_blob stblob;
stblob.data = certificateData; // What to pass here (e.g. from a string)
stblob.len = filesize; // What about here?
stblob.flags = CURL_BLOB_COPY;
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/");
curl_easy_setopt(curl, CURLOPT_SSLCERT_BLOB, &stblob);
curl_easy_setopt(curl, CURLOPT_SSLCERTTYPE, "P12");
curl_easy_setopt(curl, CURLOPT_KEYPASSWD, "s3cret");
ret = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
How to make use of curl_blob struct and its attributes?
| I have found the solution.
stdblob.data requires a char* with the file/string content.
stblob.len requires the length of the string/char array.
This is a simple example:
char* str_to_char_arr(string str)
{
const int n = str.length() + 1;
char* char_array = new char[n + 1];
for (int i = 0; i < n; i++)
char_array[i] = str[i];
return char_array;
}
std::string client_cert_content =
"-----BEGIN CERTIFICATE-----\n"
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
".....\n"
"-----END CERTIFICATE-----";
curl_blob get_client_cert()
{
struct curl_blob stblob;
stblob.data = str_to_char_arr(client_cert_content);
stblob.len = client_cert_content.length();
stblob.flags = CURL_BLOB_COPY;
return stblob;
}
And then add the cert this way:
struct curl_blob client_cert_blob = get_client_cert();
curl_easy_setopt(curl, CURLOPT_SSLCERT_BLOB, &client_cert_blob);
I wanted to use embeded certificates, and this way worked. But the same logic works when reading the char array from a file.
|
70,136,940 | 70,137,641 | can you help me with the copy c'tor for derived class? | I have this base class:
class LevelPlayer
{
protected:
int level;
int id;
public:
LevelPlayer():id(-1){}
LevelPlayer(int level,int id):level(level),id(id){}
virtual ~LevelPlayer()=default;
LevelPlayer(const LevelPlayer&)=default;
LevelPlayer& operator=(const LevelPlayer&)=default;
};
and this derived class:
class GroupPlayer: public LevelPlayer
{
private:
IdPlayer* ptr;
public:
GroupPlayer():LevelPlayer(),ptr(nullptr){}
GroupPlayer(int level,int id,IdPlayer* ptr):LevelPlayer(level,id),ptr(new IdPlayer(*ptr)){}
~GroupPlayer()override=default;
GroupPlayer(const GroupPlayer&);
GroupPlayer& operator=(const GroupPlayer&);
};
and for the copy ctor of the derived one I wrote this:
GroupPlayer::GroupPlayer(const GroupPlayer& player):ptr(new IdPlayer(*(player.ptr))){}
but I am not sure if it's correct ... should I also add LevelPlayer(player) ?
|
I am not sure if it's correct ... should I also add LevelPlayer(player) ?
Yes, the derived class copy constructor needs to call the base class copy constructor explicitly:
GroupPlayer::GroupPlayer(const GroupPlayer& player)
: LevelPlayer(player), ptr(new IdPlayer(*(player.ptr)))
{
}
Since you have implemented the derived class copy constructor, and the base class constructor takes an input parameter, you need to pass in a value for that parameter. If you don't, the base class default constructor will be called instead, and thus level and id won't be copied from player.
|
70,137,010 | 70,137,114 | How to make zero's appear on left side? | I am writing this program, in which we need to convert the input from the user from digits into words. I've written the whole program. The only error I am facing is that when I write e.g. 4200, the zeros aren't appearing. I am a beginner at C++.
while (num > 0)
{
rem = num % 10;
sum = sum * 10 + rem;
num = num / 10;
}
num = sum;
while (num > 0)
{
rem = num % 10;
switch (rem)
{
case 1 :
cout << "One " ;
break;
case 2:
cout << "Two " ;
break;
case 3:
cout << "Three " ;
break;
case 4:
cout << "Four " ;
break;
case 5:
cout << "Five " ;
break;
case 6:
cout << "Six " ;
break;
case 7:
cout << "Seven " ;
break;
case 8:
cout << "Eight " ;
break;
case 9:
cout << "Nine " ;
break;
case 0:
cout << "Zero " ;
break;
Please help me out. How can I print the zeros too?
| Your solution is not optimal. So, I have written a new solution.
Solution
int num;
cin >> num;
vector<string> v;
while (num > 0) {
switch (num % 10) {
case 1:
v.push_back("One");
break;
case 2:
v.push_back("Two");
break;
case 3:
v.push_back("Three");
break;
case 4:
v.push_back("Four");
break;
case 5:
v.push_back("Five");
break;
case 6:
v.push_back("Six");
break;
case 7:
v.push_back("Seven");
break;
case 8:
v.push_back("Eight");
break;
case 9:
v.push_back("Nine");
break;
case 0:
v.push_back("Zero");
break;
}
num /= 10;
}
reverse(v.begin(), v.end());
for (auto a: v) cout << a << " ";
You also can use map instead of switch.
If you get any errors try to write #include <vector>.
Very simple solution
int num;
cin >> num;
string s;
while (num > 0) {
switch (num % 10) {
case 1:
s = "One " + s;
break;
case 2:
s = "Two " + s;
break;
case 3:
s = "Three " + s;
break;
case 4:
s = "Four " + s;
break;
case 5:
s = "Five " + s;
break;
case 6:
s = "Six " + s;
break;
case 7:
s = "Seven " + s;
break;
case 8:
s = "Eight " + s;
break;
case 9:
s = "Nine " + s;
break;
case 0:
s = "Zero " + s;
break;
}
num /= 10;
}
cout << s;
|
70,137,027 | 70,137,320 | RSA-Implementation isn't decrypting correctly | I like to learn and today I decided to finally implement RSA on my own.
Basically from what I can tell my Code should work and it actually does to a certain extent.
However, even though (according to Internet learning sources) the correct keys are calculated and correctly used I get weird outputs. I checked but couldn't find where the problem is, because calculating by hand yields the same results...
So yeah, here's my cryptography.cpp-File:
#include "cryptography.h"
bool prime(const unsigned long long n) {
//max of sqrt(n)
unsigned long long m = 0.5 * n;
for(unsigned int i = 2; i <= m; i++) //check every possible divisor
if(n % i == 0) //wheter it goes in to n perfectly
return false; //n is not prime if such divisor is found
//if no divisor found
return true;
}
bool coprime(unsigned long long p, unsigned long long q) {
//p >= q
if(q > p) {
long long t = p;
p = q;
q = t;
}
//subtract smaller from bigger, keeping gcd
while(q != 0) {
unsigned long long r = p % q;
p = q;
q = r;
}
//gdc == 1
return p == 1;
}
/**
* Finds d for:
* 1 = (d * e) % m
*/
unsigned long long modularInverse(const unsigned long long e, const unsigned long long m) {
unsigned long long d = 1;
while(d * e % m != 1)
d++;
return d;
}
unsigned long long pow(const unsigned long long base, const unsigned long long exponent) {
unsigned long long result = 1;
for(long long i = 0; i < exponent; i++)
result *= base;
return result;
}
bool RSA::generateKeys(const unsigned long long p, const unsigned long long q, unsigned long long& n, unsigned long long& d, unsigned long long& e) {
//p & q have to be primes
if(!(prime(p) && prime(q)) || p == q)
return false;
//n defined as p * q
n = p * q;
unsigned long long m = (p - 1) * (q - 1);
//find e where e and (p - 1)(q - 1) are coprime
e = 7;
while(!coprime(m, e))
e++;
//1 = (d * e) % (p - 1)(q - 1)
d = modularInverse(e, m);
//everything worked
return true;
}
unsigned long long RSA::encrypt(const unsigned long long message, const unsigned long long e, const unsigned long long n) {
return pow(message, e) % n;
}
unsigned long long RSA::decrypt(const unsigned long long encryptedMessage, const unsigned long long d, const unsigned long long n) {
return pow(encryptedMessage, d) % n;
}
Just to be sure here's how it's used in main.cpp:
#include <iostream>
#include "cryptography.h"
int main(int argc, char const *argv[]) {
unsigned long long n, d, e;
if(!RSA::generateKeys(7, 13, n, d, e))
return -1;
std::cout << "n: " << n << std::endl;
std::cout << "d: " << d << std::endl;
std::cout << "e: " << e << std::endl;
std::cout << std::endl;
unsigned long long message;
std::cin >> message;
std::cout << "Message: " << message << std::endl;
unsigned long long encryptedMessage = RSA::encrypt(message, e, n);
std::cout << "Encrypted Message: " << encryptedMessage << std::endl;
unsigned long long decryptedMessage = RSA::decrypt(encryptedMessage, d, n);
std::cout << "Decrypted Message: " << decryptedMessage << std::endl;
}
| As @President James K. Polk correctly guessed the Problem was a silent Integer-Overflow. Also to anyone stuck on this: too high encryption-data-integers can cause problems on small primes easily.
I used this to replace pow(a, b) % c in the encrypt & decrypt Method with a call to modularPow(a, b, c):
unsigned long long modularPow(const unsigned long long base, const unsigned long long exponent, const unsigned long long modulus) {
unsigned long long result = 1;
for(unsigned long long i = 0; i < exponent; i++) {
result *= base;
result %= modulus;
}
return result;
}
|
70,137,216 | 70,137,386 | C++ Stream Extraction Operator>> Declared But Not Defined Even Though It Is Defined | So I have in stockType.h
#include <iostream>
class stockType {
public:
//...
static friend std::ostream& operator<<(std::ostream& out, const stockType& stock);
static friend std::istream& operator>>(std::istream& in, stockType& stock);
private:
//...
}
and in stockType.cpp
std::ostream& operator<<(std::ostream& out, const stockType& stock) {
//...
}
std::istream& operator>>(std::istream& in, stockType& stock) {
//...
}
I'm having no issues with operator<< but the compiler gives me a fatal error "static function 'std::istream &operator >>(std::istream &,stockType &)' declared but not defined" and it says it occurs on main.cpp line 32 but there's only 31 lines in main.cpp.
| Marking a free function (friend functions aren't methods in a class) as static indicates that it will be defined in the current translation unit. Putting a static function in a header means that all translation units including that header must have their own definition of that function. You should remove static from your declarations (clang and gcc actually reject your code as invalid).
Note that this is different to static member functions which indicate that the method is available in the class rather than in instances. This is one of the many confusing places that c++ uses the same keyword to mean different things in different contexts.
|
70,137,779 | 70,143,080 | Using eigen objects in C | I want to wrap part of Eigen's feature in C, but I am curious how would the automatic storage duration works in such case. For example:
/* eigenwrapper.h */
#ifdef __cplusplus
extern "C" {
#endif
void* create_matrix(int r, int c);
//and other declarations like addition, multiplication, delete ... ....
#ifdef __cplusplus
}
#endif
`
/* eigenwrapper.cxx */
#include <eigen headers>
#include "eigenwrapper.h"
extern "C" {
void* create_matrix(int r, int c) {
return &MatrixXf(r,c);
}
// and other definitions
}
`
/*main.c*/
#include "eigenwrapper.h"
int main(void) {
m = create_matrix(3,3);
/* working with m */
}
I assume that Eigen or C++ keep tracks of the number of references of the object, but will that work when I return pointer of object to C functions? Will the object being deconstructed when leaving the create_matrix function?
If the automatic storage duration won't work this way, Should I use the new keyword for dynamic allocation? e.g. return new MatrixXf(r,c); Then how could I obtain dynamically allocated, newed, matrices when I have a function returns matA * matB?
| As others have noted, C++ does not keep track of references. If you want a C API, you have to deal with this yourself.
Opaque pointers
As far as wrapping Eigen functions into C API, I would go with opaque pointers instead of void* so that you have at least some type safety.
Here is a suitable header:
#pragma once
#include <stddef.h>
/* using ptrdiff_t */
/** forward-declared opaque handle for matrix */
typedef struct EigenMatrixXf EigenMatrixXf;
#ifdef __cplusplus
extern "C" {
#endif
EigenMatrixXf* eigen_matrixxf_create(ptrdiff_t rows, ptrdiff_t cols);
EigenMatrixXf* eigen_matrixxf_add(
const EigenMatrixXf* left, const EigenMatrixXf* right);
void eigen_matrixxf_free(EigenMatrixXf* self);
#ifdef __cplusplus
} /* extern "C" */
#endif
And here the cpp file
struct EigenMatrixXf
{
Eigen::MatrixXf mat;
};
EigenMatrixXf* eigen_matrixxcf_create(ptrdiff_t rows, ptrdiff_t cols)
try {
return new EigenMatrixXf{ Eigen::MatrixXf(rows, cols) };
} catch(std::bad_alloc&) {
errno = ENOMEM;
return nullptr;
}
EigenMatrixXf* eigen_matrixxf_add(
const EigenMatrixXf* left, const EigenMatrixXf* right)
try {
return new EigenMatrixXf{ left->mat + right->mat };
} catch(std::bad_alloc&) {
errno = ENOMEM;
return nullptr;
}
void eigen_matrixxcf_free(EigenMatrixXf* self)
{ delete self; }
If you want to use fixed-size Eigen objects, read up on the allocator issues here: https://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html
Mapping C structs
You can also use Eigen's Map function give an Eigen view to a C struct. https://eigen.tuxfamily.org/dox/group__TutorialMapClass.html
There are a few tradeoffs here when it comes to API design and performance (e.g. number of dynamic allocations, alignment, etc.)
Header:
#pragma once
#include <stddef.h>
/* using ptrdiff_t */
typedef struct EigenMatrixXf
{
float* ptr;
ptrdiff_t rows, cols;
} EigenMatrixXf;
#ifdef __cplusplus
extern "C" {
#endif
EigenMatrixXf eigen_matrixxf_create(ptrdiff_t rows, ptrdiff_t cols);
EigenMatrixXf eigen_matrixxf_add(
const EigenMatrixXf* left, const EigenMatrixXf* right);
void eigen_matrixxf_free(EigenMatrixXf* self);
#ifdef __cplusplus
} /* extern "C" */
#endif
Cpp file:
inline Eigen::MatrixXf::MapType map(EigenMatrixXf& ctype)
{ return Eigen::MatrixXf::MapType(ctype.ptr, ctype.rows, ctype.cols); };
inline Eigen::MatrixXf::ConstMapType map(const EigenMatrixXf& ctype)
{ return Eigen::MatrixXf::ConstMapType(ctype.ptr, ctype.rows, ctype.cols); };
EigenMatrixXf eigen_matrixxf_create(ptrdiff_t rows, ptrdiff_t cols)
try {
return EigenMatrixXf { new float[rows * cols], rows, cols };
} catch(std::bad_alloc&) {
errno = ENOMEM;
return EigenMatrixXf { nullptr, 0, 0 };
}
EigenMatrixXf eigen_matrixxf_add(
const EigenMatrixXf* left, const EigenMatrixXf* right)
{
EigenMatrixXf rtrn = eigen_matrixxf_create(left->rows, left->cols);
if(! rtrn.ptr)
return rtrn;
map(rtrn) = map(*left) + map(*right);
return rtrn;
}
void eigen_matrixxf_free(EigenMatrixXf* self)
{ delete[] self->ptr; }
|
70,137,780 | 70,137,822 | Adding/Removing headers has no effect | I have used std::invalid_argument exception class in my code. So I also had included the header <exception> in the precompiled header (pch.h in my case). But then I removed <exception> from pch.h and the code compiled successfully on GCC 11.2 and I was surprised.
Here are some examples:
#include <exception> // removing this does not have any effects
#include <array> // the same here
.
.
.
throw std::invalid_argument( exceptionMsg ); // somewhere in the code
. // how does this work?
.
.
std::array<int, 4> buffer { }; // somewhere in the code
. // how does array work without #include <array> ??
.
.
Similarly, I removed <iterator>, <array>, <cstring>, etc. from the pch.h and still no issue. How is this possible?
So if including headers is not going to help when compiling the code, then what is their purpose? Is it safe to remove these #includes if the compiler does not complain?
|
But then I removed from pch.h and the code compiled successfully on GCC 11.2 and I was surprised.
This isn't unusual. You'll get used to it.
How is this possible?
This can happen when one of the headers that you still include happens to also include those headers that you don't directly include.
Is it safe to remove these #includes if the compiler does not complain?
No. It's not safe to not directly include a header that you depend on. When one header stops including another header, then that header may end up being not included at all, and if you depend on that header, then your program will stop compiling. To avoid that from happening, always directly include all headers that you depend on.
|
70,137,934 | 70,138,077 | Programming principles and practice 2nd ed. signed char overflow | I've finished C++ primer 5th edition and now I'm reading C++ programming principles and practice 2nd edition by Strostrup. However the author seems to depend on some UBs in many cases like this one:
int x = 2.9;
char c = 1066;
Here x will get the value 2 rather than 2.9 , because x is an int and ints don’t have values that are fractions of an integer, just whole integers (obviously). Similarly, if we use the common ASCII character set, c will get the value 42 (representing
the character * ), rather than 1066, because there is no char with the value 1066 in that character set.
But char x = 1066; is overflowing a signed char so the behavior is undefined and I'm not sure about what he is saying: it produces * because a UB can mean anything as I guess thus we don't depend or even guess the results. So what do you think? Thank you!
|
But char x = 1066; is overflowing a signed char so the behavior is undefined
That's not true.
Overflow happens as a result of an arithmetic operation. What happens here is conversion. Converting an unrepresentable integer to another integer type does not have undefined behaviour even if the type is signed.
P.S. char is not signed char. They are distinct types. It's implementation defined whether char is signed or unsigned.
|
70,138,063 | 70,138,122 | Why do cin and getline exhibit different reading behavior? | For reference I have already looked at Why does std::getline() skip input after a formatted extraction?
I want to understand cin and getline behavior. I am imagining cin and getline to be implemented with a loop over the input buffer, each iteration incrementing a cursor. Once the current element of the input buffer equals some "stopping" value (" " or "\n" for cin, "\n" for getline), the loop breaks.
The question I have is the difference between the reading behavior of cin and getline. With cin, it seems to stop at "\n", but it will increment the cursor before breaking from the loop. For example,
string a, b;
cin >> a;
cin >> b;
cout << a << "-" << b << endl;
// Input: "cat\nhat"
// Output: "cat-hat"
So in the above code, the first cin read up until the "\n". once it hit that "\n", it increments the cursor to the next position "h" before breaking the loop. Then, the next cin operation starts reading from "h". This allows the next cin to actually process characters instead of just breaking.
When getline is mixed with cin, this is not the behavior.
string a, b;
cin >> a;
getline(cin, b);
cout << a << "-" << b << endl;
// Input: "cat\nhat"
// Output: "cat-"
In this example, the cin reads up to the "\n". But when getline starts reading, it seems to be reading from the "\n" instead of the "h". This means that the cursor did not advance to "h". So the getline processed the "\n" and advances the cursor to the "h" but does not actually save the getline to "b".
So in one example, cin seems to advance the cursor at "\n", whereas in another example, it does not. getline also exhibits different behaviors. For example
string a, b;
getline(cin, a);
getline(cin, b);
cout << a << "-" << b << endl;
// Input: "cat\nhat"
// Output: "cat-hat"
Now getline actually advances the cursor on the "\n". Why is there different behavior and what is the actual implementation of cin vs getline when it comes to delimeter characters?
|
reading behavior of cin and getline.
cin does not "read" anything. cin is an input stream. cin is getting read from. getline reads from an input stream. The formatted extraction operator, >>, reads from an input stream. What's doing the reading is >> and std::getline. std::cin does no reading of its own. It's what's being read from.
first cin read up until the "\n". once it hit that "\n", it increments the
cursor to the next position
No it doesn't. The first >> operator reads up until the \n, but does not read it. \n remains unread.
The second >> operator starts reading with the newline character. The >> operator skips all whitespace in the input stream before it extracts the expected value.
The detail that you're missing is that >> skips whitespace (if there is any) before it extracts the value from the input stream, and not after.
Now, it is certainly possible that >> finds no whitespace in the input stream before extracting the formatted value. If >> is tasked with extracting an int, and the input stream has just been opened and it's at the beginning of the file, and the first character in the file is a 1, well, the >> just doesn't skip any whitespace at all.
Finally, std::getline does not skip any whitespace, it just reads from the input stream until it reads a \n (or reaching the end of the input stream).
|
70,138,115 | 70,146,027 | How to get Tflite model output in c++? | I have a tflite model for mask detection with a sigmoid layer that outputs values between 0[mask] and 1[no_mask]
I examined the input and output node using netron and here's what I got:
I tested the model for inference in python and it works great.
# A simple inference pipline
import numpy as np
import tensorflow as tf
import cv2
# Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="efficient_net.tflite")
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Rescale to [1,32,32,1].
input_shape = input_details[0]['shape']
img = cv2.imread("nomask.jpg")
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
input_data = img_gray[ ..., tf.newaxis]
input_data =tf.image.resize(input_data, [32,32])
input_data = input_data[ tf.newaxis,...]
input_data = np.array(input_data, dtype=np.float32)
# setting input
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data[0][0])
I tried doing the same using c++ but I get either 0 or no output at all
#include <iostream>
#include <cstdio>
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/optional_debug_tools.h"
#include "opencv2/opencv.hpp"
using namespace cv;
#define TFLITE_MINIMAL_CHECK(x) \
if (!(x)) \
{ \
fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); \
exit(1); \
}
int main(int argc, char* argv[])
{
if (argc != 2)
{
fprintf(stderr, "minimal <tflite model>\n");
return 1;
}
const char* filename = argv[1];
// read image file
cv::Mat img = cv::imread("D:\\nomask.png");
// convert to float; BGR -> Grayscale
cv::Mat inputImg;
img.convertTo(inputImg, CV_32FC1);
cv::cvtColor(inputImg, inputImg, cv::COLOR_BGR2GRAY);
// resize image as model input
cv::resize(inputImg, inputImg, cv::Size(32, 32));
// Load model
std::unique_ptr<tflite::FlatBufferModel> model =
tflite::FlatBufferModel::BuildFromFile(filename);
TFLITE_MINIMAL_CHECK(model != nullptr);
// Build the interpreter with the InterpreterBuilder.
// Note: all Interpreters should be built with the InterpreterBuilder,
// which allocates memory for the Intrepter and does various set up
// tasks so that the Interpreter can read the provided model.
tflite::ops::builtin::BuiltinOpResolver resolver;
tflite::InterpreterBuilder builder(*model, resolver);
std::unique_ptr<tflite::Interpreter> interpreter;
builder(&interpreter);
TFLITE_MINIMAL_CHECK(interpreter != nullptr);
// Allocate tensor buffers.
TFLITE_MINIMAL_CHECK(interpreter->AllocateTensors() == kTfLiteOk);
// Fill input buffers
// TODO(user): Insert code to fill input tensors.
// Note: The buffer of the input tensor with index `i` of type T can
float* input = interpreter->typed_input_tensor<float>(0);
input = inputImg.ptr<float>(0);
// Run inference
TFLITE_MINIMAL_CHECK(interpreter->Invoke() == kTfLiteOk);
printf("\n\n=== Post-invoke Interpreter State ===\n");
float* output = interpreter->typed_output_tensor<float>(149);
std::cout << output[0];
return 0;
}
I tried changing the output index to 0 instead of 149 but I always get a small output value indicating that there's a mask whatever the input is (This does not happen in python inference)
what am I doing wrong ??
| The code now works fine with these changes :
memcpy(input,img.data,32*32*sizeof(float));
instead of
input = inputImg.ptr<float>(0);
and using index 0 for output
float* output = interpreter->typed_output_tensor<float>(0);
The index here indicates the order of the output tensor not it's location
|
70,138,546 | 70,138,631 | How is it possible to safely copy an int into a byte array unaligned? | I created a byte array, uint8_t data[256], and I would like to read and write data to it at arbitrary positions. The position offset could be any number, so it could result in an unaligned access. For example if sizeof(int32_t) == 4 then position % sizeof(int32_t) != 0
It works now but, as far as I know, some platforms do not directly support unaligned access. I would like to make it work in that case as well.
#include <cstdint>
#include <iostream>
void write(uint8_t* data, uint32_t position, int32_t value) {
int32_t* ptr = reinterpret_cast<int32_t*>(&data[position]);
*ptr = value;
}
int32_t read(uint8_t* data, uint32_t position) {
int32_t* ptr = reinterpret_cast<int32_t*>(&data[position]);
return *ptr;
}
int main()
{
uint8_t data[256];
int32_t value = 123456789;
uint32_t position = 1; // Example for unaligned access
write(data, position, value);
int32_t read_value = read(data, position);
std::cout << read_value << std::endl;
return 0;
}
I prefer to use the standard library, if there is a solution there for this problem.
| I see no placement new in your code, making both reinterpret_casts undefined behaviour.
The returned pointer can only be dereferenced if at the given address exists an object of the specified type. With exception of char, std::byte, unsigned char which can always be dereferenced.
The safe way how to serialize and deserialize objects is through std::memcpy:
void write(unsigned char* data, uint32_t position, int32_t value) {
std::memcpy(data+position,&value,sizeof(value));
}
int32_t read(unsigned char* data, uint32_t position) {
int32_t result;
std::memcpy(&result,data+position,sizeof(result));
return result;
}
This also solves any aligment issues.
|
70,138,817 | 70,139,112 | How to get an Eigen vector from an Eigen matrix column/row? | The thing I want to do is this:
MatrixXd M;
// Whatever assigned to `X`
VectorXd V = M(1);
Eigen does not support this. Is there a way to retrieve an Eigen vector from an Eigen matrix?
| Eigen Slicing and Indexing is of much use here.
To retrieve an i-th row vector:
VectorXd V = M(i, all);
To retrieve an i-th column vector:
VectorXd V = M(all, i);
|
70,139,058 | 70,139,170 | Only one variable is working at a time, and it is dependent on which order I declare them in | I really didn't know what to put as the title for this so ignore that. I also don't know how to describe the question so here is my issue.
#include <iostream>
#include <vector>
class ClassB {
public:
//LOOK AT THIS PART
int value;
char letter;
ClassB(char t, int v) {
letter = t;
value = v;
}
};
class ClassA {
private:
ClassB* ptr;
public:
ClassA(ClassB n) {
ptr = &n;
}
ClassB* getPtr(){
return ptr;
}
};
int main() {
std::vector<ClassA> objects;
for(int i=0;i<4;i++) {
objects.push_back(ClassA(ClassB('a',i)));
}
std::cout << "Value: " << objects[1].getPtr()->value << std::endl;
std::cout << "Letter: " << objects[1].getPtr()->letter;
return 0;
}
In this code, the output I should receive is
Value: 1
Letter: a
However I am receiving this
Value: 1
Letter
Also, if I were to declare letter before value (look at the comment in code), then the output would say
Value: 0
Letter: ☺
I'm not sure why the order I declare them in would affect anything, or why I'm getting a smiley face instead of a. Any help is appreciated, thank you!
| The problem lies here:
ClassA(ClassB n) {
ptr = &n;
}
ClassB is a temporary variable that gets destructed at the end of the function. The pointer becomes invalid and the program goes nuts.
A simple and safe way to go about this, is to use an std::unique_ptr and pass parameters. unique_ptr will automatically delete ClassB when ClassA is deleted:
private:
std::unique_ptr<ClassB> ptr;
public:
ClassA(char t, int v) {
ptr = std::make_unique<ClassB>(t, v);
}
There's also just keeping a value instead of a pointer.
|
70,139,225 | 70,139,257 | My positive double value is printed as a negative output like -6.27744e+66 | I get a negative output to a positive double variable.
My object is: Fahrzeug fr("BMW",200.45);
class Fahrzeug {
private:
string p_sName;
double p_dMaxGeschwindigkeit;
public:
Fahrzeug(string p_sName, double p_dMaxgeschwindigkeit) {
this->p_sName = p_sName;
this->p_dMaxGeschwindigkeit = p_dMaxGeschwindigkeit; //the output is negative
cout << "Der Name des Fahrzeugs: " << this->p_sName << "\n" << "Die maximale Geschwindigkeit des Fahrzeugs: " << this->p_dMaxGeschwindigkeit << endl;
}
};
#endif /* FAHRZEUG_H_*/
| this->p_dMaxGeschwindigkeit = p_dMaxGeschwindigkeit; this assigns the (uninitialised) member variable to itself.
You also have a parameter called p_dMaxgeschwindigkeit which you probably meant to use but note that its not the same spelling - it has a lowercase G and C++ is case sensitive.
|
70,139,520 | 70,178,232 | gdb debugger quits prematurely on popen(), 'signal SIGTRAP, Trace/breakpoint trap'? | The following code works in stand alone (non-debugging) mode. However gdb debugging stops when I tried to step over popen(), meaning a breakpoint at the fgets() can never be reached.
#include <stdio.h>
int main()
{
char buff[10];
FILE *f = popen("echo blah", "r");
// program and debugger exit before this line
// so that fgets() and printf() were never called
fgets(buff, 5, f);
printf("%s\n", buff);
}
GDB reports Program terminated with signal SIGTRAP, Trace/breakpoint trap. I dug into glibc's popen() and this is where it quits,
// internal-signal.h
/* Block all signals, including internal glibc ones. */
static inline void
__libc_signal_block_all (sigset_t *set)
{
INTERNAL_SYSCALL_CALL (rt_sigprocmask, SIG_BLOCK, &sigall_set, set,
__NSIG_BYTES);
}
Does anyone knows what is going on here? thanks!
| Turned out to be a kernel issue, at least when I reverted back from 5.15.x to 5.14.x, the issue went away. I thought kernel update were never meant to break userspace.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.