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 |
|---|---|---|---|---|
66,227,840 | 66,317,197 | how to wrap class template consisting virtual function with pybind | A class template consists of pure virtual function and inherited by another class. I am not getting the right path to bind it. Following Error Message has appeared while trying to compile.
I have gone through the following link to find the solution 1, 2, 3, 4 but don't understand what to do. I am pasted my code here.
f... | Got the solution. It is about the trampoline of pybind.
using Base_Abstract_Only<T>::Base_Abstract_Only; it will be solved.
A working gist is given here.
binding.cpp
#include <pybind11/pybind11.h>
namespace py = pybind11;
template <typename T = int>
void declare_class_template_abstarct(py::module &m, const std::stri... |
66,227,861 | 66,245,801 | Avoid locking inside of boost::interprocess::managed_shared_memory | I want to create a managed_shared_memory that is going to be created and written to by process A and read from by process B. So far I managed to implement the functionality I want, but I realized that when a process crashed during a .find or .construct operation, the mutex will not be unlocked (so it is not a robust mu... |
The problem is I am at a total loss on how to change the locking behavior of the managed_shared_memory object. I looked through its constructors but I cannot find a solution to this problem.
Okay, I think the choice is hard-coded - for good reason. Like I said in my comment there is no safe way to access managed memo... |
66,227,871 | 66,228,122 | CMake Project structure: When to use add_library/target_link_library over target_sources? | I'm creating a C++ project in which I can compartmentalize my source code in the following way
project
│ README.md
│ Dockerfile
│ CMakeLists.txt <---- Entrypoint
│
└───lib/spdlog (headers)
│
└───src
│ │ main.cpp
│ │ CMakeLists.txt
│ │
│ └───mongo
│ │ │ CMakeLists.txt
│ │ │ mongo.h
│ ... | Compiling separated libraries for each part of a program is usually preferable. This is useful since you can have multiple executable linking to it. For example, automated tests usually are separated executable targets that need to call the part that is testing.
It can also be useful since different part of your progra... |
66,227,883 | 66,229,436 | Flex/Lex: Regular Expression matches double characters | I have a flex program written in C++ that needs to complete the following rules:
I want yytext to accept the following:
○ Zero or one of the following characters ABCDEFGH
For example - input:
"triangle ABC" is a valid shape and I want the program to print "Valid shape"
"triangle AAC" is not a valid shape because it... | This is not the sort of problem for which you would typically use (f)lex, since the base lexical analysis is trivial (it could be done by simply splitting the line at the space) and detailed error analysis is a bit outside of (f)lex's comfort zone, specifically because there's no way to match "a string containing the s... |
66,228,058 | 66,228,148 | variable not updating when executing bash code in makefile | I'm trying to write a makefile that contains some bash commands in order to collect the names of the cpp files from a folder.
SRC_FILES=""
CC = g++
CFLAGS = -g
gather-files:
for var in $$(cd ./src && (ls -all *.cpp | awk '{print $$9}')); \
do \
... | You are mixing shell commands with makefile commands. That's not valid. The entire recipe is sent to the shell to be run there. Once the recipe has been expanded (which happens once before the shell is invoked) the results cannot contain any make operations.
In short, it's not possible (technically it can be done bu... |
66,228,100 | 66,231,779 | C++ + linux handle SIGPIPE signal | Yes, I understand this issue has been discussed many times.
And yes, I've seen and read these and other discussions:
1
2
3
and I still can't fix my code myself.
I am writing my own web server. In the next cycle, it listens on a socket, connects each new client and writes it to a vector.
Into my class i have this struct... | As stated in the links you give, the solution is to ignore SIGPIPE, and CHECK THE RETURN VALUE of the write calls. This latter is needed for correct operation (short writes) in all but the most trivial, unloaded cases anyways. Also the fixed write size of 1024 that you are using is probably not what you want -- if yo... |
66,228,133 | 66,228,241 | Are pointers declared inside struct/class initialized to nullptr by default? | I have read on Stack Overflow that global/static variables are initialized to their default value (0).
I also read somewhere else (not sure tho), that class variables (non-static) are also initialized to 0. Is this true?
Specifically, I am wondering whether my pointers are by default initialized to nullptr.
I tried com... |
I also read somewhere else (not sure tho), that class variables (non-static) are also initialized to 0.
Wherever you read that (if you read that), then stop reading that source!
Is this true?
No.
Here's a short example:
#include <iostream>
class Foo {
public:
int* ip; // Do we get default initialization to "nu... |
66,228,155 | 66,313,202 | Custom allocator for nested containers | I am working on custom allocators. So far, I have tried to work on simple containers: std::list, std::vector, std::basic_string, etc...
My custom allocator is a static buffer allocator, its implementation is straightforward:
#include <memory>
template <typename T>
class StaticBufferAlloc : std::allocator<T>
{
private:... | Creating a scoped allocator in C++11/C++14 was a little bit challenging. So I opted for a very modern solution introduced in C++17. Instead of implementing an allocator, I used polymorphic_allocator. Polymorphic allocators are scoped allocators, standard containers will automatically pass the allocators to sub-objects.... |
66,228,430 | 66,231,634 | Ambiguous overloads, implicit conversion and explicit constructors | Consider the following little program:
#include <vector>
class A {
int a;
int b;
public:
explicit A() = default;
A(int _a, int _b) : a(_a), b(_b) {}
int f(const A& a) { return 0; }
int f(std::vector<int> a) { return 1; }
};
int g(const A& a) { return 2; }
int g(std::vector<int> a) { return 3; }
int ma... | You're right that it seems like a bug. The commented out line below fails to compile for the exact reason that there should be no ambiguity.
Got a workaround for you using std::initializer_list:
#include <fmt/core.h>
#include <vector>
class A {
int a;
int b;
public:
explicit A() = default;
A(int _a, int _b)... |
66,228,810 | 66,228,865 | Curry a function that takes abstract arguments in CPP | I would like to curry a function that takes an abstract argument. This makes my compiler angry:
#include <functional>
class MyAbstractParentClass {
public:
virtual void someVirtualMethod() = 0;
};
class MyConcreteChildClass: public MyAbstractParentClass {
public:
virtual void someVirtualMethod() override {}
}... | std::bind copies its argument, you might use reference with std::reference_wrapper
const auto myCurriedFunction = std::bind(myFunction, std::ref(myChildObject));
or use lambda:
const auto myCurriedFunction = [&](){ return myFunction(myChildObject); };
|
66,228,994 | 66,229,049 | Is there any method can print all member variable of a struct? | i have a series of struct, i want to add a show method for them.
please see the following code:
A {
int a, b, c;
void Show() {
cout << a << " " << b << " " << c << endl;
}
};
B {
int a, b;
void Show() {
cout << a << " " << b << endl;
}
};
as you can see, i need to define a show function for each ... | There isn't such a mechanism in the standard library. For types such as your A and B, you should be able to use magic_get
|
66,229,077 | 66,229,716 | can't seem to find the linker I'm looking for linking objects under python.h | I have python3.4 and have installed python3-dev( I have directory at /usr/include/python3.4). I also have boost-python-dev installed.
To compile my cpp file, I'm using
g++ python-binding/struct.cpp -I /usr/include/python3.4 -I python-binding/src -lboost_python -lpython3.4
but my compiler can't seem to find -lpython3.4... | You should be able to find the particular linking flags by utilizing pkg-config -- on my machine the invocation is pkg-config --libs python-3.4 (though my minimum version is 3.6 currently)
the output will look something like this:
$ pkg-config --libs python-3.6
-lpython3.6m
|
66,229,209 | 66,229,315 | What is wrong with this vector comparison? | I am trying to compare a vector before a method to the same vector after a method to assert that they are the same vector but when I run my test, I get the following errors:
[build] C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29333\include\xutility(5044,1): error C2893: Failed to ... | The error message suggests that your object Item is not implementing operator==
https://en.cppreference.com/w/cpp/utility/functional/equal_to
template< class T >
struct equal_to; //(until C++14)
template< class T = void > struct equal_to; //(since C++14)
Function object for performing comparisons. Unless speciali... |
66,229,359 | 66,230,342 | C# ArrayList with C++ Interop | Got this in C#
public static ArrayList MyFct()
{
var x = new ArrayList();
x.Add(5);
return x
}
On C++ side with Interop, after calling Invoke_3(), I get a variant_t which contains my array, but how can I "extract" it ?
(for instance I would like to get the number of items, etc.)
| This is a VARIANT (variant_t is a wrapper that comes from comdef.h / #import statement) that contains an IDispatch reference, so you can use IDispatch's methods, for example like this (error checks omitted):
variant_t v;
HRESULT hr = unk->GetList(&v); // get my VARIANT that contains an ArrayList reference
// get "Coun... |
66,229,407 | 66,229,511 | Calling a non-const function with a const pointer as argument | I've read that a non-const member function of a class can only be called on non-const objects.
My question is, why can a non-member function which takes a non-const pointer, be called with a const pointer?
I tried this code:
int k = 10;
int x = 5;
void func(int *n) {
n = &k;
cout << *n<< ", x: " << x << endl... | int * const ptr=&x;
declares a immutable pointer (you can't change the address stored in ptr) that points to a mutable int (you can change the value ptr points to).
void func(int *n)
takes a pointer to a mutable int by value, no problems here. The mutability of ptr is of no concern, because you take a copy anyway. S... |
66,229,593 | 66,229,689 | Does CRAN require separate files for each .R and .cpp function in packages? | I want to submit an R package to CRAN. All packages that I know have a separate .R or .cpp file for each of their .R or .cpp functions, respectively. Is this a necessary property for a package to be accepted by CRAN?
| No.
You could have all your R code in one file R/myfile.R and all your C++ code in src/myfile.cpp. But files are "transient" anyway in the sense that R now bytecompiles all R code into another internal representation, and of course always compiled native source code in C, C++, Fortran, ... as needed into object code t... |
66,229,679 | 66,248,988 | Qt | C++ connect not being triggered | I'm trying to play with basic signal/slot in C++.
Here is my Network-Manager, which will trigger the event :
class NetworkManager : public QObject {
Q_OBJECT
public:
explicit NetworkManager(QApplication* application);
void OnFinished(QNetworkReply *reply);
...
signals:
void OnReceived();
};
And in Disp... | Here is the solution :
Manager::Manager(QApplication *application,
NetworkManager _networkManager,
DisplayManager _displayManager)
: networkManager(application)
, displayManager(application)
{
...
connect(&networkManager, &NetworkManager::OnReceived,
... |
66,229,875 | 66,230,265 | how to solve invalid types for array subscript error? | I'm trying to pass a 3D array to function and change it's values. The problem is that I get an error: invalid types 'unsigned char[int]' for array subscript.
Code in main:
unsigned char image[height][width][BYTES_PER_PIXEL];
setBlankImage((unsigned char*)image, width, height);
Function code:
void setBlankImage(unsigne... | There are at least 3 methods of passing an array:
Using array notation.
Using std::vector<std::vector<std::vector<int>>>
Pointer to the first location.
Your code is using method 3 above. Since it's a pointer to a single location, you'll have to adjust the pointer to the appropriate cell using linear algebra (see my ... |
66,230,149 | 66,230,567 | dealing with variants containing move-only types | Consider the following code:
#include <iostream>
#include <variant>
#include <memory>
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...)->overloaded<Ts...>;
struct foo {
int f;
foo(int n) : f(n) {}
};
struct bar {
std::string b;
};
using... | template<template<class...>class, class> struct is_instance_of:std::false_type{};
template<template<class...>class Z, class...Ts> struct is_instance_of<Z,Z<Ts...>>:std::true_type{};
template<template<class...>class Z, class T>
constexpr bool is_instance_of_v=is_instance_of<Z,T>::value;
flattened_variant flatten(unfla... |
66,230,467 | 66,230,965 | Multiply one matrix "in-place" by another square matrix for memory efficiency? | If I have a square matrix A of dimension M x M and a matrix B of dimension M x N, they are compatiable to be multiplied and the resulting matrix will have the same dimensions as matrix B.
I've found myself in a situation where these matrices are quite large and of dynamic size. This means that I have to make big memory... | You can do it if you store a copy of a single column of B before calculating the same column of the result into this column of B. You can reuse this column-sized helper array for the calculation of every column of the result. This way you only need to store A (MxM), B (MxN), and an array of size M.
Here is a little C-l... |
66,230,707 | 66,231,307 | C++ __builtin_* functions source codes | I want to learn how can I find source codes of __builtin functions like __builtin_cbrt() in C++. If you know, Can you help me?
|
I want to learn how can I find
First become acquainted with the language you are working with - learn C and C++ programming languages. Learn about the tools like git and autotools and the environment around these programming languages. Become familiar with the tool set needed browsing files - at least grep, but I rec... |
66,231,148 | 66,231,609 | C++ template accept only typenames with certain member | I'm learning how to use templates. Let's say, I have following structure of classes. I'm using the template just for classes tC and tD(with intention of implementing more similar classes in the future). In other parts of the project I'm using only methods from the base class A for abstraction. These classes compile and... | You have two questions:
Is it acceptable to refer in the template class to member of the typename T? (I mean implementation of getVersion())
Can I specify somehow that typename T requires to have such member?
The answer to both is "yes"
After I made your code into a compilable example, it does both of those things (t... |
66,231,470 | 66,231,628 | Is there a way to limit the parameter type passed into a method? | I'm trying to restrict the parameter accepted by a method to one specific user-defined class and haven't been able to find a way to do this so far.
Is there a way?
This is my code:
class Item {
public:
std::string name;
Item(std::string n) { name = n; }
}
class Container {
private:
s... |
I have a class which has a string attribute and am trying to test a method of a second class so that it will only accept an object of the first class, but if I just try to pass a string into it, it accepts the inputted parameter.
No, it doesn't.
It implicitly converts the string parameter to an Item because the singl... |
66,231,649 | 66,234,803 | How can I pass a non-static class method as a callback function in C++? | An audio library I'm using takes a callback function as an argument, which writes audio into a buffer.
I'm writing a class called Instrument, in which I have a method oscillator() which writes a sine wave to the buffer:
class Instrument {
private:
int oscillator(int16_t* outputBuffer, ...){ // Writes a sine wave to ... | RtAudio::openStream() takes a user-defined parameter as input to the callback, per the documentation:
https://rtaudio.docsforge.com/master/api/RtAudio/openStream/
void openStream(..., RtAudioCallback callback, void *userData=NULL, ...)
public function for opening a stream with the specified parameters.
...
Parameters... |
66,231,687 | 66,232,223 | Parsing coordinates from cin input c++ | How I should parse this? I'm asking 4 coordinates which you input like this: 1 3 4 3 and then if you just input 'q' and press enter it should exit. Same as if you replace some of the coordinates with 0 or alphabets. I'm quite stuck now and not sure how I'm supposed to do this in c++, now I'm just getting errors if my i... | String handling and interactive input are exactly the things that C++ is worst for, compared to almost any scripting language. They're usually string-oriented and/or weakly- or dynamically-typed. This means you can often write optimistic code, and if it does fail, you can probably recover.
In order to handle string inp... |
66,231,713 | 66,231,820 | Why does an unspecialised template win over a partially specialised one? | I am trying to create a templated can_stream struct that inherits from
std::false_type or std::true_type depending on whether operator<< is defined for type T.
#include <iostream>
struct S {
int i;
};
std::ostream& operator<< (std::ostream& os, S const& s) {
os << s.i << std::endl;
return os;
};
struct R... |
operator << exists for both int and S (so decltype(...) is well formed).
But decltype( operator<<( std::declval< std::ostream& >(), std::declval< T const& >())) is std::ostream&, where the default value for Enable is void.
There isn't match.
You can try with
template<
typename T // .................................. |
66,231,790 | 66,232,613 | Is There a Function Like "pthread_getcancelstate"? | The Linux Pthread Library includes 2 functions to set a threads' cancel state and cancel type:
int pthread_setcancelstate(int state, int *oldstate)
int pthread_setcanceltype(int type, int *oldtype)
How can I receive those states and types? Is there a function like pthread_getcancelstate or pthread_getcanceltype? I se... | Since the functions pthread_setcancelstate() and pthread_setcanceltype() return the old state via the argument list, you can call the functions to set the 'safe' state/type (PTHREAD_CANCEL_DISABLE and PTHREAD_CANCEL_DEFERRED, I think), and if the old state/type was not the same, call the function a second time to reins... |
66,231,902 | 66,248,306 | Store a reference of an object's method received from a function | I was able to pass an object's non static method Dummy to another object's function. The problem comes when I try to store the reference of that method into the object of the function, I don't know how to do it.
#include <iostream>
#include <functional>
class Dummy{
public:
void runDummyArgs(int z){std::cout<<"TES... | I would write something that looks like:
#include <iostream>
#include <functional>
class Dummy{
public:
void runDummyArgs(int z){std::cout<<"TEST: "<<z<<std::endl;};
};
class Test{
std::function<void(int)> mFunc; // added member to hold function
public:
// added constructor to accept function
Test(std... |
66,231,935 | 66,251,337 | Mouse pointer position when a label is activated | When an object of QLabel sub class is actived, how can one find if the mouse pointer is on the label and get its position if it is?
QWidegt::event() can check the event type of QEvent::WindowActivate, but it provides no information about mouse pointer position.
UPDATE
According to comment by @Mathias Schmid , I create ... | To check if mouse cursor is on custom widget derived from QLabel at time when it gets focus just override focusInEvent() and handle mouse cursor position check there.
MyLabel.h
class MyLabel: public QLabel
{
Q_OBJECT
public:
MyLabel(QWidget *parent = nullptr);
~MyLabel();
protected:
virtual void focus... |
66,231,946 | 66,238,977 | What does C5002 1204 auto-vectorizer reason code mean? | I'm a student and I'm learning for techniques of vectorization. I'm trying to make compiler vectorize a function which multiplies two matricies (each matrix consists of elements that are matricies of equal size). The code looks as follows:
#define f_dim1 2000
#define f_dim2 240
#define s_dim1 240
#define s_dim2 2000
#... | This reason code means that loops are nested too deeply
As Eljay suggested, I posted an issue on github using the link at the bottom of the documentation page. Here is the link to the answer.
|
66,232,229 | 66,232,328 | Is a local variable an lvalue when deducing its type using decltype? | I am reading the Wikipedia entry about decltype, and I can't understand the following passage:
Similarly to the sizeof operator, the operand of decltype is
unevaluated.[11] Informally, the type returned by decltype(e) is
deduced as follows:[2]
If the expression e refers to a variable in local or namespace scope, a st... |
For me it implies that variable from local scope is not an lvalue
No, that's not the correct way to read it. The list is not a bunch of mutually exclusive options. Some properties may overlap. When determining the type decltype produces, we are meant to apply the first item whose condition is satisfied. Think of it l... |
66,233,029 | 66,233,057 | C++: memory issue when I delete a pointer created by new | I'm a little bit confused by the following code
int main()
{
int* a = new int{12};
int* b = new int;
b = a;
delete a;
delete b;
return 0;
}
The code returns an error that
a.out(27538,0x10ade7e00) malloc: *** error for object 0x7f8c18504160: pointer being freed was not allocated
a.out(27538,0... | b = a; // here the int that b pointed at "leaks" (you have no way of deleting it)
delete a; // here "a" is deleted first
delete b; // here "a" is deleted a second time (undefined behavior)
When you assign the value of a to b, the value (address if you will) b previously contained, is forgotten. Both a and b then ... |
66,233,492 | 66,297,266 | How to generate a mesh in Unreal Engine 4 from binary data from a 3d file like .fbx in runtime with C++? | My goal is to download the contents of a 3d file from a server and then generate a mesh with that data. I haven't made any progress apart from some research into the topic. I am also a ue4 begginer but i am at home with c++.
| To generate meshes in runtime you can use Epic's ProceduralMeshComponent or 3rd party project RuntimeMeshComponent
|
66,234,022 | 66,247,342 | Parse nested json to TMap in Unreal Engine 4 | I have a nested json with the following structure within UE4:
{
"boundary_points__per__cell": {
"0": [{
"x": 16.451330042628662,
"y": 2.0813326861577965
},
{
"x": 16.755262971791506,
"y": 2.0406535171257136
}... | Firstly, those aren't integers, so you would probably want to use float or double instead of int32.
On the topic of why it won't parse, based on a comment by nick.shin:
the use of TMap is not applicable to JSON -- the simpler TArray must be used.
and, to give you the closest "TMap-like" functionality -- your JSON will ... |
66,234,281 | 66,234,353 | Arduino C++ Inheritance and function declaration problem | class Entity {
public:
virtual void applyCollisionBehaviorTo(Entity &entity) { }
virtual void onCollision(Entity &entity) { }
};
class Ball : public Entity {
public:
void applyCollisionBehaviorTo(Entity entity) override {
}
void onCollision(Entity entity) override {
entity.ap... | Your class Entity should be like this:
class Entity
{
public:
virtual void applyCollisionBehaviorTo(Entity &entity) = 0;
virtual void onCollision(Entity &collidingEntity) = 0;
};
You can't refere to object of Ball class inside Entity, in fact entities don't even know about the existence of balls.
OTOH ball... |
66,234,321 | 66,235,205 | C++: potential memory leak in linked list | I'm writing a class of linked list, I feel that for the member function that used to delete specific element might cause the memory leak. The code is below.
struct node
{
int data;
node *next;
};
class linked_list
{
private:
node *head,*tail;
public:
linked_list()
{
head = NULL;
tai... | There are few issues with your instance of code, I have corrected that:-
As pointed by others, you are not required to use `new` keyword to declare a pointer.
When one tries to delete the first node of the linked list, then according to your code, it will delete the second node, because of the following
tmp = hea... |
66,234,335 | 66,246,824 | What types are trivially constructible? | I know, that many types (e.g. POD types) are trivially default-constructible. But what types are trivially constructible from an argument list other than the empty argument list? For example what types are trivially constructible from int? I can't think of any.
The following types are not trivially constructible from i... | Trivially constructible from Args... is defined as construction from values of the given types that does only do operations considered "trivial". In particular the syntax T obj(std::declval<Args>()...) has to call only "trivial" operations.
Up until C++17 the only trivial construction operations possible are default co... |
66,234,507 | 66,234,543 | C++ - Get "id" of class's variable from enum class | If I have code:
class A {
public:
int x;
enum class nums {
Ab = 0,
Bc,
Cd,
De,
Ef
};
A() { this->x = 0; }
}Avar [5];
Is somehow possible to use enum nums numbers as "id" for class's variable Avar[], so I don't need to converting to int with static_cast<> or int()... | An enum class (aka scoped enumeration) is not implicitly convertible to an integer and cannot thus be used as an index of an array without a cast. You can use a plain enum instead of an enum class. Unlike enum classes, an enum is implicitly convertible to an integer and can therefore be used as an index of an array.
P.... |
66,234,705 | 66,281,599 | /usr/include/stdlib.h:133:35: error: missing binary operator before token "(" | I have a preprocess error for compiling gtest project with tizen headers on gitlab ci-runners (Debian GNU/Linux 10 (buster)). gcc (Debian 8.3.0-6) 8.3.0
But on local machine Ubuntu 16.04 compiles this successfully. gcc (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609
I have an installed Tizen Studion 4.1 with SDK: WEARA... | Problem solved.
Using the direct path to the compiler in CMakeList.txt helped me.
if(DEFINED ENV{TIZEN_SDK_HOME})
set(CMAKE_CXX_COMPILER $ENV{TIZEN_SDK_HOME}/tools/i586-linux-gnueabi-gcc-6.2/bin/i586-linux-gnueabi-g++)
You should use FLAGS with --sysroot and -L to tizen's libs
SET(gcc_root "$ENV{TIZEN_SDK_HOME}/pl... |
66,235,277 | 66,235,437 | Rectangle in sdl2 sets colour for entire screen | I know there are already questions like this on SO but I am new to SDL2 and I have had a look at some tutorials to draw a rectangle and I have had a look at some questions here as well. With the current code below I cannot draw a rectanlge onto the window as it doesn't appear I have also tried to clear the window after... | Your issue seems to be with the rect.x, rect.y, rect.h, rect.w = 50, 50, 50, 50;
When I changed it to
rect.x = 50;
rect.y = 50;
rect.h = 50;
rect.w = 50;
The program worked
|
66,236,020 | 66,236,063 | How To Store Key Value In MAP As Pair In C++ | I'm trying to solve a question on hacker rank named (Attribute Parser) : QUESTION
So I came up with a solution that I could use map but in order to solve it I need to insert two keys 1 would be pair and the other would be a string
map<pair<string,string>,string>DATA;
I tried DATA.emplace({Type, Tag},Data);
But it's giv... | DATA.emplace({Type, Tag},Data);
There is no implicit conversion to std::pair<string,string> from {Type,Tag} even if they are of string type. Rather use std::make_pair
DATA.emplace(std::make_pair(Type,Tag), Data);
|
66,236,088 | 66,236,454 | Invalid password causing infinite display loop | I am creating a function that checks the user's username and password. When I enter the username and password correctly, the program outputs the correct string. Then, when I enter the incorrect username OR password, the correct while loop is output. However, when I try to enter the correct username after the while loop... | Answer according to your code:
#include<bits/stdc++.h>
#include<limits>
using namespace std;
void CheckUserPermissionAccess()
{
int userPassInput;
string usernameInput;
string user1 = "Bob Jones";
string user2 = "Sarah Davis";
string user3 = "Amy Friendly";
string user4 = "Johnny Smith";
... |
66,236,104 | 66,236,294 | is it possible to using std::pair as key of std::set without any duplicates each element? | I'm trying to store struct in std::set using two integers in struct as key.
I know that is possible to using std::pair as key of std::set.
struct TYPE{
pair<int, int> nums;
... // some other things
TYPE(){}
TYPE(int first, int second) { nums = make_pair(first, second); }
bool operator<(const TYPE &rhs) const... | The comparison used for a set must satisfy the Compare named requirement. Among these requirements is transitivity of the induced equivalence relation:
If equivalent(a,b) and equivalent(b,c) then equivalent(a,c).
A concrete case:
Let a be {1,2}, b be {1,4}, and c be {3,4}.
Transitivity: if {1,2} is equivalent to {1,... |
66,236,498 | 67,368,056 | “is_base_of” inside a class declaration | I was having an issue with std::is_base_of being called inside of a class declaration for an incomplete type. I came across this StackOverflow question: Why can't "is_base_of" be used inside a class declaration (incomplete type)?
Then I tried to implement my own metafunction for checking if the given template class is ... | Seems the only difference is that it does not handle non-public inheritance.
Thanks to Axalo for the comment
|
66,236,630 | 66,254,228 | Visual Studio Debugger C++ - breakpoints not recognized | Beginner programmer using Visual Studio release January 2021 on Windows 10. I have yet to get breakpoints to work. When placing a breakpoint in the helloworld.cpp program below and running the debugger, I get the following message and no breakpoint is set.
Breakpoint warning: Unexpected symbol reader error while proces... | After several hours of reading various VS Code install videos, I ended up reinstalling twice. The overall solution for me was the reinstall and using the g++ compiler and gdb debugger. I can now set breakpoints, etc.
|
66,236,880 | 66,237,555 | Why should I declare variable in the While loop | #include <iostream>
using namespace std;
int main()
{
int n, line_number = 1, stars = 1;
cout << "Enter lines number " << endl;
cin >> n;
while (line_number <= n)
{
while (stars <= line_number) {
cout << "*";
stars++;
}
line_number++;
cout <<... | The variable 'stars' you were using was incremented at the same pace as the variable 'line_number'. For example, at line 1 the 'stars' with value of 1 was equal to the 'line_number' with value of 1 so the line 1 only print one '*' which is correct. However from the line 2 and so on, due to the 'star' was incremented ... |
66,237,402 | 66,237,438 | Array with multiple data types | I want to make array for positions (x, y, z)
It would be something like this:
/*Whatever the type*/ array[100] = {(1, 2, 3), (4, 2, 5)....}
How can I do this?
| To be honest, making a struct makes the program much simplified:
struct location {
int x;
int y;
int z;
};
int main(void) {
location array[100];
// Example initialization of the first index
array[0].x = 10;
array[0].y = 20;
array[0].z = 30;
// Or, even better...
array[0] = {1... |
66,237,507 | 66,240,222 | How to launch a QThread correctly | I think I'm missing something obvious here.
I'd like to Run GTest with the QT Eventloop. For the QT Eventloop to run I have to start the QApplication.
The GTEST RUN_ALL_TESTS should then start inside a newly created QThread.
/**
* @brief Executes GTest. After Executing GTest it will stop the QApllication
*/
static voi... | I think the problem is with the statement...
auto pGTest = std::make_unique<QThread>(QThread::create(ExecuteGTest));
Generally speaking an expression...
std::make_unique<T>(args...)
will create an std::unique_ptr<T> with the instance of T being constructed according to...
T(args...)
So in this case you will actually... |
66,237,978 | 66,238,748 | C++ GDI+ how to get and load image from resource? | I'm trying to display a PNG image from my resource file using GDI+.
#include <Windows.h>
#include <objidl.h>
#include <gdiplus.h>
using namespace Gdiplus;
#pragma comment (lib,"Gdiplus.lib")
#pragma comment(lib, "dwmapi.lib")
...
auto CALLBACK BorderlessWindow::WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam... | TLDR: FindResource, LoadResource, and LockResource to get a pointer to the image bytes. Then make an IStream from it. The IStream can be used to initialize a Gdi+ Image or Bitmap object. (Gdiplus::Bitmap derives from Gdiplus::Image)
Stick a new line into your .rc file:
IDI_MY_IMAGE_FILE PNG "foo.png"
And ma... |
66,238,486 | 66,291,099 | Freetype with C++ not loading all glyphs correctly | I'm using FreeType to load the glyph textures, basically using FT_Load_Char to get the texture, then creating an instance of my custom class Character that contains all the metrics and texture for rendering later:
for (unsigned int c = min; c < max; c++)
{
if (FT_Get_Char_Index(faces[faceIndex].second, c) == 0)... | Character character;
character.texture = texture;
character.bearingX = glyph->bitmap_left;
character.bearingY = glyph->bitmap_top;
character.width = glyph->bitmap.width;
character.height = glyph->bitmap.rows;
character.advance = glyph->advance.x;
As it turns out, using unsigned int for the height and int for bearingY ... |
66,238,736 | 66,241,165 | Is it ok to do namespace ranges = std::ranges; | Since C++20, it seems that std::ranges:: is capable of almost everything std:: can do (looking at range algorithms).
Is it a good practice to just write namespace ranges = std::ranges; in the topmost header of one's project ?
For example, a namespace alias is already done for views:
namespace std {
namespace views ... | We don't want to pollute the global space with a second namespace.
When developing a library, you can do this inside your MyLib namespace so that there is no pollution => it is convenient because you can simply use ranges:: inside the MyLib scope, whatever the header or the source file.
When developing a simple projec... |
66,239,578 | 66,255,234 | Create a generator in C++ using coroutines | Following the McNellis's presentation for coroutines(Introduction to C Coroutines), I try to compile the example of the simple coroutine, which actually is a simple counter.
However when the resume is called ,assertion is fired.
Specifically
_LIBCPP_ASSERT(!done(),
"resume() has undefined behaviour when the coroutine ... | promise_type::get_return_object() shall return user-defined coroutine result type resumable_thing, instead of promise_type& itself.
struct resumable_thing
{
struct promise_type
{
resumable_thing get_return_object() noexcept
{
return {*this};
}
// ...
};
r... |
66,239,603 | 66,245,447 | How to emulate boost::algorithm::find_if_backward with Range-v3? | I've been using extensively boost::algorithm::find_if_backward to get a forward iterator to the last element in a range satisfying a predicate.
How do I accomplish the same task using Range-v3?
This is my attempt, which looks a bit clunky; and I'm not even sure is robust enough. Actually, as suggested in a comment, the... | Assuming you always know that a match is found, why not simplify to the following, getting the identical output:
Live On Godbolt
#include <algorithm>
#include <boost/algorithm/find_backward.hpp>
#include <boost/hana/functional/partial.hpp>
#include <fmt/ranges.h>
#include <range/v3/algorithm/find_if.hpp>
#include <rang... |
66,239,698 | 66,239,913 | passing pointer to const int in recursive call | How to pass a pointer to const int in a recursive call. I am using the following code format to calculate Fibonacci recursively, but am getting the error:
error: lvalue required as unary '&' operand**
#include <iostream>
void fun(const int *n)
{
fun( &(*n-1) ); // it is giving error.
}
int main()
{
con... | You would have to use another variable then, to which you assign the decremented const variable: you simply can't pass a decreased value of a const variable, since by definition, it is not modifiable neither by increment or decrement.
#include <iostream>
void fun2 (const int *n)
{
std::cout << *n << std::endl;
}
vo... |
66,239,953 | 66,240,039 | Parameter transfer between different object types | I would like to transfer some parameters from one object to another. The object are of different types. I tried some ways but none of them compiled. All types are given and cannot be changed.
I wanted to use std::bind, std::function, std::mem_fn and/or lambdas. But I didn't find correct mixture of these.
Is there a way... | Not sure if it is what you really want, but
template <typename T3, typename T1, typename T2>
void function(const T1& t1, bool(T1::*getter)(T3&) const,
T2& t2, bool(T2::*setter)(const T3&))
{
T3 data;
if ((t1.*getter)(data))
{
(t2.*setter)(data);
}
}
With usage similar to
function<... |
66,240,314 | 66,240,382 | c++ using-keyword in python | In c++ you generally can do this:
using LCN = longNamespace::sub::subsub::LongClassName
so you don't have to write a long classname everytime. Is there a similar keyword or workaround in python for static classmethods.
class MyPythonClassWithLongName:
@staticmethod
def foo():
pass
def bar():
... | Sure: classes in Python are just objects, so you can reassign them freely to a new name:
LCN = MyPythonClassWithLongName
LCN.foo()
Whether that’s recommended for readability is another matter.
|
66,241,205 | 66,241,340 | Returning a structure from a function | I am trying to learn structures, but I am confused why I can't see changes in the structure after returning it from my function.
#include <iostream>
#include <vector>
using namespace std;
struct multiset {
vector <int> elements;
vector <int> counts;
};
multiset multiset_add(multiset Set, int num) {
Set.... | Your function
multiset multiset_add(multiset Set, int num) {
Set.elements.push_back(num);
return Set;
}
gets the parameter Set passed by value. You either have to use the returned multiset in you main function like this:
int main()
{
multiset Set;
Set = multiset_add(Set, 2);
cout << Set.elements[... |
66,241,510 | 66,241,548 | Why is constructor being invoked? | Why is s1() constructor being invoked here?
#include<iostream>
struct s1 {
s1(int tmp) {
}
s1() {
std::printf("s1 invoked");
}
};
struct s2 {
s1 s;
s2(s1& s) {
this->s = s;
}
};
int main() {
s1 o1(5);
s2 o2(o1);
return 0;
}
result:
s1 invoked
Why passing by... | Given the implementation of s2(s1&):
s2(s1& s) {
this->s = s;
}
The data member s is default-initialized via the default constructor firstly, then gets assigned inside the constructor body.
You should initialize it directly in member initializer list.
s2(s1& s) : s(s) // direct-initialize data member s from parame... |
66,241,880 | 66,241,967 | DTOR not called when using shared_ptr | I'm running into some really strange behavior. One of my classes (Class A) holds a shared_ptr to a class Connector. Other classes also hold shared_ptr to that Connector instance. I noticed that the Connector's destructor doesn't get called after everything goes out of scope. However, if I hold the Connector in class A ... | This happens when you have a cycle. That means objects point to each other in a cycle, so the reference count never goes to zero. You have to fix the cycle. C++ specifically has a weak_ptr type to use in such situations, which could be useful in your case as well.
However, if I hold the Connector in class A as a refer... |
66,242,005 | 66,242,635 | Using dependency injection and mocking it with gmock | I have implemented a Dependency Injection pattern in my code. I did that to be able to mock a service using gmock. The DI implementation works in production code, however, I am having trouble with my test setup. When using the EXPECT_CALL macro, I get "expression must have class type" error. I believe this is related t... | EXPECT_CALL expects mock object as first parameter, you pass reference to mock.
either use *mockEngine:
TEST(TestCarClass, TestCarWithMockEngine)
{
IEngine *mockEngine = new MockEngine;
Car carUnderTest(mockEngine);
EXPECT_CALL(*mockEngine, start());
carUnderTest.Drive();
}
or avoid allocation direct... |
66,242,050 | 66,242,124 | C++ Creating a function, like a variable, change its body later and then call it later | I'm trying to create a dummy function inside of a class, whichs' body will be changed later in int main(). And then I'd like to call this body changed func in the class. Is there a way to achieve this?
Something like this:
class Animation {
public:
//Don't know what to write at the next line
function<void>/*?*... | You basically have the right idea
#include <functional>
#include <iostream>
class Animation
{
public:
std::function<void()> whenCompleted;
void startAnimation() { animationEnded(); }
void animationEnded() { whenCompleted(); }
};
int main()
{
Animation score;
score.whenCompleted = [](){ std::co... |
66,242,216 | 66,242,265 | printing String output is empty | I'm new to programming , when I cout << str outside the loop , it prints nothing and when cout << str[0] << str[1] it prints the char in this position and also length of str outside of the loop is 0, what is the reason for that behavior.
Note: I tried to use concatenate str+= s[i]; and it's working in this case , I can... | string str; is an empty string with size 0 and nothing in your code changes that.
Accessing any element but str[0] invokes undefined behavior. There is no str[i] for i > 0.
To append to a string you can use + or std::string::append.
|
66,242,384 | 66,242,454 | Why is this printing 1 rather than Wednesday? | big newbie here and just trying to intensely study each little bit of code i write to figure out why and how things are happening, as that's just how I learn best.
In an attempt to understand why and when to put variables inside a function's parameters rather than establishing them inside the function itself, I tried o... | You're printing out the function dayOfWeek itself, which decays to function pointer, and converts to bool with value true (as non-null function pointer), then gets printed as 1 (you can use std::boolalpha to print out bools as true or false, e.g. cout << std::boolalpha << dayOfWeek).
You should call the function as
cou... |
66,242,526 | 66,242,637 | Initialize member class that prohibits copy | I have a member variable that is a class that prohibits copying (copy assignment operator is deleted). I want to make some checks to determine what to initiate the member to, thus I need to do this inside the constructor and not in and initializer list. It seem the member variable m is already initialed with the defaul... | As long as the class has a valid copy or move constructor, or you are using C++17+, you can make a helper function that does the logic and then returns the correct object. You then use that to initialize your member. That would look like
class MyClass {
NonCopy m;
static NonCopy initialize_noncopy()
{
... |
66,242,883 | 66,243,062 | Initialize an std::array of objects with non-trivial constructor | I have a class defined as
class Edgelet
{
private:
const int e_size;
//Other private members...
public:
//The constructor
explicit Edgelet (int size, Color cl1 = Color::NA, Color cl2 = Color::NA);
//Other public members...
As there is a const member in the class the default copy constructor is impl... | You might write helper class:
template <std::size_t ... Is, typename T>
std::array<T, sizeof...(Is)> make_array_impl(const T& def, std::index_sequence<Is...>)
{
return {{(Is, void(), def)...}};
}
template <std::size_t N, typename T>
std::array<T, N> make_array(const T& def)
{
return make_array_impl(def, std::m... |
66,243,196 | 66,243,336 | Play a music file in C++ program being compiled by MinGW | I'm using the minGW compiler to make a C++ program that plays a song file in loop in the background for a game. I pass this into the command prompt : D:\project g++ music.cpp
And the error I get is:
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\User\AppData\Local\Temp\ccQ5qzuQ.o:music... | The "undefined reference to PlaySoundA suggests that you are not including the right library into your project. It requires: Mmsystem.h (include Windows.h) Winmm.lib Winmm.dll.
read more here
Steps to add a library in Code::Blocks are:
Choose Project, Build Options.
Click the Linker Settings tab. Click the Add button.... |
66,243,234 | 66,243,355 | Why is my MPI parallel program printing twice? | My program is sorting array and works fine but I have only one small problem, it prints the unsorted array more then 1 time( depending on how much processes I have selected, if I select 2 it prints twice ). I just want to print the unsorted array only once. Is there a way of doing this? Thanks for your help :).
#includ... | You need to move this:
printf("This is the unsorted array: ");
for (c = 0; c < n; c++) {
original_array[c] = rand() % n;
printf("%d ", original_array[c]);
}
below the
int world_rank;
int world_size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
MPI_Comm_size(MPI_COMM... |
66,243,534 | 66,247,649 | How do I supply parameters to a constructor called by another constructor? | In my project, I have four structs: Node, Ring, Disc, and Graph.
a Ring contains two vectors of 12 Nodes each
a Disc contains a vector of Rings (a parameter tells the constructor how many)
a Graph contains a vector of Discs (again, the number is supplied by a parameter)
Everything works fine except Graphs. If I want ... | I would make it possible to initialize each of your classes directly with a container of the same type that you store in the classes. That way you don't have to supply how many of each there are in them.
Here are some made up versions of your classes.
struct Node { int x; };
struct Ring {
Ring(std::array<std::arra... |
66,243,766 | 66,244,528 | Remove all canvas margins & spacing in Qwt | I have a QwtPlot which consists in a single horizontal QwtPlotMultiBarChart. I would like to have the canvas height, the y axis length and the barchart height to be all the same. I tried settings all margins/spacing to zero and switch layout policies.
seriesPlot = new QwtPlot(this);
seriesPlot->plotLayout()->setCanvasM... | I found the solution:
d_barChartItem->setLayoutHint(0.75);
|
66,244,924 | 66,311,634 | Windows Console (conhost) discards newline when output matches witdth of the window | I have a C++ application on Windows, that logs to stdout (via the Win32 api using WriteConsole). Each logline consists of some text and a trailing newline character. The problem is:
When the width of the log-text (not including the newline character) matches the width of the console window, the newline character gets d... | Is there some way to tell Windows not to do that?
After some debugging, I found that this problem will not occur after removing the ENABLE_VIRTUAL_TERMINAL_PROCESSING style in the console.
Like this,
DWORD lp;
HANDLE std_out = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleMode(std_out, &lp);
SetConsoleMode(std_out, lp &~... |
66,245,621 | 66,245,736 | can anyone explain how the "->" is implemented in the #define | I'm working on a reference design with this line as a #define
#define MEDIA_EXT_STATE "\"adv7611 12-004c\":1 -> \"40080000.tpg\":0[%d]"
The sprintf function uses it which is then passed to the media_parse_setup_links() function.
sprintf(media_formats, MEDIA_EXT_STATE, 1);
ret = media_parse_setup_links(media, media_for... | The macro defines MEDIA_EXT_STATE as a string literal, similar as
#define FOOBAR "foo -> bar"
defines FOOBAR as the string literal "foo -> bar". Maybe you got confused by the escaped ", but thats just like with ordinary string literals:
std::cout << "\"123";
prints "123.
To know what is the meaning of the -> in the s... |
66,245,974 | 66,252,725 | Had to print special characters Û and ß, yet they are constantly being printed on console as white squares | I'm using Visual Studio.
The code just gives this weird output:
████ ███ █ ▄ █▄█▄
█▄█▄█▄
▀ ▀
Is there any reason for this? If there's some logic behind this and its not just a glitch, then I think I might be able to use it to render like, images and characters?
#include <iostream>
#include <windows.h>
int mai... | I suggest that you could set the character set of the compiler to be consistent with the console.
First, you need to check the character set of the console. Open the console, right click the console, and select Properties.
You will see the Current code page is 65001(UTF-8).
Then, you could select Tools->Customize->Co... |
66,246,188 | 66,246,357 | Finding a way to use PIMPL with external constant definitions for the size of an array inside the implementation | We have the following situation: We are using a processor which has defined sections inside its RAM, which must be used by a special implementation using the PIMPL-Principle. For example the private Implementation would look like this:
Impl( )
{
public:
void doSomething()
{
for( uint32_t i = 0; i < DATA_SIZE; +... |
But is it possible to make the DATA_SIZE settable and not to define it directly in the Impl-File?
The size of a non-static member array must be set in the class definition.
You can include the value from elsewhere using the pre-processor, so it doesn't have to be "in the file" in that sense, but what ever that size i... |
66,246,353 | 66,256,187 | Eclipse can't find linked libraries | I am working with the windows.h functions and everything works fine so far.
But when I try to use functions which require me to link external libraries something goes wrong.
In this case I am trying to use CreateFont(). I already know that I must link libwinmm.a and libgdi32.a and I've done that:
See this screenshot
Bu... | You are wrongly using quotes with -l flag. The -l flag also automatically adds the lib prefix and the .a extension. Your command line should be:
g++ -LD:\Programme\Eclipse\lib -o GameTest.exe "src\choosemealmain.o" "src\mealchooser.o" -lwinmm -lgdi32
|
66,246,496 | 66,246,547 | Const member function Changing Object Data Member | Hi i am reading a book and have one doubt under section of const member funcitons. The code is as follows:
class Screen {
public:
// display overloaded on whether the object is const or not
Screen &display(std::ostream &os)
{ do_display(os); return *this; }
const Screen &display(std::ostream &os) co... | Since os is not a member of your class, that’s not a problem. The classes’ members are not changed in that statement.
The contents member is only read, not modified.
|
66,246,521 | 66,254,320 | C++ Destructor: cannot access private member declared in class | I am trying to create a simple program in C++ that creates lists of movies using 2 classes: Movie, which contains details of one movie, and Movies, which contains a name and a vector of Movie objects. The whole point is that the user should only interact with the class Movies, therefore I have chosen to make all the me... | If the constructor/destructor is declared as private, then the class cannot be instantiated. If the destructor is private, then the object can only be deleted from inside the class as well. Also, it prevents the class from being inherited (or at least, prevent the inherited class from being instantiated/destroyed at al... |
66,246,536 | 66,246,986 | Why my C++ parallel program gives MPI fatal error in MPI_Gather? | My sorting program works fine with even number of elements in array, but gives error
" Fatal error in MPI_Gather: Message truncated, error stack:
MPI_Gather(sbuf=0x00A2A700, scount=4, MPI_INT, rbuf=0x00A302C8,
rcount=4, MPI_INT, root=0, MPI_COMM_WORLD) failed Message from rank 1
and tag -1342177184 truncated; 28 bytes... | TL;DR: With an even number of elements the processes call MPI_Scatter and MPI_Gather with the same count, with an odd number they don't.
My sorting program works fine with even number of elements in array
When the array size is even all processes execute the else part of:
if ((world_rank == 1) && (n % world_size !... |
66,246,551 | 66,246,661 | Any reason to use std::thread over std::jthread? | So C++20 has introduced std::jthread which, as I understand it, is just better than std::thread in every regard. So apart from the usual limitations like availabilty of C++20, quality of implementation, interaction with libraries, ... - is there any scenario where std::thread is the better choice?
| std::jthread is like a std::thread which owns a std::stop_source.
C++ is a language heavily built around the concept of not having to pay for what you don't use.
So: if you don't need a std::stop_source, you should prefer a std::thread so that you don't pay for one.
Even if you do need one, you still might prefer not t... |
66,246,631 | 66,246,729 | 'variable was not declared in this scope' while accessing global variable from a derived class's constructor | I have two classes in my application code. I divided the application into three files. One the header file 'header.h' , another is a cpp file 'header.cpp' in which all functions used are defined. Finally the main.cpp file that I am compiling using g++ compiler. Following are the contents of all three files.
1) header.h... | I believe header.cpp needs #include header.h
|
66,247,176 | 66,247,363 | How can I tidy my relative references using CMake? | I'm quite new to C++ and trying to get to grips with CMake and referencing files elsewhere in the project. My references within my test file currently looks like this:
#include "catch.hpp"
#include "../../src/containers/containers.h"
How can I tidy this up using CMake to have the following?
#include "catch.hpp"
#inclu... | Adding the line target_include_directories(containers PUBLIC "${CMAKE_SOURCE_DIR}/src") solved the issue and allowed my references to be reduced as desired.
|
66,247,393 | 66,247,429 | C++ std::unordered_map fastest way to insert new element only if it doesn't exist | I have an unordered_map storing large objects:
std::unordered_map<uint64_t, LargeObject> map;
LargeObject is an array of POD/there are no pointer members.
I am receiving a lot of LargeObjects, so I only want to insert them in the map if they don't already exist (there will be a lot of times they do already exist, as I ... | This is what try_emplace is for. The API is set up in such a way as to avoid constructing nodes, or even the value, unless it's strictly necessary. It comes form N4279.
In your case, that would be:
auto [it, success] = map.try_emplace(key, largeObject);
Each of the four options in the OP has issues:
map[key] = large... |
66,247,610 | 66,248,187 | Attempting to reference Deleted function shared_ptr | i have the following code
inline entity_ptr Parser::parse(const std::string& json_str)
{
// std::cout << "parse: " << json_str << "\n";
entity_ptr entity = do_parse(json_str);
if (entity && entity->is_notification())
{
notification_ptr notification = std::dynamic_pointer_cast<jsonrpcpp::Notifica... | Apparently "poorly defined member variables" can cause default functions to be deleted. (kind of strange)
https://stackoverflow.com/a/37517125/2934222
Try altering how you've defined this method maybe:
virtual Json to_json() const = 0;
|
66,247,851 | 66,247,911 | Make decltype output a non reference type when called with a pointer | Is there any way, using decltype or any other c++17 feature, to have the following code snippet
T *a = nullptr;
decltype(*a) b = 0;
compile to
T *a = nullptr;
T b = 0;
instead of
T *a = nullptr;
T &b = 0;
Where T is an unknown type.
| You can use either std::remove_reference or std::decay like
int *a = nullptr;
std::decay_t<decltype(*a)> b = 0;
|
66,248,223 | 66,258,496 | Passing values of different types to shader | I am using GLEW32 with GLFW and write code on C++. I have encountered some problems passing values to shader. I have successfully passed vec2, uvec3 etc. Now I want to pass multiple values for each vertex:
uvec2 (or vec2 - not very important) - X and Y position;
uvec4 - RGBA color. I can also use int to decode RGBA fr... | I found a solution in Kai Burjack's comment. I made a structure to keep data and send it. The code is:
struct dataToSend
{
GLushort x, y;
GLubyte r, g, b, a;
}
...
glVertexAttribIPointer(0, 2, GL_UNSIGNED_SHORT, sizeof(dataToSend), (GLvoid *) 0);
glEnableVertexAttribArray(0);
glVertexAttribIPointer(1, 4, GL_UNS... |
66,248,519 | 66,248,981 | Why is this soln faster than the other? | The problem is Leetcode's N-Repeated Element in Size 2N Array
In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.
Return the element repeated N times.
I'm confused Please help!
Faster code
class Solution {
public:
int repeatedNTimes(vector<int>& A) {
... | Here's some (untested) code using the method described above. I do assume that the input data is in the form described. If that is not the case this code will error.
class Solution
{
public:
int repeatedNTimes(vector<int>& A) {
// check for alternating elements at even indexes
if (A[0] == A[2])
... |
66,248,561 | 66,248,663 | Reading integers separated by semicolon from a file in C++ | For a lab assignment we have been given a data file that looks like this:
12; 5;
15; 14;
21; 1;
1; 22;
The idea is to extract the first two integers and add them together. Nothing I've tried has been able to extract the second number (5) from the file. So far this is what I've got:
void add_numbers()
{
std::ifstre... | The simple answer is to add a char variable to read the semi-colons,
int num1, num2;
char semi;
std::cin >> num1 >> semi >> num2 >> semi;
|
66,248,953 | 66,249,150 | Can partial_sort's middle iterator equal the end iterator? | According to http://www.cplusplus.com/reference/algorithm/partial_sort/, the middle argument is a:
Random-access iterator pointing to the element within the range
[first,last) that is used as the upper boundary of the elements that
are fully sorted.
Specifically, middle isn't allowed to be equal to last. However, htt... | The description of std::partial_sort in the standard (N4659, 28.7.1.3/2) reads
Effects: Places the first middle - first sorted elements from the range [first, last) into the range [first, middle). The rest of the elements in the range [middle, last) are placed in an unspecified order.
I see nothing here that would... |
66,249,127 | 66,249,753 | Allocating memory with new in the DLL - how to release? | I have many export functions in a DLL that output pointers, and they allocate memory in those functions. For example:
DLL_EXPORT void some_function(const char*** param)
{
*param= new const char*[somenumber];
//someting
//in some for-cycle
char* somestr = new char[somenumber1];
strcpy(somestr , somel... | No, std::string will not take ownership of the allocated memory. The user of your DLL is responsible for freeing the memory after done using it, such as copying it into std::string.
In this case, you must either:
export an additional function that the user of the DLL must call to delete[] the arrays when it is done u... |
66,249,176 | 66,249,302 | Save values in a std::vector from a Win32 API window procedure | I am new to the Win32 API. I have beginner questions.
How do I get and display values saved in a vector (mynum) in wWinMain()? How can I initialize it inside wWinMain()?.
I did it as a global variable, but there must be a better way.
I am using DestroyWindow(hwnd); inside the click event of a button, is this the cor... | You can declare the vector as a local variable inside of wWinMain(), and then use the lpParam parameter of CreateWindowW() to pass a pointer to the vector into your window procedure, eg:
#include <windows.h>
#include <sstream>
#include <vector>
using namespace std;
#define ID_EDIT 1
#define ID_BUTTON 2
LRESULT CALLBA... |
66,249,251 | 66,249,278 | cout return twice a string of char | The output of the below code is
Toto
TotoToto
but I would hope just
Toto
Toto
Why the second cout repeat the string in the output?
I'm using g++ version 7.5.0 on Ubuntu, I'm not sure if this is relevant.
The code is the following:
#include<iostream>
using namespace std;
int main(){
char c1[] = "Toto";
char c2[... | When you stream out a character array, it must - by convention - be null terminated, otherwise you have undefined behaviour.
Change c2 as follows and it will start working as hoped:
char c2[5] = {'T','o','t','o', '\0'};
In the case of c1, it assumes you'll want an implicit null appended and sizes c1 automatically to a... |
66,249,907 | 66,249,924 | Assigment expression | Will be Assigment operator (=) return the value of the left (or right part)?
QVector<function>::Iterator it;
binOp *bpl = nullptr;
bool b1 = (bpl = dynamic_cast<binOp *>(&*(it-2))) != nullptr;
So, i have my own class (binOp : function), and i try use dynamic_cast into expression. If i will use as... | The = assignment operator returns a reference to the left-hand operand. So, your 1st example will work just fine, and the result will be equivalent to your 2nd example.
|
66,249,929 | 67,075,776 | Sciplot c++ for scatter plots | Has anyone used the sciplot library in c++ for creating scatter plots?
https://sciplot.github.io/
I am fine with the examples for "normal" plots but I wonder if I am also able to create a scatter plot.
I do not find something in the documentation which mentions scatter plots.
An example code snippet would be great.
| Vec x = { 1, 2, 3 };
Vec y = { 4, 5, 6 };
Plot plot;
plot.drawPoints(x, y).pointType(0);
plot.show();
|
66,250,082 | 66,250,153 | Preprocessor error: cblas.h: No such file or directory | I am trying to see the output of a preprocessed .cpp file using the g++ compiler. I am doing this in the Windows command prompt. I type in g++ -E file.cpp in the command line but I get the error: cblas.h: No such file or directory
How do I go about fixing this problem?
| You can install lapack from here
|
66,250,297 | 66,250,318 | How to fill a char array without loop | I need help with filling up a char array in c++ with a letter and without using a loop. This is what i have so far.
int n, m;
cin >> n >> m;
char canvas[n][m] = {{'B'}};
This however won't work. Does anyone know how I can do this?
| You can do this pretty easily with a 2D std::vector:
int n, m;
std::cin >> n >> m;
std::vector<std::vector<char>> canvas(n, std::vector<char>(m, 'B'));
|
66,250,388 | 66,410,737 | PrintPreviewDialog issue on 4K monitor | I have added a print preview feature to my program. The problem is, it does not display the preview document well on screen resolutions above 1920 x 1080.
Example:
Code:
QFont docFont;
docFont.setPointSize(14);
QTextDocument *textDoc = new QTextDocument(this);
textDoc->setDefaultFont(docFont);
textDoc->setPlainText(ge... | I have found some hack to get the toolbar actions from a print preview dialog. By adding some additional logic it fixed the issue.
QList<QToolBar*> toolbarList = printPreviewDlg->findChildren<QToolBar*>();
if (!toolbarList.isEmpty()) {
if (screenSize.width() > 1920 && screenSize.height() > 1080) {
... |
66,250,700 | 66,250,746 | Writing text on heap - what does this mean? x[count++] = c; | I'm studying a code that writes text on the heap:
#include <iostream>
using namespace std;
int main() {
char c;
int count{0},d{0};
char *x;
x = new char[1000];
if(x != NULL){
cout << "enter the text,ending with by eof marker" << endl;
for(count=0; count!=cin.eof()&&count<1000;)... | This is doing a post-increment of count. The value of c will be assigned to x[i], where i is the old value of count.
It's equivalent to:
x[count] = c;
count = count + 1;
|
66,251,010 | 66,251,986 | Antlr4 c++ get name of rule from ParseTree * | While traversing the parse tree created, I need a way to get the name of the parser rule from the antlr4:tree:ParseTree * node that I am currently traversing
for example if the grammar is:
t: AB;
(ignore lexer rules for now) and t is some rule, I need to check if the node (type: ParseTree *) corresponds to rule t.
Tha... | kaby76 answer was correct
antlr4::RuleContext *x = dynamic_cast<antlr4::RuleContext *>(node);
auto ri = x->getRuleIndex();
auto name = parser.getRuleNames()[ri];
std::cout << name << std::endl;
where node is some node in the ParseTree, name will be the parser rule's name as std::string
Also as Mike Lischke says below,... |
66,251,568 | 66,251,740 | How do you initialize a union member after the union itself was initialized? | If it is even possible, how do you initialize a union member after the union itself was initialized?
struct U_Keeper
{
U_Keeper() : x();
bool HoldingTypeU {true};
union
{
X x;
Y y;
};
};
void doSomething(){
U_Keeper uk;
doSomethingWithX(uk.x);
// set uk to Y mode and ini... | If the union members are trivial, the traditional way to activate a member is to assign it:
uk.y = some_value;
If the members are non-trivial (such as std::string), then you must instead first destroy the currently active member, and then initialise the other using placement-new:
uk.x.~X();
::new (&uk.y) Y /*parenthes... |
66,252,027 | 66,252,098 | How do I fix my function definition that causes this error with my embedded class/struct: could not deduce template argument for 'T'? | I implemented a linked-list called Node that had a function called freeData where it would perform a delete on the node given and any following nodes.
I wanted to implement it inside my own custom list class as a private member, but came up with this error in Visual Studio 2019:
C2672 'freeData': no matching overloade... | freedata() is a free-standing function. Unlike class methods, free-standing functions have to be declared before they can be used. But, you can't forward-declare freedata() in this case since its argument depends on a type that needs to know what freedata() is. Catch-22.
To fix that, you could break up the declarati... |
66,252,082 | 66,252,121 | C++ - Is necessary another return on the end? | What If I have function return_num(), where I need return some value, but if I switch inserted value x, and I'm sure, that default will return value 1, if I enter anything else... Is necessary to add another return with value 1 to the end of function?
Compiler does not complain.
int return_num(int x) {
switch (x) {
... | Since the return type isn't void, it is indeeed necessary to not let the function execute to the end.
However, given that the switch returns in all cases, there is no need to add anything. Anything after the switch would be dead code.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.