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
65,218,804
65,219,092
I can't seem to figure out why my read/write to a file functions are not working
I've been doing my project and the last thing I need to do is to save to and start reading a structure array from a file on startup of the program, but I can't figure out why the code isn't loading the information of the file. I know that it does save something since I can open the .dat file and read it in a text edito...
The problem is that a C++ std::string is much more complex than a char array. The implementation is not mandated by the standard, but in common implementation, the string element contains a pointer to a character array. That means that your code only stores into the file a pointer value instead of a character string. I...
65,219,640
65,219,917
Why are C++ unit tests failing with die program
I have the following program written: die.h class Die { public: // Randomly assigns a value to roll_value in the range of 1 to 6 void roll(); // Returns roll_value int rolled_value() const; private: // Stores a randomly assigned value int roll_value; // Di...
You're experiencing undefined behavior. It is not legal to read a value before it's initialized. Your test is showing something interesting: What should be the value of a die when you haven't rolled it yet? Maybe you should have a zero value, or maybe the die should be rolled when constructed.
65,220,208
65,220,288
Conversion of const char** to std::vector<const char *>
I am currently working on a Vulkan project that uses the glfw library for window handling. To get the required extensions glfw provides const char** glfwGetRequiredInstanceExtensions(uint32_t *count). To avoid passing around a const char** together with the count i wrote a simple helper function that converts the const...
From the Vulkan docs on glfwGetRequiredInstanceExtensions(): Pointer lifetime The returned array is allocated and freed by GLFW. You should not free it yourself. It is guaranteed to be valid only until the library is terminated. So you don't need to worry about the memory at all. std::vector will clean up after itsel...
65,220,210
65,220,396
strange phenomenon about C++ memory address
That is just crazy! In order to figure out how objects store in memory in C++, I write the following code to see the address of variables. But things get more confused. So in the following I wonder why 1 is different from 2 ------does this means that it's a pointer? but why? why 1 is different from 3 ------it's passed ...
The format specifier %p requires that the argument is of type void*. If you pass an argument of wrong type, then the behaviour of the program is undefined. printf(" persons: %p\n", persons); Here, you pass an argument of type vector<A>, therefore the behaviour of the program is undefined. Since The argument isn't ev...
65,220,803
65,220,853
Add integer to each item of unordered linked list
I want to write a function that adds an integer (passed as an argument to the function) to each item in the unordered linked list. Here is the complete program. #include <iostream> using namespace std; //creates a node class class Node { //defines data, and next as a pointer. private: int data; //data in the be...
You probably want something like the following: current->setData(current->getData() + item); Note that now you are retrieving a return value in the left-hand side, then trying to assign to it. This is what your compiler is telling you, presumably.
65,221,476
65,627,114
How to translate a union inside a struct from c++ to python with SIP?
I answered this question explaining how to translate a union from c++ to python with SIP (unions are not automatically supported). When I use this type of wrapping for a union inside an existing struct I get the following error message when I try to build with sip-install (I renamed 'wrapped_u' to 'u' and 'test_u' to '...
Unions are supported since Sip version 6.0.0. Thank you for the quick integration Riverbank Computing. Hopefully the manual way to do the translation will not be necessary any more.
65,222,182
65,222,617
Segmentation fault while returning a Node Linkedlist
In find(T item) function I am checking if the data inputted is a string then I am handling it separately and for other data types I am handling it in else case, because I am using the string function compare() to check for the match. The program runs fine when there is a matching string in the linked list and returns t...
For starters the member function find can invoke undefined behavior in the very beginning Node<T>* find(T item){ Node<T> *tmp = head; if (typeid(item) == typeid(string)){ string s, d; s = item; d = tmp->data; ^^^^^^^^^^^^^ // because in general head can be equal to nullp...
65,222,289
65,222,771
Makefile - No such file or directory of file.h ( Can't find the solution)
I was trying to make a Makefile so I can develop my code a bit faster. My Makefile is the following: IDIR =../include CXX=g++ CXXFLAGS=-I$(IDIR) LDIR =../lib LIBS=-lm _DEPS = person.h DEPS = $(patsubst %,$(IDIR)/%,$(_DEPS)) OBJ = main/main.o ../modules/person.o $(ODIR)/%.o: %.c $(DEPS) $(CXX) -c -o $@ $<...
The problem is this: OBJ = main.o ../modules/person.o $(ODIR)/%.o: %.c $(DEPS) $(CXX) -c -o $@ $< $(CXXLAGS) So, this pattern rule tells make how to build a file that matches the pattern ../modules/%.o and it adds the CXXLAGS variable to the compile line. But you have not provided a rule for building main.o...
65,222,331
65,231,456
Configuration-specific add_custom_command with Xcode generator
I want to create a custom command that will merge all static libraries into a fat static library using Apple's libtool command during build. I'm using Xcode generator and CMake 3.19.1. My script is like this: set( TARGET_OUTPUT_NAME ${CMAKE_BINARY_DIR}/fat-libs/${CMAKE_CFG_INTDIR}/lib${libname}.a ) add_custom_command( ...
Actually, the trick is in using COMMAND_EXPAND_LISTS. As explained in this CMake gitlab issue, the correct CMake script is: set( TARGET_OUTPUT_NAME ${CMAKE_BINARY_DIR}/fat-libs/${CMAKE_CFG_INTDIR}/lib${libname}.a ) add_custom_command( OUTPUT ${TARGET_OUTPUT_NAME} COMMAND /usr/bin/libtool -static...
65,222,800
65,222,922
Recover type of generic collection given as template
I am working on a generic class that essentially works like that template<typename T, typename Collection> class myClass { T attr1, attr2, attr3; //Attributes are actually stored in multiple list-like nodes public: void method1(Collection<T> arg) { attr1 = arg[0]; attr2 = arg[1]; attr3 = arg[2]; } }...
I see two ways. If your intention is to use standard containers, you can count on the value_type member type. So, I suppose something as template<typename C> class myClass { using my_type = typename C::value_type; my_type attr1, attr2, attr3; public: void method1 (C arg) { attr1 = arg[0]; attr2 =...
65,222,905
65,227,591
Undefined reference error to static constexpr data member
I'm very confused as to what is wrong here. I am getting an undefined reference error to an array I have defined the same way as two others which are not throwing errors elsewhere in the code. undefined reference to `shift7seg::numbers' shift7seg.cpp code showing other function using similarly defined arrays being use...
Somewhere in your code you are ODR-using numbers but you don't have a definition for it. Here's a simple version of your problem (wandbox): #include <iostream> #include <cstdint> class shift7seg { public: static constexpr std::uint8_t numbers[10] = {}; }; int main() { // taking the address is ODR-use std::co...
65,223,188
65,223,480
How do I avoid creating copies of the base class when inheriting? C++
I have a "Database" class that has a map that stores users. There is also an "Auth" class that inherits from "Database" and gets a map of users in order to find the right user during authorization. There is also the "Admin" class, which also inherits from "Database" and can add new users. But the problem is that when i...
Problem: Auth and Admin need access to Database members but they shouldn't create a new instance of Database. Solution: Is hard to help without a Minimal Reproducible Example, but from what it can be seen you should probably use friend classes instead of inheritance and pass the databases to the classes by reference. S...
65,223,296
65,223,880
uniform_real_distribution has a huge performance difference between Code Blocks and Visual Studio 2019
I try to transplant project from Code::Blocks to Visual C++ 2019. After that, I am undergoing some performance problems. The most considerable performance dropping is that when I need to generate large amount of random double variables. After Searching for information from the internet, I still can't give a reasonable ...
First, thanks for @churill commented. His advice is very useful. There are a lot differences between Debug and Release. The key factor of influence to this problem is that Release will optimize when compiling. For more information: https://stackoverflow.com/a/938665/6367757 medium article
65,223,726
65,224,233
How to efficiently iterate over std::(unordered)set when deleting items from it?
I have a bunch of elements stored in some container. Their order does not matter for me. I iterate over my container and check some predicate - P for each of the elements. If P is true - remove the element from the container. If P is false - just go to the next one. If at least one element was deleted during the iterat...
Use std::erase_if() in a loop: while (std::erase_if(your_set, your_predcate)) /**/; If you don't have C++20, don't despair. Cppreference.com gives an example implementation too. If it proves to be a bottleneck, hand-rolling your own all_erase_if() with a specialization for node-based containers might be useful: te...
65,223,791
65,229,085
Raspberry pi 4 to arduino via usb Serial for robot car
I am trying to code a line follower car using a Raspberry Pi with camera, Arduino and an l298n motor driver. I am trying have the Raspberry Pi communicate with the Arduino using USB serial and I am struggling a bit. Here is the code I have for the Arduino: #define leftEnable 6 // EnA #define leftReverse 8 // IN1 #...
You are missing with serial ports commands on both ends. Send commands to serial port like this on raspberry pi ser = serial.Serial() ser.baudrate = 19200 ser.port = '/dev/ttyACM0' ser.write(b'L') # send codes like 'L' for left,;'R' for Right Read commands on arduino like this void setup() { // initialize serial: ...
65,223,974
65,224,280
I have 2 sets of data mapped to each other. Is there a way to based on the value of another variable check that corresponding variable for its value?
So I have 64 variables called S0O through S63O. These are corresponding to the chess squares on a board. Now I have a function that walks through and marks each of these variables as TRUE(Occupied) or FALSE(Empty). Now i'm trying to take a variable(BP1 aka Black Pawn 1) which has a value 0 through 63 and I want to chec...
As François Andrieux pointed out if I use an array to put all these in a grid I can move about and edit specific "squares" inside of the board. So if my input is stored in variable BP1P = 48; Then I can take this value and check for it occupied with something like ([BP1P-8] == 'O').
65,224,592
65,225,200
Is there a code preprocessing tool that would merge multiple user defined includes (an no system includes) into one file?
I have a project consisting of multiple c++ files. I need to merge all of those files into one main.cpp file and send one file over the network. The recipient at the other end will compile and run the file: gcc main.cpp ./a.out Note that the recipient at the other end is a program, expecting only a single file and wil...
I don't know of any preprocessor techniques to do this, but there are other possibilities. I read that you simply want to send a single compile-able main.cpp file for online coding competitions, so that's what I was working with. If you have access to command-line tools, you could simply use sed. If you change all your...
65,224,705
65,226,552
Exiting loop by keystroke without waiting for input
bool stop = false; int hours = 0; int minutes = 0; int seconds = 0; while (stop == false) { system("cls"); cout << "Hours Minutes Seconds\n"; cout << hours << " " << minutes << " " << seconds << endl; Sleep(1000); seconds++; i...
bool stop = false; int hours = 0; int minutes = 0; int seconds = 0; while (!_kbhit()) { system("cls"); cout << "Hours Minutes Seconds\n"; cout << hours << " " << minutes << " " << seconds << endl; Sleep(1000); seconds++; if (seconds == 60) { minutes++; ...
65,224,706
65,224,871
How would I initialise a 2D vector of objects in a constructor of a class? (C++)
I am currently attempting to create a class containing a 2D vector of structs, however I am clearly doing something tragically wrong as whenever I run my code, I get the error at line 19 (the line in the for loop in the world constructor) error: expected primary-expression before ‘)’ token Here is my code at the moment...
You need to construct the vectors you are attempting to push_back. // Note the added parentheses after <Cell> state.push_back(std::vector<Cell>()) In this case, push_back is expecting a value, or an "expression" which evaluates to a value. Your expected primary expression before ')' token error more or less means that...
65,225,172
65,225,344
Dependent template names and C++20 ADL
Consider the following example: namespace N { template<class> struct C { }; template<int, class T> void foo(C<T>); } template<class T> void bar(N::C<T> c) { foo<0>(c); } int main() { N::C<void> c; bar(c); } Both GCC and Clang fail to compile this code under C++17 standard (with -Werror),...
This is P0846, which is a C++20 feature. It appears that gcc does not implement this yet. It's not a question of dependent name or not, it's a question of does the compiler know that foo refers to a template or not, and so is foo< doing a comparison or is it starting to do template parameters. In C++17, the compiler ha...
65,225,521
65,225,687
Creating member variable in C++ QObject subclass accessable from QML?
Say I have a QObject subclass Foo defined in C++: class Foo : public QObject { Q_OBJECT public: /* ... */ }; and say I attach it to the root context of a QQmlApplicationEngine as like: Foo foo; QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("foo", (QObject*)&foo); so now I can call a Q...
You have to create a Q_PROPERTY: #ifndef FOO_H #define FOO_H #include <QObject> class Foo : public QObject { Q_OBJECT Q_PROPERTY(int bar READ bar NOTIFY barChanged) public: explicit Foo(QObject *parent = nullptr); int bar() const; void setBar(int bar); Q_INVOKABLE void doStuff(); Q_SIGNALS: ...
65,226,057
65,444,236
constexpr variable not captured
The following code does not compile in clang (it does in GCC): struct A{ int a; }; auto test(){ constexpr A x{10}; return []{ return x; // <-- here x is A: clang doesn't compile }(); } Clang's error is variable 'x' cannot be implicitly captured in a lambda with no capture-default specified, bu...
When you return x; in the first example, you have to invoke A’s copy constructor, which involves binding a reference to x and thus odr-uses it. The argument can be made that a trivial copy of a value usable in constant expressions shouldn’t constitute an odr-use any more than return x.a;, but there’s no such exception...
65,226,369
65,226,550
Unable to find breakpoint when debugging a cpp source file when invoked from .sh
I need to set breakpoints in a cpp source file. The current setup to call the cpp target is through a shell target, with additional dependencies, which means it's not feasible to directly invoke the cpp target in Linux console. As I searched online, there are generally two ways: invoke gdb in shell pause in cpp, let g...
You need to compile the program with debug symbols. Otherwise GDB will only know of symbols in the dynamic symbol table. Turning off optimizations also helps debugging. So add the flags -O0 -g. If this is not possible, you'll have have to step through the disassembly (Ctrl+X, 2).
65,226,558
65,226,665
Remove an object from an array of pointers
I have an array of pointers that point to Building objects that look like this: class Building { int id ; int year; double price; char* adress; }; What I'm trying to do is to remove objects from the array via the id using operator-, but I don't really know how to do so. My list class looks like this: c...
Your operator- is not implemented correctly. Although its loop to find an object is fine, removing that object is broken. You are not updating the array correctly, as you need to shift down ALL of the array elements after the found index, which you are not doing. Also, make sure your List class implements the Rule of...
65,227,007
65,227,272
Trying to find the minimum element of 2D vector with lambda
I'm currently trying to find the minimum element of a 2D vector. I'm trying to practice using C++11 lambda functions and figured this might be good practice, but can't seem to get it compiling. I'm aware that I could do the following: vector<vector<int>> matrix = { {1, 2, 3, 4, 5 }, ...
I've compiled a working version that does what I've mentioned in the comments: #include <vector> #include <algorithm> #include <iostream> int main() { std::vector<std::vector<int>> matrix = { {1, 2, 3, 4, 5 }, {6, 7, 8, 9, 10 }, {5, 6, 8, 1, 12 }, {1, 7, 2, 4, 18 }, }; std:...
65,227,047
65,232,556
Detect the coin and from there measure the leaf in the image
Friends, I am trying to detect the coin first, since I already know its size is 1.011cm2. And then measure the leaves in the image. I am using findContours, but I am not always able to distinguish the currency first, I have also tried to use hougCircles but it is not working in my case. Would anyone have any ideas? Ope...
If your setup has constant white-ish/gray-ish background and green leaves, I'd use the HSV color space to detect all objects using the S channel (the green leaves and the golden part of the coin will have significantly more saturation than the background) and then distinguish between the coin and the leaves using the H...
65,227,200
65,256,203
Accessing/wrapping a struct inside a class in Cython
I am trying to wrap the btCollisionWorld C++ class of the Bullet Physics library with Cython. I have had good success generally with the physics simulation parts of the library but I have run into trouble trying to wrap the collision detection parts. If you look at https://github.com/kripken/bullet/blob/master/src/Bull...
I think you're just failing to distinguish between the type name and the member name. Something like this works for me (at least gets through the cython stage): cdef extern from *: cdef cppclass btCollisionWorld: struct LocalShapeInfo: int m_shapePart LocalShapeInfo m_shape cdef...
65,227,689
65,228,265
Sending Unicode string from C# to C++ working in one project but not another
I have built a test harness solution with two projects in VS2017, a C# project where I am sending a unicode string and a C++ DLL where I receive it and show it in a MessageBox. My C# code is: [DllImport(@"TestDLL.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)] private static extern ...
First stop returning the cv::Mat from your function. Exporting a class has never been advisable. Furthermore the OpenCV cv::Mat is not being exported. Also, to avoid name mangling prefix the function definition with extern "C": extern "C" __declspec(dllexport) void __stdcall ProcessOneFile(wchar_t *FullFilePath)
65,227,720
65,229,026
Troubles with laying out memory for use by OpenGL (glBufferSubData help needed)
So today I wanted to learn how I can use a Vector2 & Color class to send data to OpenGL with pretty clean looking syntax. The plan is this. /* Vector2 (8 bytes) Color (16 bytes) Vector2 + Color = 24 bytes How can memory be laid out like this? {Vector2, Color}, {Vector2, Color}, {Vector2, Color} */ So I have my t...
You need to add 1 vertex and 1 color alternately to the buffer: for (int i = 0; i < 3; ++i) { GLintptr offsetV = i * (sizeof(Vector2) + sizeof(Color)); glBufferSubData(GL_ARRAY_BUFFER, offsetV, sizeof(Vector2), &vertices[i]); GLintptr offsetC = offsetV + sizeof(Vector2); glBufferSubData(GL_ARRAY...
65,227,728
65,227,789
Why does `*this` resolve to the subclass?
// Example program #include <iostream> #include <string> class A; class B; void h(A &a) { std::cout << "a"; } void h(B &b) { std::cout << "b"; } class A { public: virtual void call() { h(*this); } }; class B: public A { public: void call() override { h(*this); } }; int main() { B b = B{}; A &te...
h(test); // prints a Since the type of test is A &, that's the overload that gets called. There's nothing more to say here. The End. The books are closed on this subject matter, and this is the compiler's job to do, here. The compiler figures out which overload to call based on what test is. test.call(); This invokes...
65,227,752
65,228,209
Appending an unsigned char to a vector changes its value
I have the following 2D vector: vector<vector<unsigned char>> dates; I also have the following unsigned char array: unsigned char date[3] = {1, 18, 108}; When I push_back this array to dates it sets all the unsigned char elements to 204: date = ADP::addDay(date); cout << int(date[0]) << '-' << int(date[1]) << '-' << ...
addDay is returning a pointer to a stack variable that's going out of scope; the pointer is invalid the moment the caller has access to it. Replace C-style arrays with std::array or std::vector (or std::tuple, given the position probably has meaning independent of the value stored) if you want this to work. The most mi...
65,227,766
65,228,269
which are the rewritten candidates for != operator
The relevant rule in the standars says: over.match.oper#3.4.3 The rewritten candidate set is determined as follows: For the relational ([expr.rel]) operators, the rewritten candidates include all non-rewritten candidates for the expression x <=> y. For the relational ([expr.rel]) and three-way comparison ([expr.spac...
I suspect that this is granted by [over.match.oper]/3.4.4: For the equality operators, the rewritten candidates also include a synthesized candidate, with the order of the two parameters reversed, for each non-rewritten candidate for the expression y == x. Equality operators are both operator== and operator!=. Also n...
65,228,163
65,228,330
Linker error when using class declarations from header files
I'm setting up a class in a file called "initialize.cpp" and adding a declaration in "Engine.h". When i try to use that class in Main, it gives me a linker error for each function being used. unresolved external symbol "public: int __cdecl Application::run(void)" (?run@Application@@QEAAHXZ) referenced in function main ...
here is initialize.cpp #include<GL/glew.h> #include <GLFW/glfw3.h> class Application { public: int run() { /* Initialize the library */ if (!glfwInit()) return -1; //... This is not how you implement the member functions of a class. What this does is define a completely different class App...
65,228,271
65,228,404
C++ Error: Expected unqualified-id and use of undeclared identifier error?
I get repeated errors like this: error: use of undeclared identifier 'item' and "error: expected unqualified-id cin.getline(*(cart->(item+i)->itemName), SIZE1);. When I used pointer notation with the arrow operator when accessing a struct within a struct. I understand that I am only filling in some of the members of th...
You should use cart->item[i], which is more readable and easily gets the precedence right. If you still want or need to use addition with pointers, you need to place the parentheses differently: (cart->item+i)->itemName because item is a member of the ShoppingCart cart.
65,228,549
65,228,608
Is it possible to write a generic arithmetic function in C++?
I'd like to write a set of generic arithmetic functions that can act on any type that passes the is_arithmetic test. For example, this min function is ok: template<typename T> T min(std::vector<T> values) { T min = values.at(0); for (T& value : values) { if (value < min) { min = value; ...
Declare sum as T sum = 0; and you'll have what you're looking for. If you need the sum to be of different type than the vector holds, then use a second template parameter, e.g. template<class T, class U> U average(std::vector<T> values);. You'll have to specify U when you call the function, though. Note - these are t...
65,228,898
65,231,184
QJsonDocument to object is empty
I'm trying to parse a simple JSON data in Qt5. Code looks like this : ... socket->readDatagram(Buffer.data(),Buffer.size(),&sender,&senderPort); QJsonParseError jsonError; QJsonDocument dataJson = QJsonDocument::fromJson(Buffer.data(),&jsonError); if (jsonError.error != QJsonParseError::NoError){ ...
Assuming that you're reading correctly, you should test with a command like this: echo -n \{\"x\":1,\"y\":2,\"\z\":3\} > /dev/udp/127.0.0.1/8080 So, get rid of single quotes and escape curly brackets. Even better: put your json data in a myfile file and use cat myfile > /dev/udp/127.0.0.1/8080
65,228,947
65,230,023
How to disable VS2019's syntax coloring for C++ and make it look like VS2017
I'm a light theme user, and I guess that makes me unpopular, but I'm sure there are still some light theme users out there. I have switched to VS2019 and the light theme (called Blue Theme) was a nightmare. It turned out it was an issue and the solution can be found in this thread. My other question is the C++ syntax c...
It looks the only way to solve this problem is to change the colors one by one. But you may ask, how do I come up with colors, I'm not a graphic/UI/UX designer? Here's how. You open the colors in VS2017 in Options->Fonts and Colors and select Text Editor in Show settings for:, and there when you scroll down you will se...
65,229,309
65,230,980
Segmentation fault in solving dynamic problem
Is there any difference in these type of calculating ans in dynamic problems ? Because in case of Code 3 I am getting segmentation fault while Code 1 and Code 2 are passing int dp[8005][2];//dp is initialized as -1 in main int a=4; int b=6; int tar=90; int solve(int pos,int ba) { if(pos<0||pos>8000||ba>=2) ...
Code 3 doesn't update dp until after all the calculations are done. The first two go Recurse Update dp Recurse Update dp Return new value Note that 1 and 2 are equivalent, since ans is the same as dp[pos][ba]. The third is Recurse Recurse Update dp and return the new value
65,229,494
65,231,888
Why does XMMatrixLookAtLH result in a debug error?
I am developing a DirectX 11 game in C++ and I am trying to create a view matrix but when I do I am getting the following debug error: Assertion failed! Program: ...ate-Direct3D11\Build\Debug\Template-Direct3D11.exe File: C:\Program Files (x86)\Windows Kits...\DirectX...rix.inl Line: 1971 Expression: !XMVector3Equal(...
The eyPos and the lookAtPos you are setting are the same value... The result is a 0-length unit vector for direction. DirectX::XMVectorSet is not the best way to initialize a constant vector. Read the DirectXMath Programmer's Guide particularly the Getting Started guide.
65,229,522
65,236,873
Standard library algorithm to average the difference between adjacent elements
I have a std::vector<std:::chrono::system_clock::time_point> values. I want to average the time difference in milliseconds between adjacent elements. The container requires at least 2 elements and I am having trouble with the averaging function. I was using std::accumulate but I don;t think I can quite get that to wo...
As cigien suggested in the comments, here's how to do it with inner_product: auto result = inner_product( timeStamps.begin() + 1, timeStamps.end(), timeStamps.begin(), 0ms, [](auto x, auto y) {return x + y;}, [](auto x, auto y) {return round<millis...
65,229,927
65,230,288
What does more specialized mean when specializing a primary template?
C++ template specialization rules mentioned specialization has to be more specialized than the primary template. Following #1 code snippet causes compilation error which says the second line is not more specialized, but the last snippet (#2) works which looks very close to #1. Both code snippets specialized int N as 0,...
For more specialized: Informally "A is more specialized than B" means "A accepts a subset of the types that B accepts". Whatever types the specialization could accept are supposed to be subset of types the primary template could accept. But for B<0>, it could be accepted by the specialization only, while the primary ...
65,230,737
65,232,906
Why the compiler complains: the value of ‘testFunc’ is not usable in a constant expression?
Why the compiler complains: the value of ‘testFunc’ is not usable in a constant expression. But reg(regHelper<&ctx::map_create>);is ok. Why? Here is the code snippest: class ctx { public: int map_create(void*){return 0;}; }; typedef int (ctx::*ctx_mem_func)(void*); template <ctx_mem_func func> int regHel...
From constant_expression#Usable_in_constant_expressions a variable is usable in constant expressions at a point P if the variable is a constexpr variable, or it is a constant-initialized variable of reference type or of const-qualified integral or enumeration type pointer on member doesn't have the "exception...
65,230,764
65,231,142
How to implement protocol which resends messages using BOOST ASIO
I am implementing protocol with BOOST ASIO which resends response in case it was not acknowledged. I use async_read_some() and deadline_timer running asynchronously alongside to see whether I received whole message or whether timer expires first and new message will be sent. Question is if deadline_timer expires first ...
I'm not sure why you want to interrupt async_read_some if you want to read a new message anyway. There seems to be some flaw (or misunderstanding) in the protocol you are implementing. This is a question about protocols, not concrete implementation. The real question is: how do you synchronize sends and reads? Meaning ...
65,230,767
65,243,154
How can I solve this compiling error on CLion?
I use as the main directory one called CLionProjects, on it I have several directories. Recently I added those directories so to organize my files. I used since the first time I installed CLion a directory called "Boletin1" that it's inside the main directory, later when I created "Boletin2" (In these directories I hav...
Try to rename your directory to Boletin1 and Boletin2 REMOVE ALL ACCENTS and write it with the boring i letter, even if the spelling is then wrong in your language. This is an encoding problem and it occurs because in this case you have 3 programs (here cmake, gcc.exe and mingw64-make.exe) that parse the same characte...
65,231,036
65,231,396
How to use CuteLogger in Qt qmake based project?
I was able to build a Qt CuteLogger project using cmake. Following is the code, pretty much what is explained in https://github.com/dept2/CuteLogger. I guess I can also use cutelogger in non cmake projects, like qmake or even in visual studio. May I ask for instructions on how to do that? I'm new to both cmake. main.cp...
A simple solution is to create a .pri that includes the .cpp and .h: ├── 3rdParty │   ├── CuteLogger │   │   ├── CMakeLists.txt │   │   ├── CuteLogger.pro │   │   ├── CuteLogger.qbs │   │   ├── Doxyfile │   │   ├── include │   │   │   ├── AbstractAppender.h │   │   │   ├── AbstractStringAppender.h │   │   │   ├── Andro...
65,231,048
65,408,133
Rendering CGAL::Triangulation_3 Glitches on edges
How I would have to proceed to render a Delaunay 3D triangulation ? I'm getting glitches in the edges... and its normal given that there are three facets colliding there, so three values of normals around the edge. I need a triangulation because I'm working in a cristal look with transparency and inner facets so convex...
Sort facets in camera axis to avoid glitches on edges works
65,231,178
65,231,298
No instance of overloaded function toupper matches the argument list
I am trying to use toupper to convert first letter to uppercase in string but it keeps showing error code below: no instance of overloaded function"toupper"matches the argument list Code: #include<iostream> #include<cstring> #include<cctype> using namespace std ; int main() { string s("some string"); if(s.b...
Dereferencing the iterator with * operator will do the work: *c = toupper (*c);
65,231,319
65,232,333
Detect digital input from 2v5 src on a chip with 3v3 power?
I'm using a 12F675 PIC and I have programmed it to make 3 LEDs flash in sequence. I want it to only do this when a particular input is NOT received. The PIC is running at 3v3 and that seems to be enough to power the chip and the LEDs when I test it. The input is from another LED on a different PCB, basically I want to ...
There is a problem in your code here: if (GPIO & 0b000000). You do a bitwise AND between something and 0 - that is always 0, and 0 always evaluates to false. You want something like: if ((GPIO & 0b001000) == 0b001000) or if ((GPIO & 0b001000) == 0b000000) extra parenthesis because I can't remember if & or == has prece...
65,231,628
65,238,194
Can I use boost::copy_range on the result of boost::adaptors::transformed over std::array to get back another std::array?
This code works and generates the correct output (23, as 2 and 3 are the sizes of the two std::vector<int>s in array_of_vectors: #include <array> #include <boost/range/adaptor/transformed.hpp> #include <iostream> #include <vector> using boost::adaptors::transformed; constexpr auto get_size = [](auto const& snip){ ret...
If you compile with -std=c++2a, gcc 10.2 has a nice error message: boost_1_74_0/boost/range/iterator_range_core.hpp:842:38: error: array must be initialized with a brace-enclosed initializer 842 | return SeqT( boost::begin( r ), boost::end( r ) ); | ~~~~~~~~~~~~^~~~~ The pr...
65,232,157
65,232,356
Merge overlapping intervals - it doesn't work properly for negative numbers
I've tried to do this exercise myself but I couldn't make it work properly for negative intervals. Then I implemented the version from geeksforgeeks and I get the same thing. Here's the logic behind it: 1. Sort the intervals based on increasing order of starting time. 2. Push the first interval on to a stack. 3. F...
When you read input you do: void Interval::citire() { std::cin >> lo >> hi; } And you assume that lo < hi. However, your input with negatives is: 5 -2 -4 -1 -3 -5 -8 -10 -12 -6 -9 And all intervals have first the larger number and then the smaller one. Either your input is invalid and it should be: 5 -4 -2 -3 -1 ...
65,232,193
65,430,081
How do I capture the key press event for an edit cell of a QTableWidget?
Here are 2 answers for capturing the key press event for QTableWidget. How to create a SIGNAL for QTableWidget from keyboard? Follow the way above, I can "hook" key press event, When I press space, the background color becomes red. However, it only works for a selected cell, but not for a in-editing cell. When it's i...
When it's in "editing state" there is editor widget atop QTableWidget (item delegate) which receives key events, and since it's on top you can't see cell content and cell background behind it. But you can access and "hook" this events by setting QAbstractItemDelegate to QTableWidget. // itemdelegate.h class ItemDelegat...
65,233,303
65,233,304
Disable squiggly lines for C++ (Visual Studio 2019)
I want to disable squiggly lines in C++ completely for taking screenshots. I already have done so in Tools/Options C++ / Advanced / Disable Code Analysis Squiggles C++ / Advanced / Disable Intellisense Squiggles Yet, I still have squiggly lines as in this code: volatile const unsigned const long unsigned int vola...
It turned out I had Resharper installed. Disabling Code Analysis in Resharper options helped. I now have beautiful non-squiggled C++ code like
65,233,377
65,235,798
Mocking read/write functions and receive warnings of redundant redeclaration
I use gtest and gmock for my unit tests, I mock unistd read/write functions for input, sending and receiving testing(C function Gmock): class MockSysFuncs { public: MOCK_METHOD3(read, ssize_t(int, char*, size_t)); MOCK_METHOD3(write, ssize_t(int, const char*, size_t)); sem_t readSem; static std::shared_ptr<Moc...
Your warning is about redundant declarations, so just remove them: #include <unistd.h> // declare read/write class MockSysFuncs { public: MOCK_METHOD3(read, ssize_t(int, char*, size_t)); MOCK_METHOD3(write, ssize_t(int, const char*, size_t)); sem_t readSem; static std::shared_ptr<MockSysFuncs> _mockSysFuncObj;...
65,233,487
65,233,600
Get raw type inside std::reference_wrapper in type trait
Problem I have a custom vector type for math operations. I can give it a type directly MyVector<2, int>vec{4,5}; or a reference_wrapper int num1 = 4; int num2 = 5; MyVector<2, std::reference_wrapper<int>> vec2{std::ref(num1), std::ref(num2)}; which both works. However, i'd like to restrict the MyVector class to only ...
You might try: template <typename T> struct unwrap_ref { using type = T; }; template <typename T> struct unwrap_ref<std::reference_wrapper<T>> { using type = T; }; template <typename T> using unwrap_ref_type = typename unwrap_ref<T>::type; And use static_assert(std::is_arythmetic_type_v<unwrap_ref_type<T>>)...
65,233,810
65,235,221
How to draw a line under the title cells on TDBGrid using C++ in Rad Studio?
I am trying to draw a line under TDBGrid title cells but can't seem to get it to work. I am doing this in the OnDrawColumnCell event like this: Canvas->Pen->Color = TColor(RGB(0, 0, 0)); Canvas->MoveTo(Rect.Left, Rect.Bottom); Canvas->LineTo(Rect.Right, Rect.Bottom); It's signature looks like this: void __fas...
OnDrawColumnCell is not called for title cells. As far as I can see in TCustomDBGrid source code, title drawing is done by an inner procedure you can't change from the outside. Probably you have to derive a new component and override DrawCell which does all the processing. You didn't show your complete code for dbGridM...
65,233,816
65,243,735
boost::interprocess::message_queue no message received in second process
I am using boost's message queue to write a basic class with just two char arrays, but the data is not being received in the second process is empty, even though get_num_msg() returns 1 before the read and returns 0 after reading. For debugging purposes I also tried writing and reading from the same process, and that w...
Looks like p1 (in the sending function) is a smart pointer (like std::unique_ptr or std::shared_ptr). In that case this->mq->send(&p1, sizeof(p1), 0); is obviously wrong, because it puts the pointer object on the queue, instead of the data structure. Use this->mq->send(*p1, sizeof(*p1), 0); Or, indeed, don't use dyna...
65,234,338
65,235,019
Why this code snippet works with C++17 whereas the compiler complains when using C++11?
Why this code snippet works with C++17 whereas the compiler complains when using C++11(i.e https://godbolt.org/z/71G91P)? Are there any potential problems with this code snippet? #include<iostream> class ctx { public: int map_create(void*){std::cout << "haha" << std::endl; return 0;}; }; ctx obj; typedef ...
This is a difference between C++14 and C++17. Simplified: int f(); template<int (&)()> struct S {}; constexpr auto& q = f; using R = S<q>; // valid in C++17, invalid in C++14 The change is to Allow constant evaluation for all non-type template arguments, meaning that now a constexpr variable naming a function (member ...
65,234,783
65,238,597
Qt QThread stop when I need
//Work.h #ifndef WORK_H #define WORK_H #include <QDebug> #include <QObject> #include <QThread> class Work : public QObject { Q_OBJECT public: explicit Work(QObject *parent = nullptr); public slots: void snap(); void setStatus(); signals: private: bool status; }; #endif // WORK_H //Work.cpp #inclu...
Firstly consider your Work::snap implementation... void Work::snap() { status = true; while (true) { if (status) { qDebug() << "Work thread: " << QThread::currentThreadId(); } else { qDebug() << "STOP"; break; } } } Once started it never yields control to the Qt event loop. Now con...
65,235,012
65,235,073
C++ program error on passing arguments to the parameterized constructor by pointer object?
I have a class called sample. class sample { private: int Age; public: sample() : Age() {} sample(int age) { this->Age = age; } }; In main int main() { sample* s = new sample(); s(21); return 0; } I want to pass values to the parameterized constructor through pointer object bu...
You've already constructed the object when did new sample(), so you can pass your constructor values right there. You cannot construct the object twice. Do it like this: sample* s = new sample(21); or sample* s; s = new sample(21);
65,235,027
65,235,461
Function call with template parameter
I have written a simple class template: template <class T> class my_class { public: my_class(T value) : my_Value(value) { } private: T my_Value; }; Now I can use this template in a simple function signature like: my_function(my_class<std::string> my_string) When I want to call the function I ca...
You can have only one implicit user-conversion, so your call with const char* is invalid. There are several options, add another constructor for my_class my_class(T value) : my_Value(value) {} template <typename U, std::enable_if_t<std::is_convertible<U, T>, int> = 0> my_class(U value) : my_Value(value) {} add over...
65,235,488
65,236,140
Is there any way to read a textfile with multiple integers on a line and save to Vector C++
I need to read values from an text file. There is multiple values on each line, and there is over a couple of thousand lines in the text file. I want to save each individual value to a vector, but i dont know how i should make the program to read every value on the same line. I tried to use getline, but it takes the wh...
You can read all numbers and store them all in one vector with int number; std::vector<int> vec; while (file >> number) vec.push_back(number); e.g.: #include <fstream> #include <iostream> #include <sstream> #include <vector> int main() { //std::ifstream file("file.txt"); std::stringstream file(R"(1 2 3 4...
65,235,641
65,235,932
Exception safety of new operator
This is implementation of new operator in libstdc++: _GLIBCXX_WEAK_DEFINITION void * operator new (std::size_t sz) _GLIBCXX_THROW (std::bad_alloc) { void *p; /* malloc (0) is unpredictable; avoid it. */ if (__builtin_expect (sz == 0, false)) sz = 1; while ((p = malloc (sz)) == 0) { new_handler ...
You are mixing in your question "new expression" and "operator new". New expression is like this: A* a = new A(); C++ language defines, that this expression is evaluated to something like this (over-simplified pseudo-code): void* __a = operator new(sizeof(A)); try { A::A(this = static_cast<A*>(__a)); } catch (...) {...
65,235,843
65,235,880
Why is the end() element in Associative container print the same value as the last element?
In the code below, the value that the iterator points to is the same for both the last and the second last element. #include <iostream> #include <set> using namespace std; int main() { set<int> s1 = {4,3,2,5,1}; set<int>::iterator i; i = s1.end(); cout << *i << endl; // 5 i--; cout ...
You invoked undefined behavior, std::set::end Returns an iterator to the element following the last element of the set. This element acts as a placeholder; attempting to access it results in undefined behavior. Undefined behavior renders the entire program meaningless.
65,235,891
65,236,035
Qt 5.15.2, C++ QString indexOf() function problem
I am using Qt Creator to develop a C++ application, I am trying to learn QString functions and i have problem with indexOf() function. I try to find "str" string in another string but this function always return the first index #include <QString> #include <QDebug> int main() { QString str = "Topic of today is QStri...
It always returns the first index because you use 1 as the second parameter of indexOf(). When you want the second match you need to use the previous index as the second parameter. The following code shows how to find and display the first 2 matches. #include <QString> #include <QDebug> int main() { QString str = "...
65,236,583
65,741,918
Why a std::array is not constant expression when it is the input of a templated function/generic lambda?
(Realted to this other question of mine; if you give a look at that too, I would really appreciate it.) If std::array<T,N>::size is constexpr, then why does the following code not even compile? #include <array> #include <iostream> constexpr auto print_size = [](auto const& array){ constexpr auto size = array.size(...
I was watching the 2014 Metaprogramming with Boost.Hana: Unifying Boost.Fusion and Boost.MPL presentation, where Louise Dionne touches this topic and explains what @super was telling me in the comments, but I was not understanding it. This is my rewording of that concept: there's no such a thing as a constexpr function...
65,236,703
65,237,157
How can I uniquely identify a lambda (may be capturing) contained within a std::function in C++
I planned to use a set-like container (for example QSet in qt or std::set) to hold std::function objects wrapping lambda (capturing or non-capturing) to avoid adding the same lambda multiple times. And these classess all require users providing comparing or hash calculation functions for key type. However as long as I ...
Every lambda has its own unique type, so you could use target_type for your purpose. Only non-capturing lambdas are convertible to function ptrs. Note that it is not trivial to compare whether two functions are equal, depending on what equal is in your context. If you have multiple parts in your code where you define t...
65,237,062
65,290,013
ofstream.open() set failbit in DLL called by UWP application
I've looked up on Internet to see if someone encountered that problem, but haven't found anything. So I'm trying to use a C++ DLL in a C# UWP application. This DLL has a log file which is opened at the beginning of the code with the following function: #include <string> #include <iostream> using namespace std; int Lo...
I figured out myself after some more active debugging. Somewhere before in the code this similar (indirect) call to ofstream::open didn't fail: ofstream out("out.txt", ios_base::trunc); And by putting breakpoints on the right place, I was able to determine that in that case, the value of the open mode (the ios_base::t...
65,237,634
65,238,927
What are the name resolution rules in C++ namespaces?
How do names get resolved in C++ namespace? I'm especially interested in cases where a name is provided in multiple different ways, for instance by a parent namespace and a using namespace. Take this piece of code: namespace ns1 { static auto str = "ns1::str"; } namespace ns2 { static auto str = "ns2::str"; ...
The rules to keep in mind for using-directives are the following [namespace.udir] 2 A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive. During unqualified name lookup ([basic.lookup.unqual]), the names appear as ...
65,237,774
65,237,820
What does std::vector::swap actually do?
What triggered this question is some code along the line of: std::vector<int> x(500); std::vector<int> y; std::swap(x,y); And I was wondering if swapping the two requires twice the amount of memory that x needs. On cppreference I found for std::vector::swap (which is the method that the last line effectively calls): ...
vector internally stores (at least) a pointer to the actual storage for the elements, a size and a capacity.† std::swap just swaps the pointers, size and capacity (and ancillary data if any) around; no doubling of memory or copies of the elements are made because the pointer in x becomes the pointer in y and vice-versa...
65,237,943
65,237,999
Loading value from C++ .DLL in C# always returns true
I'm trying to learn how to make C++ DLLs so I could easily have missed something super basic. I'm currently creating a DLL with C++ and then loading it into a testing environment written with C# The Testing environment is in C# because I find Windows Forms easiest for building prototype GUIs. I have a define in my DLL ...
.NET uses a 4 byte bool, but Visual C++ uses a 1 byte bool. So you'll need a marshaling directive to tell the marshaler that what's coming in is just a single byte. As it is, it's just marshaling 3 bytes of junk in addition to your bool. The junk is usually non-zero, which is why your function appears to return true...
65,238,116
65,238,725
How to convert a single object to a boost::any_range?
I'm trying to create and return a boost:any_range that contains only one object (I don't know if that's the core problem) but I get the following errors: error C2893: Failed to specialize function template 'range_iterator<C,void>::type boost::range_adl_barrier::begin(T &)' note: With the following template arguments: ...
Somehow this works, but that's not really clean That should not compile without diagnostics, as auto is deduced as std::initializer_list<Handle>. That approach invokes Undefined Behaviour because the initializer list doesn't exist after returning. Solutions The any_range should be able to return an iterator range. Po...
65,238,651
65,287,099
How can I implement the visitor patter with return type in C++
I want to implement the visitor pattern for one of my class without having to depend on the types that will implement the interface to visit them. My solution was this: class model::VisitableNode { public: template<class T> virtual T accept(NodeVisitor<T>); } But C++ says that it doesn't support template + virtu...
If a visitor needs to return a value, it is normal to store the returned value in the visitor itself. Thus: NodeVisitor<double> dv; node->accept(dv); double result = dv.result(); If you don't like the boilerplate, you can wrap it in a non-virtual member: class model::VisitableNode { public: template<class T> /* ...
65,238,947
65,239,053
Does c++ std::string are binary compatible between different compilers and std libraries?
I think it's impossible or very dangerous to send pointer / reference to dynamic loaded library from another compiler or ever another languages like C#. And I want to find proofs, but C++ standard documentation is pretty huge. I think null terminated string will work fine, but how about std::string, or maybe string_vie...
C++ does not standardize ABI. In practice, different std::string implementations may employ small string optimization differently tuned (with different buffer size), or no small string optimization. They may also have different order of fields. Additionally, std::allocator that allocates std:;string by default from dif...
65,239,211
65,240,599
Why isn't an expression a "core constant expression" if its evaluation requires the evaluation of a reference?
(This is a follow up to this question.) So I'd like to ask question specifically to understand the standardese quoted in that answer I received, and my exact question is in the title. Honestly, not even on cppreference I understand what the reason is why the standard says so. However, here's the minimal example: #inclu...
I believe it's because the constant-expression rules permit us to use the address-of operator, as hinted at in this answer. For example, this is legal: void f() { int i, j; constexpr bool b = &i == &j; // OK, b := false since i and j are distinct objects } It might seem harmless to permit the use of references...
65,239,250
65,240,061
Include declaration but not definition in main file C++
When using multiple files in C++, for example: main.cpp, definition.cpp, declaration.h // declaration.h int Myfunc(); //definition.cpp #include "declaration.h" int MyFunc() {return 5;}; // main.cpp #include <iostream> #include "declaration.h" int main() { std::cout << Myfunc() << std::endl; } Why do I not need...
Declaration is like a signature of the function and at compile time only the signature is required (What variable to pass and what the function will return so that you can write your other code around it). Actual call to function is resolved during the link time. If you will include the definition in the header file a...
65,239,295
65,239,488
Visual Studio Watch Window show WClass whenever I debug a simple windows application from its execuatble
Here's the code for just displaying a window using WinApi For ref this code is from here. #include <windows.h> const char g_szClassName[] = "myWindowClass"; // Step 4: the Window Procedure LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: ...
The watch window doesn't do anything on its own. The user has to enter a symbol or expression for it to become active. If your watch window shows an entry with name WClass, then that's an entry you entered. Given the code you provided, there is no symbol with that name, so the debugger cannot evaluate it. If this is fr...
65,239,845
65,240,748
How to enable -mno-outline-atomics AArch64 flag?
I've been trying to cross compile an open source library for AArch64. When I run an executable linking against this library on a Raspberry Pi 4 (running a 64-bit OS), I get an Illegal Instruction error. I created a github issue and the library developer suggested I enable the -mno-outline-atomics compiler flag (more de...
The outline-atomic feature was added with gcc 9.4. -- The C compiler identification is GNU 7.5.0 -- The CXX compiler identification is GNU 7.5.0 Clearly, your compiler is too old and does not support it.
65,239,921
65,240,044
Loop through first column of multidimensional array
I have a multidimensional array containing IP addresses and their corresponding Gateways. The structure of the array is shown below. I'd like to loop through the array and assign the first column of IP addresses to my network interface. I expect the interface to at some point to have several IP Addresses assigned to...
I was overcomplicating it. My sprintf line was wrong. Also, I needed to actually execute the command. I added system(cmdStr); after that line. Here's how the code looks now. char eth0IntName[256]; const char *arrayIPAddress[3][2]={ {"192.168.16.65", "192.168.16.66"}, {"192.168.17.65", "192.168.17.66"}, ...
65,240,293
65,240,969
How to print ALL BST nodes with values between min and max
I have the following BST for reference. BST Assume that min: 9 and max: 20 It satisfies all the criteria such that for each node (X), all the nodes in the left substree are smaller than, and all the nodes in the right substree are bigger than the value of X. I'm having trouble creating a function (member function so it...
First, there's a small problem with void printBetween(int min, int max);. int should be T. You should also consider taking min and max by const& in case your BST is used with types that are expensive to copy. How would I go about if both the left child and the right child could have a value between min and max? In th...
65,240,405
65,240,683
trouble understanding if statement with strings
i've started learning c++ today. Now i think that i've got the basics, i couldn't get with this program i'm trying to execute. Basically all program need to do is, output the user first name, and last name. Now i got it to work, but i want that if the user input a random number, the program won't execute, and output "O...
You will need to search the string for digits. Here is one method to find numeric digits in a string. There are many others. static const char digits[] = "0123456789". if (First.find_first_of(digits) != std::string::npos) { cout << "First name has at least one digit.\n"; } Edit 1: If that is not easily understood,...
65,240,940
65,240,985
How to use Structs in Templates as Parameters c++
I saw a video about templates in c++ the other day and it had the following code: template <typename T> void someFunction(T num) { Print(num); } The "Print()" just prints out the var "num" in console. I basically understood how to use templates as parameters. However, I don’t know how to use this with Structs, or i...
This is actually possible using a type trait and if constexpr: #include <iostream> #include <type_traits> struct vec2 { float x, y; }; struct vec3 { float x, y, z; }; template <typename T> void someFunction(T vec) { if constexpr (std::is_same_v<T, vec2>) { std::cout << vec.x << ' ' << vec.y << '\n'; ...
65,241,072
65,241,181
How do templates work when using them as array dimensions?
I tried to use tempaltes as array dimension value. I was puzzled when tried to specify wrong dimension as tempate argument. For example code: #include <iostream> using namespace std; template <int X, int Y> void f(int a[X][Y]) { for (int i = 0; i < X; ++i) { for (int j = 0; j < Y; ++j) { cout ...
You get this result because f(int a[X][Y]) is a lie. Arrays are not first-class citizens in C++. You cannot pass an array as a function parameter by value. So when you write such parameter, it is silently adjusted to a pointer (the first level only). Thus the type of a is really int (*)[Y]. Since there is no X in the t...
65,241,194
65,242,072
C++ Priority Queue - ordering intervals
Given initially a time interval. Every time, we pick the largest interval and split that into two halves. If there is a tie, then we pick the interval with the lowest starting point. for example - [0,9] first split - P1 [0,4] and P2 [4,9] For second split : dist(P1) = 3 => if pick P1, new intervals would be [0,2] and [...
We can plainly see that [1,2] is ordered before [4,6], by plugging it into your comparator: comp([1,2], [4,6]) if (abs(dist([1,2]) - dist([4,6])) <= 1) { // abs(0 - 1) <= 1 or 1 <= 1 return 1 > 4; // false } return dist([1,2]) < dist([4,6]); // not reached Only you can correct the comparator to ac...
65,241,411
65,241,563
MinGW Installation Manager - Missing devpropdef.h file
I downloaded the MinGW Installation Manager and installed most of the packages available there in trying to find the 'devpropdef.h' file. This file is needed by the openframeworks library and without it, I cannot compile the most basic project. This file was listed by one of the contributors in this thread, but I don't...
The http://winlibs.com/ build of GCC/MinGW-w64 has a very recent version of MinGW-w64 which contains devpropdef.h.
65,241,596
65,241,852
How do I show map in UML? C++
I have a "Database" class that has a template "myMap" that stores instances of the "Client" class. The "myMap" consists of nodes (instances of the "Node" class). How do I show this in UML? template<typename KEY, typename VALUE> class myMap; template <typename KEY, typename VALUE> class Node { private: friend class...
A map between type K and type V, noted in C++ with std::map<K,V> is typically modelled in UML using an association with a qualifier, the qualifier being of type :K and the other end of the association being of type V. The qualifier is used in conjunction with a source type T that is at the first end of the association...
65,241,899
65,242,429
Manipulating variables between functions
I've been teaching myself C++ for the past few hours (I have previous coding experience, but only very basic). I'm wondering, how would I allow the user to change the value of a variable between different functions? Edit: I do have an intermediate knowledge of Python from school, but it has completely left my mind. I'm...
WARNING: this most likely is above your level. Change and use code with caution. You could use a class for this. For example, class ShopInventory{ public: int items; int tools; ShopInventory(){ items=0; tools=0; } ~ShopInventory(){} }inventory; int shop(){ int selection; cout <<...
65,242,140
65,242,188
How does this work? Pointer to pointer assignment
#include <iostream> using namespace std; int main() { int *p1; p1 = new int; int *p2; p2 = new int; p2 = p1; // what happens here? *p1=5; cout << "pointer 2 is " << *p2 << endl << *p1 << endl; // both give out 5 delete p1; // what happens to p2 ? cout << "pointer 2 is " << *p2 <...
What is pointer p2 referencing now ? Nothing. It's dangling. It was pointing to the same thing p1 was pointing to, but you've deleted that. Consequently, your *p2 is broken, as is your delete p2; these both have undefined behaviour. You've also leaked the second new int, because p2 used to point to it but stopped doi...
65,242,518
65,244,132
Why is my Rcpp mean function slower than R?
I want to create a C++ function that raises each element in x to power and takes the mean. I've created three versions: power_mean_R: R solution -- mean(x^power) power_mean_C: C++ solution power_mean_C_2arg: C++ solution with extra power argument The extra power argument seems to drastically slow down the function to...
There are few things that handicap your C++ function with the examples you gave 1:100 is an ALTREP sequence, for which a highly optimized sum method exists which is much faster. In the below extreme examples, it's over 6 million times faster. Obviously the vector is not altrep all the way through, but it's a bad idea t...
65,242,593
65,243,295
C++ primer 5th ed. function template overloading
In the book C++ Primer, there is an example about function template overloading: // print any type we don't otherwise handle template <typename T> string debug_rep(const T &t) { cout << "debug_rep(T const&)\n"; ostringstream ret; // see § 8.3 (p. 321) ret << t; // uses T's output operator to print a repres...
The book is wrong. In the first example, the instantiation generated is not debug_rep(const string* &), it is debug_rep(string* const&). That is, const qualifies the pointer, not the thing pointed to. (This would be more obvious if the book used right const; that is, template <typename T> string debug_rep(T const& t) f...
65,242,766
65,242,875
Inserting into Map of String keys and Vector values
I'm a smidge rusty on using map and need a lil' help; I've declared the below. std::map<std::string, std::vector<double>> myMap; I'm periodically reading JSON data, where the ordering of data may sometimes change, or new data elements appear. Other parts of my code will loop through the JSON and extract two variables ...
If the string in jsonLabel already exists as a key in the map, then insert will not insert anything into the map. And the map insert function is to insert into the map itself. The pair should be a pair of the key and value types (where the value should be a vector of doubles). What you seem to want is simply myMap[json...
65,243,143
65,243,245
Issues freeing image data from stb_image in wrapper class
I am writing an Image class for a project using the raw data from stb_image. In the destructor for this class I am freeing the pointer to the image data to avoid memory leaks. However, when the destructor is called and the data is freed, I get an access violation. The header of image: class Image { unsigned char* p...
Default copy constructor would lead to double free. There are two ways to fix it - You can wrap the resource with unique_ptr having custom deleter and this would make the class move-only anyways. Or, make it non-copyable explicitly.
65,243,400
65,243,882
Why is ctor with default argument std::initializer_list unavailable (VS2019)?
I can't quite figure out why this code doesn't compile on Visual Studio 2019 (16.8.3): #include <initializer_list> struct Foo { Foo(std::initializer_list<int> = {}); }; int main() { Foo f; } Foo::Foo(std::initializer_list<int>) {} It gives me this error: C2512: "Foo": no appropriate default constructor ava...
There is a compiler bug here. It shouldn't be failing compilation just because the constructor's definition isn't available in the same translation unit (providing it in another one, or even providing it underneath main, doesn't permit the program to build). If you swap std::initializer_list for int it all works as exp...
65,243,589
65,243,821
How does operator++ overloading work to iterate over my LinkedList
This is my LinkedList namespace namespace LinkedList { template<class T> class Node{ public: Node(const T& data) :data_(data), next_(nullptr) {} T data_; Node<T> *next_; Node<T> *operator++(){ return next_; } }; template<c...
You've written a template<class T> Node<T>* Node<T>::operator++(); which would get invoked like Node<int> n; Node<int> *p = ++n; // calls the pre-increment operator Note this is quite different to the canonical form Node<T>& Node<T>::operator++(); which returns a reference to the incremented object that you can use ...
65,243,691
65,243,725
getting strange result in loops c++
I wrote a pretty simple code. And it works fine, but why I got A1A2A3 -1102135405. when the correct result is 3192831891 #include <iostream> #include <cmath> #include <fstream> using namespace std; int main() { for (int a = 41840; a <= 41849; ++a) { for (int b = 37960; b <= 37967; ++b) { f...
It looks like integer overflow. int is signed and 32 bits by default, which means the maximum positive number it can hold is 2^31 - 1, which is approximately 2 billion. Your number is larger than that. Larger values become negative in 2's complement, which is why you are seeing a negative number. https://en.wikipedia.o...
65,244,860
65,244,938
Why is my program reading an extra entry from a file in C++?
I have a file named 1.txt, it contains 3 lines, each line is stored in an object of class entry as follows: 1* 10/12/2020 5:30 a 11:15 p 0 0 0 0 ----- 2* 11/12/2020 3:45 a 5:46 a 0 0 0 0 ----- 3* 12/12/2020 5:46 a 4:56 p 34.6 0 0 0 blah and I'm reading from this file line by line into Entry e, and storing each entry i...
I think the problem here might root from the while statement - this will add an extra iteration from what you expect because this condition is only false after you've gone past the end of the file. while(file) { // ... } getline reads a whole line at a time, and since EOF is not a line you avoid the unwanted extra ite...
65,245,276
65,245,926
"error: no matching function for call to ..."
I am following the instruction of this repository with many given examples to build a POMDP model and use their solver for my problem. Here is my code: Belief* StarMazeProblem::Tau(const Belief* belief, ACT_TYPE action, OBS_TYPE obs) const { static vector<double> probs = vector<double>(NumStates()); ...
From the second note the compiler shows, you're trying to pass an int value (the state_id) to a parameter that wants a const despot::State &. Assuming that the state ID belongs to the state you want to pass, you already have it in next. Rather than passing next.state_id, just pass next: double p = state->weight * next....
65,245,568
65,245,731
How can I make diagonal shapes in C++?
I currently have some problem with looping. Please help me to make some program that run like this : But I have made some program that runs kind of like this : And this is my code for my program. Maybe you can correct the wrong syntax. #include <iostream> using namespace std; int main() { int input; char ab...
Here is your solution: // ... for (int i = 0; i < input; i++) { for (int j = 0; j < i; j++) { cout << abjad; abjad++; } cout << i + 2; // ... I have only changed the first for loop to start with 0 instead of 1 and as a compensation to this the condition changed to i < input instead of <=....
65,245,638
65,245,823
Identifier "hport" is undefined
I have been trying to learn how to read or write on a com port on my computer (specifically com11). I have a small understanding of c++, but I have only ever written code for Arduino, so what I was trying to do was new to me. I couldn't find any tutorials or explanations that made sense to me, but I found some code her...
HANDLE hport = CreateFile Here, you are defining hport, but you are using hPort. if (!GetCommState(hPort, &dcb))
65,245,658
65,253,590
Remove C++/clr dll from disk after FreeLibrary
I have very simple exe and dll just to test. Here is the code in exe process: auto lib = ::LoadLibrary("CppDll.dll"); auto bar = (Bar)::GetProcAddress(lib, "Bar"); bar(); while (::FreeLibrary(lib)); When after this I'm trying to delete the dll file I see the following: I also looked into Modules and I'm puzzled auto ...
This seems to be impossible. An app that hosts CLR uses CLRCreateInstance from which it can get ICLRMetaHost interface on which it can call GetRuntime in order to create CLR. But the interface doesn't have members to unload CLR. Its Stop method stops code execution in CLR but does not release, resources or unload appdo...
65,246,457
65,271,269
I2C Communication not working between 2 arduinos
I'm trying to have two Arduino's communicate with each other through I2C. I'm trying to send a string from the transmitter to the receiver, and have the receiver receive it and put it into a SD card. The if(Wire.available() > 0) doesn't execute either, and I'm not sure if it's a problem with the transmitter or receiver...
The issue was that incomingString = Wire.read(); should be in the receiveEvent(); function. You need one of those.And that is in the Wire.onReceive thing. Pretty much now my code is updated to - void receiveEvent(int bytes){ incomingString = Wire.read(); } void interruptServiceRoutine() { if (Wire.available() > 0) ...