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
73,430,966
73,432,583
How to conditionally enable console without opening separate console window
I'd like to create a windows application that, under normal conditions, does not have any connected terminal, but may have one in some conditions. I tried two different routes. Option A, creating a normal console application, and conditionally calling FreeConsole(): int main() { if (someCondition) { HANDLE stdOutHandle = GetStdHandle(STD_OUTPUT_HANDLE); WriteConsoleA(stdOutHandle, "hello world\n", 12, NULL, NULL); } else { FreeConsole(); // normal operation } return 0; } And option B, creating a WinMain based application, and conditionally calling AllocConsole(). int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nCmdShow) { if (someCondition) { AllocConsole(); HANDLE stdOutHandle = GetStdHandle(STD_OUTPUT_HANDLE); WriteConsoleA(stdOutHandle, "hello world\n", 12, NULL, NULL); } else { // normal operation } return 0; } The problem with option A, is that it doesn't act exactly like a windows application, in that you can very briefly see a console window open up before normal operation continues. This isn't a huge problem, but I'd prefer the program to act, as I said, exactly like a normal windows application. The problem with option B is that, if the program is invoked from an existing terminal, it opens up a separate terminal window and outputs to that, instead of outputting to the terminal from which it was invoked. This is a much bigger problem. What is the appropriate solution to conditionally behave as either a console program or a windows program, without either of the problems described above? Edit Based on a suggestion in the comments, I tried to use the AttachConsole function. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nCmdShow) { if (someCondition) { AttachConsole(ATTACH_PARENT_PROCESS); HANDLE stdOutHandle = GetStdHandle(STD_OUTPUT_HANDLE); Sleep(3000); WriteConsoleA(stdOutHandle, "hello world\n", 12, NULL, NULL); FreeConsole(); } else { // normal operation } return 0; } This seems to be on the right track, but there is still something missing, because my shell prompt is immediately printed out without waiting for the program to finish.
Impossible. AttachConsole does not work 100% because cmd.exe actually checks if the process it is about to start is a GUI app or not, and alters its behavior. The only way to make it work is to have two programs; myapp.com and myapp.exe. %PathExt% lists .com before .exe so you can make a console .exe and rename it .com at it will be executed if the user runs "myapp" (but will not work if the user types "myapp.exe"). If your program is not very big you can just ship two versions. If the program is large you can move most of the code to a .dll or make the .com a small helper that calls the .exe with a command line parameter and some pipes for stdin/stdout. Visual Studio does this (devenv.com).
73,431,360
73,431,411
How to dynamically reference to different non-copyable/non-moveable object without using raw pointer?
I am catching up c++17/20 recently. A while ago, I read a blog post from modrencpp: no new new. I found out that raw pointer is not recommanded and should be avoid in the future. edit: add explaination of what I try to accomplish. As an exercise, I start to modernize our project's code and replace raw pointer by using std::unique_ptr or reference. The process was pretty smooth. Most of the time I only need to replace * with a &. However, I encounter an issue where the code wants to do the following: bigObject is an object too big to copy or uncopyable. (bigObject contains mutex). Even though bigObject is an uncopayable object, I can use raw pointer reference to different objects and passing it around functions without triggering copy constructor. bigObject* pickEnv(bigObject* prod, bool use_test_env) { bigObject* result = null; if (use_test_env) { result = new bigObject("test"); result->init(); } else { result = production_env; } return result; } bigObject prod_env("production"); bigObject* selected_env = pickEnv(use_test, &prod_env); How can this be accomplished without using raw pointer? I tried a lot of different approaches. Most of the approaches trigger copy constructor. Here are two examples I have tried. bigObject make_test_env() { bigObject test_env("test"); test_env.init(); return test_env; // compile error: test_env is non-copyable } bigObject prod_env("production"); const auto& selected_env = use_test ? make_test_env() : prod_env; //compile error: prod_env in this line of code trigger copy constructor because of lvalue-to-rvalue conversion. // error: bigObject is non-copyable and non-moveable std::unique_ptr<bigObject> pickEnv(std::unique_ptr<bigObject> prod, bool use_test) { if (use_test) { return prod; } std::unique_ptr<bigObject> test_env = std::make_unique<bigObject>(bigObject("test")); return result; } Is it possilbe to dynamically pick different non-copyable object without using raw pointer? How to do it in a more modern way?
The recommended approach for how to solve this problem would be to use a smart pointer, like unique_ptr, to solve this problem. You can't return by-value, as you have found, and raw pointers don't convey proper ownership. The approach you attempted with unique_ptr is mostly correct in terms of what would be ideal -- only you have an issue with your make_unique call. When you write: ... test_env = std::make_unique(bigObject("test")) This is calling a copy constructor, which bigObject doesn't have. std::make_unique just forwards all arguments to the underlying type's constructor -- so by passing bigObject("test"), it's as though you are constructing bigObject(bigObject("test")). What you should be doing is calling make_unique<bigObject>("test") (passing the arguments directly to it): std::unique_ptr<bigObject> pickEnv(std::unique_ptr<bigObject> prod, bool use_test) { if (use_test) { return prod; } // This was changed; previously it was 'make_unique<bigObject>(bigObject("test"))` auto test_env = std::make_unique<bigObject>("test"); return test_env; } Live Example
73,431,435
73,433,728
How to convert nanoseconds to ptime in boost C++
Say I have a nanoseconds, 1614601874317571123. This represents the nanoseconds from epoch (1970-01-01). That is "2021-03-01T12:31:14.317571123" in ISO format I want to convert it to boost::posix_time::ptime. I know I could define a function like, #include <boost/date_time/posix_time/posix_time.hpp> #define BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG using namespace std; namespace pt = boost::posix_time; namespace gr = boost::gregorian; pt::ptime from_nanos(const long long &nanos) { return pt::ptime(gr::date(1970, 1, 1)) + pt::time_duration(0, 0, 0, nanos); } But this requires me to define a macro BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG that changes resolution from microseconds to nanoseconds. I want to avoid this. Are there any more robust solutions?
You already have the "correct" solution (although the code shown is incorrect, the define MUST precede any headers that may include Boost Datetime stuff). Also note that return pt::ptime(gr::date(1970, 1, 1)) + pt::time_duration(0, 0, 0, nanos); should probably just be return pt::ptime({1970, 1, 1}, pt::time_duration(0, 0, 0, nanos)); or indeed even return {{1970, 1, 1}, {0, 0, 0, nanos}}; If you cannot use the define, you can always do a twostep: add seconds, and add fractional seconds later. That way you don't run into overflow issues with the default representation types. Here's a tester: Live On Compiler Explorer #include <boost/date_time/posix_time/posix_time.hpp> using boost::posix_time::ptime; ptime from_nanos_std(intmax_t nanos) { return {{1970, 1, 1}, {0, 0, 0, nanos}}; } ptime from_nanos_man(intmax_t nanos) { constexpr auto NANO = 1'000'000'000; #ifdef BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG constexpr auto FRAC = 1; #else constexpr auto FRAC = 1'000; #endif return {{1970, 1, 1}, {0, 0, nanos / NANO, (nanos % NANO) / FRAC}}; } #include <iostream> int main() { std::cout << "Expected: 2021-Mar-01 12:31:14.317571123\n"; #ifdef BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG std::cout << "Standard: " << from_nanos_std(1614601874317571123) << "\n"; #endif std::cout << "Manual: " << from_nanos_man(1614601874317571123) << "\n"; } Output with -DBOOST_DATE_TIME_POSIX_TIME_STD_CONFIG: Expected: 2021-Mar-01 12:31:14.317571123 Standard: 2021-Mar-01 12:31:14.317571123 Manual: 2021-Mar-01 12:31:14.317571123 Output without: Expected: 2021-Mar-01 12:31:14.317571123 Manual: 2021-Mar-01 12:31:14.317571
73,431,467
73,436,618
Making a special constructor inaccessible to users but accessible to std::construct_at
My code needs a special constructor that std::construct_at can use. This works fine if it's public but then it can be accessed by users of the class. If it is private, std::construct_at fails. Here's the minimal code: #include <memory> #include <iostream> class Vec { public: int* const p{}; const int len{}; Vec(int len = 1) : len(len), p(new int[len]{}) {} // Raw ctor, for use only inside class using std::construct_at to overlay object // Doesn't work executed from std::construct_at if private Vec(int* p, int len) : p(p), len(len) {} Vec& operator=(Vec&& rhs) { delete[] p; std::construct_at(this, rhs.p, rhs.len); // dtor not needed for this class std::construct_at(&rhs, nullptr, 0); // steal rhs guts and make valid return *this; } // .... Other ctors ~Vec() {delete[] p;} }; int main() { int* pi{}; Vec x(pi, 0); // ctor accessable to users. Not good. Vec a, b(2); b.p[1] = 42; a = std::move(b); std::cout << "a.p[1] " << a.p[1] << " b.p (Null) " << b.p << "\n"; } So I tried creating an empty struct tag (INNER) defined in the private space, but used in the public ctor. This works: #include <memory> #include <iostream> class Vec { struct INNER {}; public: int* const p{}; const int len{}; Vec(int len = 1) : len(len), p(new int[len] {}) {} // Raw ctor, for use only inside class using std::construct_at to overlay object // Doesn't work executed from std::construct_at if private Vec(int* p, int len, struct INNER) : p(p), len(len) {} Vec& operator=(Vec&& rhs) { delete[] p; std::construct_at(this, rhs.p, rhs.len, INNER{}); // dtor not needed for this class std::construct_at(&rhs, nullptr, 0, INNER{}); // steal rhs guts and make valid return *this; } // .... Other ctors ~Vec() { delete[] p; } }; int main() { int* pi{}; //Vec x(pi, 0, Vec::INNER{}); // not compilable since INNER is private Vec a, b(2); b.p[1] = 42; a = std::move(b); std::cout << "a.p[1] " << a.p[1] << " b.p (Null) " << b.p << "\n"; } While this works in GCC, CLANG, and MSVC. But it seems odd that std::construct_at can use it since INNER is defined in the private segment. Is std::construct_ats use of INNER legit?
But it seems odd that std::construct_at can use it since INNER is defined in the private segment. Is std::construct_ats use of INNER legit? std::construct_at by itself only use public interface. it is legit. passkey idiom has some caveat though, and you are misusing it. private forbids to use the name explicitly, but you can use other form (as implicit contructor with {/*..*/} or decltype, ...) to actually use the thing which should be protected. You have to protect a little more: class Vec { class Key { friend Vec; // Who can have the key constexpr Key() {} // Not default to avoid non contrainted uniform initialization call (< C++20) constexpr Key(const Key&) = default; }; public: // ... // "private", except for those which have the key constexpr Vec(int* p, int len, const Key&) : p(p), len(len) {} Vec& operator=(Vec&& rhs) { std::destroy_at(this); std::construct_at(this, rhs.p, rhs.len, Key{}); std::construct_at(&rhs, nullptr, 0, Key{}); return *this; } // .... Other ctors ~Vec() { delete[] p; } }; Here, only Vec can create a Key, and it can pass it to any functions
73,432,708
73,438,317
How to make a widget blink in Qt with a delay of one second?
I want to show and hide a widget with an interval of one second. My code is like: if(ui->widget->isVisible()) ui->widget->hide(); else ui->widget->show(); I need a one-second gap between showing and hiding my widget. I also want this to be repeated so that the widget starts blinking.
With QTimer it should be posible: QTimer *timer = new QTimer(this); constexpr int i = 1000; // 1s timer->setInterval(i); connect(timer, &QTimer::timeout, this, [this]{ if (isVisible()) hide(); else show(); }); timer->start();
73,432,751
73,432,993
wrong output in vscode and codeblocks
This code snippet is supposed to return the reverse of the given integer and in the Sololearn compiler it works but in VSCode and Code::Blocks the output is different. For 543 it returns -93835951 in VSCode and 694653940 in Code::Blocks. Does anybody know why? #include <iostream> using namespace std; int main() { int n, sum, a; a = 0; sum = 0; cin >> n; while (n>0) { a = n % 10; sum = sum * 10 + a; n = n / 10; } cout << sum; return 0; }
Here is the working version with a bit of refactoring but still keeping it very similar to your snippet: #include <iostream> int main( ) { std::cout << "Enter a number: "; int num { }; std::cin >> num; int sum { }; while ( num > 0 ) { const int remainder { num % 10 }; sum = sum * 10 + remainder; num = num / 10; } std::cout << "The reversed number: " << sum << '\n'; } A few general things to keep in mind: Do not use using namespace std;. That's a bad practice. See Why is "using namespace std;" considered bad practice?. Do not declare multiple variables in a single statement. That can lead to various issues. Make sure to initialize your variables before using them if their initial values will be read and used in some operation. If the initial value is not used by anyone, then do not initialize the variable since it would be a waste of computing power. Try to shrink the scope of variables as much as appropriate to reduce the risk of them being used accidentally by another statement that is not supposed to access those variables. In the above example, I declared remainder inside the scope of the while loop because it was not being used outside the loop. And last but not least, avoid ambiguous identifiers like int a, int n, etc. These are not meaningful and purposeful names in this context. Use names that MAKE sense.
73,432,871
73,746,303
Not declared in the scope error, C++ sfml
The compiler error says that "mango" was not declared in the scope. I don't understand why. Mango is a sprite defined in another function in another cpp file. all im trying to do is load a sprite on the screen. I'm sure it's a silly error, I apologize in advance. I'm new to C++. main.cpp: #include "test.h" #include <SFML/Graphics.hpp> #include <iostream> ///////////////////////// constexpr int32_t winWidth = 1080; constexpr int32_t winHeight = 600; int main() { // Rendering SFML window sf::RenderWindow window(sf::VideoMode({winWidth, winHeight}), "CLICKER GAME"); // Game Loop, Call all functions in here while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } window.clear(sf::Color(255, 84, 167)); // Magenta window.draw(mango); window.display(); } return 0; } test.h: #pragma once #include <iostream> #include <string> class Game { public: void test(); }; test.cpp: #include "test.h" #include <SFML/Graphics.hpp> #include <iostream> #include <string> // Function Defs void Game::test() { sf::Texture mangoTexture; if (!mangoTexture.loadFromFile("Data/mango.png")) { std::cout << "Load Error"; } sf::Sprite mango; mango.setTexture(mangoTexture); }
Just a quick introduction to scopes in c++. There are a few different ways scoping can work, depending on the type of variable you're using but in general most variables have an automatic scope which means they are created and destroyed automatically. The rules of thumb are: Any two functions are not correlated with each other in any way. Neither can see what's inside the other. Any variable with an automatic scope is created where you created, and is deleted at the end of the body you created it in. examples: void someFunc() {//body start of someFunc if () { //body start of if while() { //body of while } } //body end of if }// body end of someFunc int main() //head of main. main cant see inside body of someFunc. vice versa { //body start of function main } // body end of function main int main() { int abc = 4; //abc was created in main body thus exists until main body's end if () { float bcd; //bcd was created in if body thus... }//float exists until this point etc. }//abc exists until this point //Pretty much the only exception are dynamic variables in basic C++: int main() { int *dyn = new int; //important!! the dynamic part here is the 'new int' thats the non-automatic scoped variable. //The int *dyn is an automatic pointer to that scope. after main function ends the pointer is //automatically deleted yet the value of the variable still exists in that place in //memory until you delete it manually or the program ends completely. not deleting a non-automatic //scoped variable ends in memory leaks which lead to unnecessary higher resource usage and //slowness of the systme running the program. } //So finally lets say you create a class with some values or something. Lets say they're all automatically scoped. 1. you can access variables in the class itself. 2. you can't access variables inside functions. //Lets use your example: //to make it easier to understand lets just make it a simple function instead of a class method(same thing but still) void test() { sf::Texture mangoTexture; if (!mangoTexture.loadFromFile("Data/mango.png")) { std::cout << "Load Error"; } sf::Sprite mango; mango.setTexture(mangoTexture); } int main() { //lets say you want to use mango in main. This breaks rule 1 of the aformenthioned 2 rules i wrote at the start: main function cannot see whats inside test function. And even if it somehow could, it couldnt use that variable mango because it was destroyed at the end of the function: //mango doesnt exist hasnt been made yet test(); //mango doesnt exist. has been made and deleted in prev line. //In the end functions are just packed up code in neat blocks you can recycle and use many times return 0; } //If you want to actually use mango in eg main, youd have to either have it as a class variable or have the function return mango //OPTION 1 class Game { public: sf::Sprite mango; void test() { sf::Texture mangoTexture; if (!mangoTexture.loadFromFile("Data/mango.png")) { std::cout << "Load Error"; } mango.setTexture(mangoTexture); } }; //OPTION 2 class Game { public: sf::Sprite test() { sf::Texture mangoTexture; if (!mangoTexture.loadFromFile("Data/mango.png")) { std::cout << "Load Error"; } sf::Sprite mango; mango.setTexture(mangoTexture); return mango; } }; //For your case i highly recommend option 1. I wrote both options just as an example as there can be many difficult situations in which you might be forced to only use one or the other.
73,433,132
73,433,364
using Membrane keypad to answer math prob. Arduino
I am trying my first project in Arduino. I am trying to use my Membrane Switch Module to answer simple math prob. like 1+1. in general, I am trying to make my Arduino do the following: ask for an answer to 1+1 if the answer is correct turn the light on for 30 sec else blink 3 times and ask again... the result for my code is that it is running endlessly without getting the input of the keypad. thank you for the help. I am new to Arduino and for c++ coding :) #include <Keypad.h> char pad[4][4]={ {1,2,3,'A'}, {4,5,6,'B'}, {7,8,9,'C'}, {'*',0,'#','D'} }; byte rowPins[4]={9,8,7,6}; byte colPins[4]={5,4,3,2}; Keypad customKeypad=Keypad (makeKeymap(pad),rowPins,colPins,4,4); void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(10,OUTPUT); digitalWrite(10,LOW); } void loop() { // put your main code here, to run repeatedly: Serial.println("how much is 1+1?"); char answer=customKeypad.getKey(); Serial.println(answer); delay(10000); if (answer==2){ digitalWrite(10,HIGH); delay(30000); digitalWrite(10,LOW); delay(1000);} else { digitalWrite(10,HIGH); delay(1000); digitalWrite(10,LOW); delay(1000); digitalWrite(10,HIGH); delay(1000); digitalWrite(10,LOW); delay(1000); digitalWrite(10,HIGH); delay(1000); digitalWrite(10,LOW); delay(1000); } }
See the documentation: https://playground.arduino.cc/Code/Keypad/ getKey returns the currently pressed key, as you wait 10 seconds between calls to getKey it's likely that you'll miss your key presses unless you hold the key down. You should use waitForKey instead.
73,433,381
73,436,511
Is it valid to use void* rather than any pointer type if we always static_cast<> it?
Lets assume that we have following code: struct VeryComplexStruct { // a very complex struct void test() {} }; void foo(VeryComplexStruct **ptr) { // do something } int main() { VeryComplexStruct *p = nullptr; foo(&p); p->test(); } I wonder if the code is still valid by C++ standard if we just use void* and cast it like this: struct VeryComplexStruct { // a very complex struct void test() {} }; void foo(VeryComplexStruct **ptr) { // do something } int main() { void *p = nullptr; foo(reinterpret_cast<VeryComplexStruct **>(&p)); (static_cast<VeryComplexStruct *>(p))->test(); } This may happen if we use C libraries in C++. Any idea?
reinterpret_cast<VeryComplexStruct **>(&p) There is no guarantee that the alignment requirements of void* and VeryComplexStruct* are compatible. If they are not and &p is not suitably aligned for a VeryComplexStruct*, then the value resulting from this cast will be unspecified and using it in basically any way will cause undefined behavior. Even if the alignment requirement is satisfied, the resulting pointer may not be used to access the object it points to. There is no VeryComplexStruct* object which is pointer-interconvertible with the void* object at the address &p. Therefore the result of the cast will still point to the void* object, not a VeryComplexStruct* object. Generally it is an aliasing violation, causing undefined behavior, to access an object of one type through an lvalue (e.g. a derereferenced pointer) of another type with a few specific exceptions, none of which apply here. (There isn't even any guarantee that void* and VeryComplexStruct* have the same size and representation, although that is practically generally the case.) (static_cast<VeryComplexStruct *>(p))->test(); Assuming the function has not modified p, this is trying to call a non-static member function on a null pointer, causing undefined behavior. If the function did modify p in some way, which is legal basically only by first casting the argument back to void**, then it depends on what the function did do with p. The line is valid if p was assigned a pointer to a VeryComplexStruct* object or some object which is pointer-interconvertible with such. Otherwise the member function call is again going to have undefined behavior. This may happen if we use C libraries in C++. Any idea? It causes undefined behavior in the same way in C, although the object model and terminology used there is different. In that case the problem would be that void* and VeryComplexStruct* are not compatible types, so accessing the void* object through a pointer to VeryComplexStruct* would again be an aliasing violation. So if something like this is used in a C library, it already relies on undefined behavior.
73,433,646
73,434,010
std:bitset c++ external initialization
I want to wrap or cast a std:bitset over a given constant data arrary or to formulate it differently, initialize a bitset with foreign data. The user knows the index of the bit which he can check then via bitset.test(i). Data is big, so it must be efficient. (Machine bitorder does not matter, we can store it in the right way). Thats what I tried: constexpr uint32_t data[32] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32}; constexpr std::bitset<1000> bset(1); //bit bitset initialized with a value here constexpr std::bitset<1000> bset2(data); //init it with our data, this is not working The number of bits is 32*32=1024 that is held by data. With my bitset i can address the almost full range. User does not need more than 1000. Can someone please explain to me how this is done in cpp in my example above with bset2?
Unfortunately std::bitset does not have suitable design for what you want. It is not designed an aggregate (like std::array is) so aggregate initialiation is impossible (and also copying bits into it with std::memcpy is undefined behavior). It can take only one unsigned long long in constexpr constructor. The operator [] and set method will become constexpr in C++23 so there will be a way after that. Just use constexpr raw array or std::array and add bit accessing methods until then.
73,433,917
73,433,935
glGetUniformLocation returning -1 on OpenGL 4.6
I'm writing a small "engine", and the time has finally come to implement transformations. However, when I try to glGetUniformLocation, it return -1. Here is my rendering method: void GFXRenderer::submit(EntityBase* _entity, GPUProgram _program) { if(_entity->mesh.has_value()) { mat4 mod_mat(1.0); //mod_mat = translate(mod_mat, _entity->transform.position); /* mod_mat = scale(mod_mat, _entity->transform.scale); mod_mat = rotate(mod_mat, radians(_entity->transform.rotation.x), vec3(1.0, 0.0, 0.0)); mod_mat = rotate(mod_mat, radians(_entity->transform.rotation.y), vec3(0.0, 1.0, 0.0)); mod_mat = rotate(mod_mat, radians(_entity->transform.rotation.z), vec3(0.0, 0.0, 1.0)); */ mod_mat = translate(mod_mat, vec3(0.5f, -0.5f, 0.0f)); //mod_mat = glm::rotate(mod_mat, (float)glfwGetTime(), glm::vec3(0.0f, 0.0f, 1.0f)); glUseProgram(_program.id); int transform = glGetUniformLocation(_program.vsh.id, "transform"); std::cout << transform << std::endl; glUniformMatrix4fv(transform, 1, GL_FALSE, value_ptr(mod_mat)); glUseProgram(_program.id); glBindTexture(GL_TEXTURE_2D, _entity->mesh->tex_id); glBindVertexArray(_entity->mesh->vao); glDrawElements(GL_TRIANGLES, _entity->mesh->indices.size(), GL_UNSIGNED_INT, 0); glUseProgram(0); glBindVertexArray(0); } } Here EntityBase is an object class. It contains a transform class, as follows: class Transform { public: vec3 position; vec3 rotation; vec3 scale; quat q_rot; mat4x4 matrix; }; Ignore the quaternion and matrix. ALso, I must mention that without doing transformation - it renders flawlessly. (SIKE) Here is my vsh : #version 460 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTex; out vec2 tex_coord; out mat4 f_tr_opt; // for stopping optimization uniform mat4 transform; void main() { tex_coord = aTex; f_tr_opt = transform; gl_Position = transform * vec4(aPos, 1.0); } Here is my fsh: #version 460 core in vec2 tex_coord; in mat4 f_tr_opt; // again, same thing out vec4 FragColor; uniform sampler2D texture0; void main() { mat4 garbage = f_tr_opt * f_tr_opt; // named garbage for easier recognition FragColor = texture(texture0, tex_coord); } I check for compile and linking errors, all is fine. Please correct me as to what I am doing wrong here.
See glGetUniformLocation. The uniform location must be requested from the linked program object, not from the (vertex) shader object: int transform = glGetUniformLocation(_program.vsh.id, "transform"); int transform = glGetUniformLocation(_program.id, "transform");
73,434,121
73,916,018
Why default operator delete[] can't deallocate the memory allocated by default operator new?
Due to unspecified overhead, it is illegal to deallocate with delete-expression that does not match the form of the new-expression. However, default operator new and operator delete isn't the same. operator new[]: [new.delete#array-4] Default behavior: Returns operator new(size), or operator new(size, alignment), respectively. operator delete[]: [new.delete#array-14]: Default behavior: The functions that have a size parameter forward their other parameters to the corresponding function without a size parameter. The functions that do not have a size parameter forward their parameters to the corresponding operator delete (single-object) function. It can be seen that default operator new[] and operator delete[] simply call operator new and operator delete. However, operator delete[] can only deallocate the memory allocated by operator new[], according to [new.delete#array-9]: Preconditions: ptr is a null pointer or its value represents the address of a block of memory allocated by an earlier call to a (possibly replaced) operator new or operator new[](std​::​size_­t, std​::​align_­val_­t) which has not been invalidated by an intervening call to operator delete[]. Therefore, the following code is illegal: operator delete[](operator new(1)); Because void* operator new(std::size_t size) does not return void* operator new[](std::size_t size). However, the following code is legal: operator delete(operator new[](1)); According to [new.delete#single-10]: Preconditions: ptr is a null pointer or its value represents the address of a block of memory allocated by an earlier call to a (possibly replaced) operator new(std​::​size_­t) or operator new(std​::​size_­t, std​::​align_­val_­t) which has not been invalidated by an intervening call to operator delete. void* operator new[](std::size_t size) does return operator new(size), so no problem at all. Is this asymmetric behavior an issue?
This inconsistent behavior is an issue, see LWG3789. EDIT: However, the status of the issue has been set to Tentatively NAD: "No reason to carve out an exception covering a case on something which can’t be observed by the program (whether the allocation operators are replaced). This just makes things more complicated for no good reason." "This would require changes to sanitizers and other dynamic analyzers, for zero practical benefit (except allowing bad code to go un-diagnosed)."
73,434,558
73,438,801
Legality of using delete-expression on a pointer to an object of class type with a trivial destructor/scalar type whose lifetime has ended
Is the following code legal? struct S {}; int main() { S* p = new S; p->~S(); delete p; } The standard rules at [basic.life#6]: Before the lifetime of an object has started but after the storage which the object will occupy has been allocated24 or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that represents the address of the storage location where the object will be or was located may be used but only in limited ways. For an object under construction or destruction, see [class.cdtor]. Otherwise, such a pointer refers to allocated storage ([basic.stc.dynamic.allocation]), and using the pointer as if the pointer were of type void* is well-defined. Indirection through such a pointer is permitted but the resulting lvalue may only be used in limited ways, as described below. The program has undefined behavior if: (6.1) — the object will be or was of a class type with a non-trivial destructor and the pointer is used as the operand of a delete-expression, (6.2) — the pointer is used to access a non-static data member or call a non-static member function of the object [basic.life#6.1] doesn't apply, so this code seems to be legal because S has a trivial destructor. However, according to [basic.life#6.2], this code is illegal because the delete-expression calls the destructor of the S object, which is a non-static member function of it. EDIT: According to [class.dtor#19], it's also illegal. Which should I listen to? Maybe [basic.life#6.2], because [basic.life#6.1] doesn't stipulate that it must be legal to do so for classes with trivial destructor. The conclusion is that it's illegal. However, after replacing S with a scalar type, things seem to be different: #include <memory> int main() { char* p = new char; std::destroy_at(p); delete p; } This will make a pseudo-destructor call to the char object pointed to by p, which will end its lifetime, according to [expr.call#5]: If the postfix-expression names a pseudo-destructor (in which case the postfix-expression is a possibly-parenthesized class member access), the function call destroys the object of scalar type denoted by the object expression of the class member access ([expr.ref], [basic.life]). [basic.life#6.1] still doesn't apply. But the difference is that [basic.life#6.2] doesn't apply either, because there is no non-static member function called for the char object (char isn't a class after all). The conclusion is that it's legal. Why?
It seems that there is a wording defect. Either your code is intended to be legal, or it's not. If it is intended to be legal, then [basic.life]/6.2 should have an exception for a trivial destructor. If it's not intended to be legal, then the words "with a non-trivial destructor" should be struck from [basic.life]/6.1 because even if the destructor is trivial, the inevitable destructor call will violate p6.2. I suspect that it was intended to be legal, because there's no point in preserving the explicit exception in the case of delete if not to prevent breaking code that was, in fact, calling delete on objects with trivial destructors that are outside their lifetimes. N2762 removed the trivial destructor exception for all the other UB-causing operations on pointers to objects outside their lifetimes, but conspicuously kept it for delete-expressions. This suggests that there was a need to keep this exception in the language in order to avoid breaking code. Most likely the reason why the second bullet was not also changed to make an exception for a trivial destructor call is that the authors forgot that a delete-expression does call the destructor even if it's trivial. They might have assumed that delete was specified to skip the destructor call if it would be trivial. (Note also that in C++98 through C++17, your S object's lifetime is not ended by the destructor call anyway because [basic.life]/1 specified that a destructor call ends the lifetime of the object only if it is non-trivial; this was changed in C++20 by CWG2256. However, due to N2762, in C++11 and later, if an object's lifetime has not yet started because it has nontrivial initialization, we can run into an issue that is similar to the one described by the OP.) I think it's worth filing a defect report about this, though I'm not sure what the outcome will be. So much time has elapsed since N2762 that I would imagine the committee would actually want to consider whether the exception for trivial destructors ought to be eliminated at this point (i.e., fixing p6.1 instead of p6.2); after all, the resolution of CWG2256 may also have broken some code, but it was probably code of the sort that has become increasingly rare over the years since C++ diverged from C.
73,434,740
73,435,408
Create std::variant from another with a sub set of the types
Seen some other questions about this but they so not seem to be answered correctly or there is no answer at all. I have a instance of a std::variant and I want to create another instance with a sub set of the types in the first one as I know the original is not that type. For exmaple... std::varaint<int, const char*, bool> v1 = false; std::varaint<int, bool> v2 = cast_variant<int, bool>(v1); As you can see I can guarantee v1 does have a value that is in the list of types for v2. Just wondering how you would implement this or can you?
@appleapple already provided an answer. However, if constexpr(requires {std::variant<Ts...>{v};}) This can easily triggers implicit conversion, so the below code will work without throwing any exceptions: std::varaint<int, const char*, bool> var1 = false; auto var2 = cast_variant<int>(var1); // convert `false` to int Instead, consider explicitly checking if current type is included in new types: template<typename ... newTypes, typename ... oldTypes> auto cast_variant(const std::variant<oldTypes...>& var) { return std::visit([]<typename T>(T && arg) -> std::variant<newTypes...> { if constexpr (std::disjunction_v<std::is_same<std::decay_t<T>, newTypes>...>) { return arg; } else { throw std::bad_variant_access(); } }, var); }
73,435,368
73,443,097
C++ syntactic sugar for two phase look-up
I am trying to provide an API where an user can statically inherit from a base class and use its methods. The issue is that the class is templated with typename T and the methods are templated with typename U, such that the use of the methods is really cumbersome (I think, for an API). As far as I understood this is intended since the compiler cannot resolve (the dependent?) methods. template<typename T> struct base { template<typename U> void foo(){} }; template<typename B> struct child : B { void barr(){ B::template foo<float>(); this->template foo<float>(); /* B::foo<float>(); - ERROR: expected primary-expression before ‘float’ this->foo<float>(); - ERROR: expected primary-expression before ‘float’ foo<float>(); - ERROR: error: ‘foo’ was not declared in this scope */ } }; int main(){ child<base<bool>> c; c.barr(); return 0; } Is there any way that I could get rid of template keyword in the call to foo? Maybe some syntactic sugar I don't know of?
The problem is indeed caused by the compiler's need to resolve foo before deciding that foo< isn't calling operator< on the expression foo. Adding template means that the compiler knows foo< is the start of a template argument list. As the author of base, there's nothing you can do about that. That's the whole point of the two-phase compilation. The compiler trips over the foo< in the first pass, where all it knows is that child<B> inherits from some unknown B.
73,435,592
73,435,842
Finding all Strings in an array
I tried solving this all day but I cannot find an adequate solution. I want to print all words of an input char array, but if I type in an empty space at the start or at the end of the array my result is wrong. Does somebody know how to fix this or does somebody have an understandable solution for me? Thank you! Using a library would be okay to if it is understandable :) #include <iostream> #include <ctype.h> #include <stdio.h> #include <cmath> #include <string> #include <stdlib.h> #include <sstream> using namespace std; const int len = 1000; char inputnames[len]; int main() { int counter = 0, z = 0; cout << "Type in the Candidates names and press enter please: "; cin.getline(inputnames, len); string stringstream(inputnames); string token; char LastCharacter = stringstream.back(); if (LastCharacter == ' ') { counter = 0; for (int z = 0; z < len; z++) { if (inputnames[z] >= 'a' && inputnames[z] <= 'z' && inputnames[z + 1] == ' ' || inputnames[z] >= 'A' && inputnames[z] <= 'Z' && inputnames[z] == ' ') { counter++; } cout << inputnames[z]; } } else if (LastCharacter != ' ') { counter = 1; for (int z = 0; z < len; z++) { if (inputnames[z] >= 'a' && inputnames[z] <= 'z' && inputnames[z + 1] == ' ' || inputnames[z] >= 'A' && inputnames[z] <= 'Z' && inputnames[z] == ' ') { counter++; } cout << inputnames[z]; } } [EDIT] Hello guys, I solved the last bug now, which involved +1 count if user typed in a space bar at the end of the input message. Please let me know if you have further tips/help/critic. Thank you all!
You're looking for word by checking if there's space followed by any other character. Try checking for letters if(inputnames[z] >= 'a' && inputnames[z] <= 'z') || (inputnames[z] >= 'A' && inputnames[z] <= 'Z') and if the following character is not a letter.
73,436,481
73,436,578
Troubles with std::set.insert c++
I have a set of a custom class and when I'm trying to insert an object of that class, the terminal gives me an error: #ifndef EMPLOYEE_HH #define EMPLOYEE_HH #include <string> #include <iostream> #include <set> #include <iterator> using namespace std ; class Employee { public: // Constructor Employee(const char* name, double salary) : _name(name), _salary(salary) {} // Accessors const char* name() const { return _name.c_str() ; } double salary() const { return _salary ; } // Print functions void businessCard(ostream& os = cout) const { os << " +------------------+ " << endl << " | ACME Corporation | " << endl << " +------------------+ " << endl << " " << name() << endl ; } private: string _name ; double _salary ; } ; class Manager : public Employee{ public: Manager(const char* name, double salary) : Employee(name, salary) {}; void addSubordinate(Employee& empl){ _subs.insert(empl); } const set<Employee*>& listOfSubordinates() const{ return _subs; } void businessCard() const{ Employee::businessCard(); set <Employee*>::iterator it=_subs.begin(); cout <<"Managed employees: " <<endl; while(it!=_subs.end()){ cout <<*it++ <<endl; } } private: set <Employee*> _subs; }; #endif The addSubordinate() routine: void addSubordinate(Employee& empl){ _subs.insert(empl); } returns this error: no instance of overloaded function "std::set<_Key, _Compare, _Alloc>::insert [with _Key=Employee *, _Compare=std::less<Employee *>, _Alloc=std::allocator<Employee *>]" matches the argument list I have tried to overload the operator < as other people suggested in response to similar questions, but that doesn't seem to solve the issue.
Your set accepts a pointer to an Employee, but you are trying to insert the object itself. What you can do is void addSubordinate(Employee& empl){ _subs.insert(&empl); // This will store the address to the object } or accept a pointer itself void addSubordinate(Employee* empl){ _subs.insert(empl); }
73,436,932
73,438,827
Does IFNDR take precedence over diagnosable rule violations?
[intro.compliance.general]/2 specifies how a compiler should handle a program given to it. In particular it has two points dealing with ill-formed programs. (2.2) requires the compiler to issue at least one diagnostic for a violation of a diagnosable rule. (2.3) states that there are no requirements imposed on the compiler for a program which violates a rule for which no diagnostic is required. Unfortunately I don't think the paragraph makes a precedence between the two requirements clear. If a program contains a violation of a diagnosable rule for which a diagnostic is required and a violation of a rule for which no diagnostic is required, is the compiler required to issue a diagnostic? As an example (considered as a whole one-translation-unit program): // ill-formed, diagnostic required int main() { using T = void&; } // IFNDR according to [temp.res.general]/8.1 and [temp.res.general]/8.4 void f(auto) { using T = void&; } Moreover, if IFNDR takes precedence, the same presumably applies to undefined behavior that is typically considered runtime UB, e.g. does // always runtime undefined behavior int main() { return *(int*)0; } // ill-formed, diagnostic required using T = void&; then technically also not require a diagnostic (considered as a whole one-translation-unit program)? From a quality-of-implementation standpoint it seems clear to me that the compiler should issue a diagnostic whenever possible in such a situation. But my impression is that the standard does not actually require one and this is also what I have read/heard before. For example the qualification of "and the template is not instantiated" in [temp.res.general]/8.1 would not make much sense otherwise. However at other times the standard doesn't use such inverting qualifications where it seems that they should be required, e.g. [dcl.constexpr]/6.
Section 2.3 is clear – "this document places no requirement on implementations". Not "this document except for 2.2", but "this document". If an IFNDR situation exists, then the implementation is free to do anything. Necessary Overriding 2.2 is necessary. Hypothetically, an IFNDR situation could throw compilation off-track, resulting in it missing an ill-formed situation that does require a diagnostic. (Bugs hidden by other bugs is not a novel concept.) This does not make the implementation non-conforming. The existence of the IFNDR situation gives implementations the leeway they need to potentially miss a diagnostic in related code despite good-faith processing. This does mean that implementations also have leeway to miss a diagnostic in unrelated code. Oh well. The standard could try to distinguish between "related code" and "unrelated code", but it would be wasted effort. At some point, it is better to trust that implementations work in good faith, rather than excessively regulate. A "diagnostic not required" scenario is a valid reason for missing a diagnostic. If an implementation uses it as an excuse to actively omit a diagnostic, then it is compliant, but you should stay away. Just like you should stay far away from a compliant implementation that detects undefined behavior and uses that as an excuse to format your hard drive. Practical From a practical perspective, though, 2.3 does not override 2.2. While the official terminology is "no diagnostic required", a more practical view is "the situation does not need to be detected". Situations that require a diagnostic must be detected so that the diagnostic can be produced. Situations that do not require any particular action by the implementation do not need to be detected. If an implementation does not try to detect an IFNDR situation, then it cannot make decisions based upon the IFNDR existing. That is, it must provide diagnostics for the ill-formedness that it does detect. This is not just "quality-of-implementation", nor is it just "good faith", but rather it is necessary to ensure compliance in the face of an unknown. If an implementation does detect an IFNDR situation, then we fall back on good faith.
73,437,029
73,437,125
How to get first element of typelist in C++-11
I am following C++ templates the complete guide and trying to get the first element from a typelist. The following compiles: #include <bits/stdc++.h> using namespace std; template <typename... Elements> class Typelist; using SignedIntegralTypes = Typelist<signed char, short, int, long, long long>; template <typename List> class HeadT; template <typename Head, typename... Tail> class HeadT<Typelist<Head, Tail...>> { public: using Type = Head; }; template <typename List> using Head = typename HeadT<Typelist<List>>::Type; int main() { static_assert(is_same<Head<SignedIntegralTypes>, SignedIntegralTypes>::value, ""); } Head<SignedIntegralTypes> produces SignedIntegralTypes. I would expect it to produce signed char. Why is this happening? How do I fix it?
Let's deconstruct all the templates, one step at a time. Head<SignedIntegralTypes> Ok, now let's take the definition of what Head is: template <typename List> using Head = typename HeadT<Typelist<List>>::Type; Since SignedIntegralTypes is the template parameter, that's what List becomes here. So this becomes: typename HeadT<Typelist<SignedIntegralTypes>>::Type And since SignedIntegralTypes is, itself a: using SignedIntegralTypes = Typelist<signed char, short, int, long, long long>; The full class becomes: typename HeadT<Typelist<Typelist<signed char, short, int, long, long long>>>::Type And if you work out the result of the specialization, the first type in the Typelist is Typelist<signed char, short, int, long, long long> And that's what Type gets aliased to. A.k.a. a SignedIntegralTypes. And you fix this, to get the intended result, simply by fixing the Head alias: template <typename List> using Head = typename HeadT<List>::Type;
73,437,193
73,441,479
How to fix memcpy.asm error when assigning a value to an std::string through a pointer?
I made this code for a Stack struct: #include<iostream> #include<Windows.h> template<uint32_t S> struct Stack { size_t size; byte base[S]; byte* top; // Stack() { top = (byte*)base; size = 0; } ~Stack(){} // template<class T> void alloc(T*& rt) { if (sizeof(T) > MAXBYTE) return; rt = (T*)top; top += sizeof(T); size += sizeof(T) + 1; *top = sizeof(T); top++; } void alloc(void*& rt, size_t arg) { if (arg > MAXBYTE) return; rt = top; top += arg; size += arg + 1; *top = arg; top++; } template<class T> void* push(T arg) { if (arg > MAXBYTE) return 0; T* rt; alloc<T>(rt); *rt = arg; return rt; } template<class T> T&& pop() { if (top == base) return 0; top--; size -= *top; top -= *top; return (T&&)*(T*)top; } void pop() { if (top == base) return; top--; size -= *top; top -= *top; } }; it works perfectly well when i play around with primitive values and custom structs, but throws a peculiar error if i use an std::string int main() { Stack<64> t; std::string* a; t.alloc(a); *a = "TEST"; // std::cout << "press enter to exit..."; std::cin.get(); return 0; } the error says "access violation reading location", occurs in memcpy.asm and MSVS2019 always says it occurs one "functional" (meaning non-whitespace and non-comment) line after the assignment. When i do sizeof(std::string) it tells me it's 28, so a 64-byte Stack should have no problem containing that, even with an additional byte carrying its size at the end. Any ideas?
As the comments note: you need to create a string in order to assign a value to it. C++ has construction and assignment, and the two are fundamentally different. Construction is done via the constructor, and creates an object out of raw memory. Assignment is done via the operator= member function, and like all operators requires that an object already exists. Now most of the times you don't need to do much work to call a constructor. Just write ``string s { "This is the initial value"];` in any function, and you construct a local variable. It will be destructed automatically when the function returns. There are many more ways in which you can create objects. Adding an element to a container, for instance, or calling std::make_unique. In your case, you're implementing your own container. That means it's now up to you to call the primitive functions. You could use the new std::construct_at, or the old placement new. . And obviously, call std::destruct_at when popping an element.
73,437,346
73,438,245
Visual Studio comment multiple variables at once?
variables comment method in which a group of variables receive the same comment if the variables declared in a class is for the same task, I don't want to write the same comment for each variable , it make the code dirty. Comment Hover Pop Up declare 5 variables of int type in a row, give a comment description to the first variable and the other 4 variables should take the comment from the first variable , when you mouse hover on any of the variable in visual studio , it should show the comment from the first variable. In doxygen we do something like /*! \name This will be the description for the following group of variables It can be arbitrarily long, but the first line will show up in bold, and any subsequent lines will show up like a description under it */ //@{ int relatedVariable1; int relatedVariable2; char* relatedVariable3; //@} How to achieve something same in visual studio if possible?
What you are asking, is the IntelliSense's task QuickInfo. It shows tooltips, and comments there that are followed by declarations, if the mouse pointer is above their usages. It's not well documented, I could not find more useful info. But I found an reported issue, that complains about not shown comment in a tooltip, if a comment and a declaration are split even by an empty line. Thus, I come to a conclusion, what you have asked is impossible - any comment detached from a declaration will not be shown in a tooltip. In your example, the second and third variables are detached from the comment above the first variable declaration.
73,437,450
73,438,901
WinRT DLL in UWP app crashes when using dependencies from VCPKG
I created an SDK using WINRT because it's the most flexible and I can use it outside UWP apps without having to maintain another SDK for native platforms at the same time. I am using VCPKG as my package manager because it's very easy to maintain. The issue is that if I include a dependency like cpr in the SDK and then try to run in the UWP app I end up with a missing DLL error. If I remove include cpr.h and then just use a test printf in the SDK and try it from the UWP app it works, so I guess something is wrong with third party dependencies when the SDK DLL is being exported. Any idea on how to fix this?
Apparently this isn't mentioned anywhere in Microsoft documentation but you should copy your dependencies to bin\x64\Debug\AppX or bin\x86\Debug\AppX If you're running 32 bit. You can do this as part of the build process by going to properties > Build Events > Post-Build Event and adding copy commands to the above build directory.
73,437,909
73,438,122
extern "C" variables affected by compiler optimization level
Consider this link with the snippet #include <cstdio> namespace X { extern "C" int z; } namespace Y { extern "C" int z; } int X::z = 1; int main() { std::printf("%d -- %d\n", X::z, Y::z); X::z = 2; Y::z = 4; std::printf("%d -- %d\n", X::z, Y::z); X::z = 0; std::printf("%d -- %d\n", X::z, Y::z); } With -O1 GCC outputs 1 -- 1 2 -- 4 0 -- 0 whereas the output of GCC with no optimization enabled matches with that of CLANG (across all optimization levels) i.e. 1 -- 1 4 -- 4 0 -- 0 Is this a compiler bug in GCC because with extern "C" I'd expect name mangling to be disabled and thus there being only the variable z in both the namespaces and thus the values should always be the same.
This is a GCC bug. A similar test case has already been reported here. (Although that one could be a bit more subtle than your test case because it also depends on how exactly using namespace lookup works). As you are expecting the standard says that variable declarations with C linkage and the same name declared in different namespace scopes refer to the same entity, see [dcl.link]/7.
73,438,747
73,438,788
C++ const class member function abs()
Intro I'm currently working on a implementation of a 'mathematical' vector, like in MATLAB, since I'd like to learn more about C++. The Vector class has some constructors (including a copy constructor that is shown below), some operators (including a copy operator, shown below) and some methods (only relevant method shown): template <class T = double> class Vector { public: Vector(Vector<T>& vec) : vector_(vec.vector_), size_(vec.size_) {} // ... some other constructors ... Vector<T>& operator=(const Vector<T>& other) { if (this != &other) { vector_ = other.vector_; size_ = other.size_; } return *this; } // ... some other operators, etc. ... Vector<T> abs() { Vector<T> result = *this; for (std::size_t i = 0; i != length(result); i++) { result.vector_[i] = fabs(result.vector_[i]); } return result; } private: std::vector<T> vector_; std::array<std::size_t, 2> size_{0, 0}; }; FYI: fabs() comes from #include <cmath>. Now I'm currently working on abs(), a element wise absolute value method. Problem Since abs() does NOT change the object itself, it could be made const like this: Vector<T> abs() const { ... } but, apparently this does not work and I get the following errors: error: binding reference of type 'Vector<int>&' to 'const Vector<int>' discards qualifiers Vector<T> result = *this; note: initializing argument 1 of 'Vector<T>::Vector(Vector<T>&) [with T = int]' Vector(Vector<T>& vec) : vector_(vec.vector_), size_(vec.size_) {} Can anyone tell me what the problem is?
This is because your copy constructor cannot accept const reference. In this line Vector<T> result = *this; Copy constructor of Vector<T> is called. But when you mark your member function as const, this is also considered to be pointer to const. And when dereferencing you get const reference to *this, which you try to bind to non-const reference in your copy constructor. The solution is to make your copy constructor accept const reference Vector(const Vector<T>& vec) : vector_(vec.vector_), size_(vec.size_) {} As a general rule, you should accept arguments by const reference if you are not going to change them in the function. Copy constructor usually(in almost all cases) doesn't modify the object from which copying takes place.
73,438,758
73,438,789
C++ How would I make something like this? For every x numbers above 50, increase y value
double mWeight; double mHeight; double mAge; int mExercise; bool mCorrectExercise = true; cout << "Please type in your age: "; cin >> mAge; cout << "Please type in your weight: "; cin >> mWeight; cout << "Please type in your height: "; cin >> mHeight; cout << "Finally, please select an exercise program that most closely matches yours.\n\n1) No exercise.\n\n2) 1-2 hours a week.\n\n3) 3-5hours a week.\n\n4) 6-10 hours a week\n\n5) 11-20 hours a week.\n\n6) 20+ hours a week.\n\n"; cin >> mExercise; int metricResult = (mWeight * 9) + (mHeight * 9) - (mAge * 6.5); /*if (mAge >= 50) { int metricResult = (mWeight * 9) + (mHeight * 9) - (mAge * 8.5); }*/ switch (mExercise) { case 1: cout << "The amount of calories you should consume on average per day:\n\n" << metricResult * 1.0 << "\n\n"; break; case 2: cout << "The amount of calories you should consume on average per day:\n\n" << metricResult * 1.1 << "\n\n"; break; case 3: cout << "The amount of calories you should consume on average per day:\n\n" << metricResult * 1.15 << "\n\n"; break; case 4: cout << "The amount of calories you should consume on average per day:\n\n" << metricResult * 1.25 << "\n\n"; break; case 5: cout << "The amount of calories you should consume on average per day:\n\n" << metricResult * 1.35 << "\n\n"; break; case 6: cout << "The amount of calories you should consume on average per day:\n\n" << metricResult * 1.5 << "\n\n"; break; default: cout << "Invalid input. Please try again.\n\n"; } So in the place of that 'if' statement that is commented out, I'd like something along the lines of "on mAge, for every number above 50, increase mAge in the formula int metricResult = (mWeight * 9) + (mHeight * 9) - (mAge * 8.5); by 0.2" So for if the user types 51, mAge would become (mAge * 8.7) and 52 would make it 8.9, 53 would make it 9.1 etc Does that make sense? It seems pretty complex. Initially I tried loops and if statements but either way it seems like the formula needs to be more flexible than my skills allow. I simply don't have the logic or the skill to make it so. Sorry for being unable to explain it simpler. Thank you
If you break it down into pieces, it becomes easier to see the solution: float overAge = (mAge > 50) ? (mAge - 50) : 0; float ageMultiplier = 8.5 + 0.2 * overAge; int metricResult = (mWeight * 9) + (mHeight * 9) - (mAge * ageMultiplier); In case you are fairly new to programming in C++, the '?' is called a 'ternary operator' and you can look that up for more information.
73,438,870
73,438,909
Accessing templatized static constexpr member of templatized class with template parameter
So I've got a templatized class which has a templatized static constexpr bool. The setup boils down to this: #include <type_traits> template <typename T> class A { public: template <typename U> static constexpr bool same = std::is_same_v<T, U>; }; template <typename T> bool test() { return A<T>::same<int>; // errors } int main() { A<int>::same<int>; // compiles perfectly test<int>(); // errors } When I access it with actual types like A<int>::same<int>, it compiles just fine, but when I try to access it with a template type, as in the test() function above, it errors. Here is the full list of errors: constexpr_value.cpp: In function ‘bool test()’: constexpr_value.cpp:12:21: error: expected primary-expression before ‘int’ 12 | return A<T>::same<int>; | ^~~ constexpr_value.cpp:12:21: error: expected ‘;’ before ‘int’ 12 | return A<T>::same<int>; | ^~~ | ; constexpr_value.cpp:12:24: error: expected unqualified-id before ‘>’ token 12 | return A<T>::same<int>; | ^ constexpr_value.cpp: In instantiation of ‘bool test() [with T = int]’: constexpr_value.cpp:16:12: required from here constexpr_value.cpp:12:16: error: ‘A<int>::same<U>’ missing template arguments 12 | return A<T>::same<int>; | ^~~~ The first three errors are from the template itself, and they show up even when I don't use the test() function at all, so it seems like the compiler is assuming A<T>::same<int> is an invalid statement before even checking any specific Ts. I don't understand these errors at all. Why does A<int>::same<int> compile perfectly, but as soon as you use template types, it doesn't like it at all? I don't even know where to begin fixing this, because the errors tell me nothing. The only difference between compiling and not is using <T> instead of <int>, so is there something I can do with T to tell the compiler that this is a valid statement?
The template code is not equivalent to A<int>::same<int>. This will also compile: template <typename T> bool test() { return A<int>::same<int>; } Returning to the erroneous code. The latest GCC 12.1 would produce the hint in the warning: constexpr_value.cpp: In function 'bool test()': constexpr_value.cpp:12:16: warning: expected 'template' keyword before dependent template name [-Wmissing-template-keyword] 12 | return A<T>::same<int>; // errors | ^~~~ As the warning message suggests the fix: template <typename T> bool test() { return A<T>::template same<int>; } // ^^^^^^^^ See the hot question Where and why do I have to put the "template" and "typename" keywords? for more info.
73,439,773
73,440,758
How to determine current build type of visual studio in CMakeList.txt
This is my build command in CMD: cmake --build . --config Debug This Debug can sometimes be Release, or sometimes it is the default. And I have a code in my CMakeList.txt: if(CMAKE_BUILD_TYPE STREQUAL "Debug") target_link_libraries(${PROJECT_NAME} PRIVATE LLUd wstp64i4) else() target_link_libraries(${PROJECT_NAME} PRIVATE LLU wstp64i4) endif() I think its grammar is fine. But it is a great pity that Visual Studio(multi-config generators) does not recognize the CMAKE_BUILD_TYPE variable as the document. How should I change it? I have found a similar topic here, but it seem don't work for me.
This is all you should need: find_package(LLU REQUIRED PATH_SUFFIXES LLU) target_link_libraries(MyTarget PRIVATE LLU::LLU) If the above isn't working, you should ask about that error, not your attempted workaround. The code you show is broken on several levels. First, the value of CMAKE_BUILD_TYPE should never be used to check the active build type because it is not set when using a multi-config generator like Visual Studio. Every in-project use of CMAKE_BUILD_TYPE is a code smell. It is meant to be set by the person building your project (maybe you, maybe not) as a cache variable from the outside. Second, what you are actually trying to do is to pick a different physical (i.e. on disk) library for Debug mode versus Release (and other *Rel*) mode(s). But this is handled by CMake already. You shouldn't have to do what you're attempting. I'm assuming that LLU is the Wolfram LibraryLink Utilities. If so, you should read the documentation which shows very nearly the same code I gave above. Notice that LLU::LLU is an imported target. Unless Wolfram's LLU package is broken, this will handle per-config library selection automatically. If it is broken, you should complain to the developers, loudly. The moral of the story is, as always, to link to imported targets. If what you're linking to doesn't have :: in its name, you should be wary. Here's a little background on why this is the case: Imported targets that are generated by CMake's package export mechanism have the following properties set on them. These properties control CMake's view of which physical libraries should be used in which build types: IMPORTED_LOCATION_<CONFIG> - This property names the path to the physical library that is to be used in the given configuration. IMPORTED_CONFIGURATIONS - This property contains a list of the configurations that have been imported for the given target. MAP_IMPORTED_CONFIG_<CONFIG> - This is a per-config property that maps <CONFIG>, which should not be present in IMPORTED_CONFIGURATIONS, to a second config that is present in IMPORTED_CONFIGURATIONS. The physical library from the second configuration will be used. Regarding point (3), some packages forget to map MinSizeRel and RelWithDebInfo to Release. If you are getting an error in these configs (but not in Release) you can add the following code to your project before importing any packages: set(CMAKE_MAP_IMPORTED_CONFIG_RELWITHDEBINFO Release) set(CMAKE_MAP_IMPORTED_CONFIG_MINSIZEREL Release) This happens with LLVM's broken CMake packages. Most of the time, though, you don't have to worry about any of this.
73,439,801
73,439,816
How does the execution occurs in c++?
if(condition1 and condition2){ //body } If condition1 turns out to be false, will c++ compiler check for condition2 or will it directly return false?
What you described is called short-circuit evaluation and C++ does use it: if condition1 is false, condition2 will not be checked.
73,439,922
73,439,981
C++ : Is class type const always a top-level const?
Here are the following code: #include <iostream> using namespace std; class A { public: int *x; }; int main() { int b=100; A a; a.x = &b; const A &m = a; // clause 1 - Is this top-level const? int *r = m.x; // *r has no const yet allowed. Is it due to reference m being top level const? } Any help appreciated. Thanks
int const ca = 24; int a = ca; You would expect this to compile right? And indeed it does. Here I initialized a integer with the value 24. You code is the same situation, except that instead of integer you have pointer to integer: m is const so m.x is const. The x is const, i.e. x cannot be modified (via m). In stricter terms m.x is of type int * const i.e. constant pointer to integer. int *r = m.x Here you just initialize the pointer r with the value of the pointer m.x. The fact that m.x is const is not an issue. Both types without their top level cv are identical: pointer to (mutable) integer. const A &m = a; // clause 1 - Is this top-level const? Yes Talking about top level const on references is strange indeed. A reference cannot be rebound. However if we are talking about the referenced type, i.e. const A then yes, it is top level. But then again talking about top level const is useful only on pointer types. E.g. int *const cp vs const int *p.
73,440,392
73,440,488
Initializing a vector with a vector of vector causes segmentation fault in C++
I was revisiting and old project of backtracking that aimed to solve a problem similar to Rat in the Maze and found this chunk of code that for some reason causes a segmentation fault. The isolated line in particular is the one causing the problem. int makeDecision(vector<int> currPos, vector<vector<int> > board, vector<vector<int> > &visited){ int M = board.size(); int N = board[0].size(); int currX = currPos[0]; int currY = currPos[1]; vector<int> prevPos = visited[visited.size()-2]; int prevX = prevPos[0]; int prevY = prevPos[1]; I believe it has something to do with being a double vector, but I'm not entirely sure. This part is the principal function, that calls makeDecision() decisions is a vector that stores the past choices, cPos stands for current position and visited is another vector for checking the places the code has been void backtracking(vector<vector<int> > board, vector<int> &decisions, vector<int> & cPos, vector<vector<int> > &visited) { int M = board.size(); int N = board[0].size(); vector<int> currPos; if (cPos[0] == N - 1 && cPos[1] == M - 1) cout << "\nYou found the exit :D" << endl; // Base case else { int d = makeDecision(cPos, board, visited); decisions.push_back(d); backtracking(board, decisions, cPos, visited); } } And lastly, this is my main function int m; cout << "Enter M: "; cin >> m; int n; cout << "Enter N: "; cin >> n; cout << "\nCreaate board" << endl; vector<vector<int> > b = createBoard(m,n); cout << "\nPrinting..."; printBoard(b); cout << "Solving..." << endl; vector<vector<int> > visited; vector<int> decisions = {0,0}; vector<int> cPos; cPos.push_back(0); cPos.push_back(0); backtracking(b, decisions, cPos, visited); return 0; If needed, I'm compiling with g++ and C++11 A full version of my code is available here
If the problem is in this section, it is likely that one of the assumptions about sizes of inputs is not correct. You can put assert calls to check them before doing anything. int makeDecision(vector<int> currPos, vector<vector<int> > board, vector<vector<int> > &visited){ assert(board.size()>0); assert(currPos.size()>1); assert(visited.size()>1); assert(visited[visited.size()-2].size()>1); int M = board.size(); int N = board[0].size(); int currX = currPos[0]; int currY = currPos[1]; vector<int> prevPos = visited[visited.size()-2]; int prevX = prevPos[0]; int prevY = prevPos[1];
73,440,465
73,440,548
Send IV with cipher text and use it to decrypt cipher text in another function
I have two functions, one for encrypting and another for decrypting. I do not want use static IV, not safe, so I would like to prefix the cipher text with the 16-byte IV so then in the decrypt function I can get the first 16 of the cipher text (the IV used for encrypting originally) and use it to decrypt the text. How can I do this given my current code? This is all straight from a Wikipedia source. I have tried appending the iv to the front of cipher text before exting function, but it never actually changes the cipher text. Am I supposed to change something else? Encrypt: int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext) { EVP_CIPHER_CTX *ctx; int len; int ciphertext_len; /* Create and initialise the context */ if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors(); /* * Initialise the encryption operation. IMPORTANT - ensure you use a key * and IV size appropriate for your cipher * In this example we are using 256 bit AES (i.e. a 256 bit key). The * IV size for *most* modes is the same as the block size. For AES this * is 128 bits */ if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) handleErrors(); /* * Provide the message to be encrypted, and obtain the encrypted output. * EVP_EncryptUpdate can be called multiple times if necessary */ if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) handleErrors(); ciphertext_len = len; /* * Finalise the encryption. Further ciphertext bytes may be written at * this stage. */ if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors(); ciphertext_len += len; /* Clean up */ EVP_CIPHER_CTX_free(ctx); // APPEND IV AT THE BEGINNING OF CIPHER TEXT HERE return ciphertext_len; } Decrypt: int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, unsigned char *iv, unsigned char *plaintext) { EVP_CIPHER_CTX *ctx; int len; int plaintext_len; /* Create and initialise the context */ if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors(); /* * Initialise the decryption operation. IMPORTANT - ensure you use a key * and IV size appropriate for your cipher * In this example we are using 256 bit AES (i.e. a 256 bit key). The * IV size for *most* modes is the same as the block size. For AES this * is 128 bits */ if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) handleErrors(); /* * Provide the message to be decrypted, and obtain the plaintext output. * EVP_DecryptUpdate can be called multiple times if necessary. */ if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) handleErrors(); plaintext_len = len; /* * Finalise the decryption. Further plaintext bytes may be written at * this stage. */ if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors(); plaintext_len += len; /* Clean up */ EVP_CIPHER_CTX_free(ctx); return plaintext_len; }
Your concern is correct, it is a must to use different IV's for each encryption. You can first copy IV to cyphertext and put the output after the IV like this: int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext) { EVP_CIPHER_CTX *ctx; int len; int ciphertext_len; /* Create and initialise the context */ if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors(); /* * Initialise the encryption operation. IMPORTANT - ensure you use a key * and IV size appropriate for your cipher * In this example we are using 256 bit AES (i.e. a 256 bit key). The * IV size for *most* modes is the same as the block size. For AES this * is 128 bits */ if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) handleErrors(); // Copy IV to ciphertext int iv_len = 16; memcpy(ciphertext, iv, iv_len); ciphertext_len = iv_len; /* * Provide the message to be encrypted, and obtain the encrypted output. * EVP_EncryptUpdate can be called multiple times if necessary */ if (1 != EVP_EncryptUpdate(ctx, ciphertext + ciphertext_len, &len, plaintext, plaintext_len)) handleErrors(); ciphertext_len += len; /* * Finalise the encryption. Further ciphertext bytes may be written at * this stage. */ if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + ciphertext_len, &len)) handleErrors(); ciphertext_len += len; /* Clean up */ EVP_CIPHER_CTX_free(ctx); return ciphertext_len; } and call decrypt like: int iv_len = 16; decrypt(ciphertext+iv_len, ciphertext_len, key, ciphertext, plaintext); Make sure that ciphertext is capable of holding both IV and cyphertext. But it looks cleaner to me if you do this packing not in encrypt function but on the calling site. With this approach you keep the encrypt and decrypt function as is, and on the calling sites: // encryption int iv_len = 16; int ciphertext_len = encrypt(plaintext, plaintext_len, key, iv, ciphertext); unsigned char * packed = malloc(ciphertext_len + iv_len); memcpy(packed, iv, iv_len); memcpy(packed+iv_len, ciphertext, ciphertext_len); ... // decryption int iv_len = 16; decrypt(ciphertext+iv_len, ciphertext_len, key, ciphertext, plaintext);
73,440,925
73,441,417
How much memory allocated with vector initialized with initializer lists and push_back
If I have these 2 lines of code in C++ vector<int> vec = {3,4,5}; vec.push_back(6); How much memory is allocated in total for the 2 lines and what assumption we need to make? I tried to look these up but can't find the definition for these anywhere.
Looking at llvm's libcxx library as an example, we could speculate that the capacity would be 6 ints in size. vector<int> vec = {3,4,5}; allocates 3 ints on initialization __vallocate(3); template <class _Tp, class _Allocator> inline _LIBCPP_INLINE_VISIBILITY vector<_Tp, _Allocator>::vector(initializer_list<value_type> __il) { #if _LIBCPP_DEBUG_LEVEL >= 2 __get_db()->__insert_c(this); #endif if (__il.size() > 0) { __vallocate(__il.size()); __construct_at_end(__il.begin(), __il.end(), __il.size()); } } vec.push_back(6); triggers re-allocation with a doubling in capacity 2*__cap // Precondition: __new_size > capacity() template <class _Tp, class _Allocator> inline _LIBCPP_INLINE_VISIBILITY typename vector<_Tp, _Allocator>::size_type vector<_Tp, _Allocator>::__recommend(size_type __new_size) const { const size_type __ms = max_size(); if (__new_size > __ms) this->__throw_length_error(); const size_type __cap = capacity(); if (__cap >= __ms / 2) return __ms; return _VSTD::max<size_type>(2*__cap, __new_size); } https://github.com/llvm-mirror/libcxx/blob/78d6a7767ed57b50122a161b91f59f19c9bd0d19/include/vector Update (based on ChrisD's comment) Since the capacity multiplier could be in the range of 1.5 to 2, the size could be 4, 5, or 6 ints.
73,443,214
73,447,984
Determining the type of the template parameter method argument
There are many IEnumXXXX type COM interfaces that have a pure virtual method Next, like this: IEnumString : IUnknown { ... virtual HRESULT Next(ULONG, LPOLESTR*, ULONG*) = 0; ... }; IEnumGUID : IUnknown { ... virtual HRESULT Next(ULONG, GUID*, ULONG*) = 0; ... }; Need a template, like this: enum_value_type<IEnumString>::type // LPOLESTR enum_value_type<IEnumGUID>::type // GUID
Something along these lines: template <typename T> struct ExtractArgType; template <typename C, typename T> struct ExtractArgType<HRESULT (C::*)(ULONG, T*, ULONG*)>{ using type = T; }; template <typename IEnum> struct enum_value_type { using type = typename ExtractArgType<decltype(&IEnum::Next)>::type; }; Demo
73,443,378
73,453,797
array transfer constructor function c++
I am trying to learn constructors in c++. I am working on a list that I defined. I managed to get the copy constructor working, but I have problems with the array transfer constructor. Any help will be appreciated. Thanks! The array transfer constructor supposedly should take in an array and a size(int) and output a list with that size. ex: input: data = {1,3,5,6};int = 5;output = {1,3,5,6,0} edit: change n to i #include <iostream> using namespace std; class list_element{ public: list_element(int n = 0,list_element* ptr = nullptr): d(n),next(ptr){} int d; list_element* next; }; class List{ public : List():head(nullptr),cursor(nullptr){} List(const int* arr, int n); // copy array transfer data List(const List& lst); //copy constructor void prepend(int n); int get_element() { return cursor->d; } void advance() { cursor = cursor->next; } void print(); ~List(); //delete private: list_element* head; list_element* cursor; }; //transfer array List::List(const int* arr, int n) { List temp; int i = 0; while (i < n) { head = new list_element(arr[i], head); ++i; } } //delete List::~List(){ for (cursor = head; cursor != 0;) { cursor = head->next; delete head; head = cursor; } } //deep copy constructor List::List(const List& lst) { if (lst.head == nullptr) { head = nullptr; cursor = nullptr; } else { cursor = lst.head; list_element* h = new list_element(); list_element* previous; head = h; h->d = lst.head->d; previous = h; for (cursor = lst.head; cursor != 0;) { h = new list_element(); h->d = cursor->d; previous->next = h; cursor = cursor->next; previous = h; } cursor = head; } } void List::prepend(int n) { if (head == nullptr) cursor = head = new list_element(n, head); else head = new list_element(n, head); } void List::print() { list_element* h = head; while (h != 0) { cout << h->d << ','; h = h->next; } cout << "###" << endl; } int main() { List a, b; //change size int data[10] = { 1,3,5,7}; List d(data, 10); d.print(); return 0; }
Main Question With regards to your 'from_array' constructor, you have a temporary List variable that you are not using and is also unnecessary. Second you are assigning the head pointer each time meaning that by the end of the constructor call, head now points to the last element you constructed. Third your list_element constructor is taking the old head pointer which points to the previous element meaning the list is tries to advance from the bottom element upwards through the list, causing the reversed read you mentioned in a comment. You can fix this two ways. First, you could reverse the order you read the input array so it constructs your linked-list back to front. List::List(const int* arr, int n) { int i = n - 1; list_element* it = new list_element(arr[i], nullptr); ///< Last element --i; while (i > -1) { it = new list_element(arr[i], it); --i; } head = it; ///< assign head to the last instance of it. it = nullptr; } However, there is a better why that expresses the linking of the elements more intuitively. First you need to pre-construct the next element and give it some default values (I didn't bother implementing a default constructor for list_element but you might want to.) and assign it to next, then assign head to a new list_element passing in the pointer to next. increment i so that you can assign next's value to the second value in the array. Finally incremenet i again so we can loop through the rest of the array. Finally, in the while loop, copy next into a variable called prev. Assign next to a new list_element with the value from the array and a nullptr. Finally assign prev->next to the new next pointer and increment i. list_element::list_element() List::List(const int* arr, int n) { int i = 0; list_element* next = new list_element(0, nullptr); head = new list_element(arr[i], next); ++i; next->d = arr[i]; ++i; while (i < n) { list_element* prev = next; next = new list_element(arr[i], nullptr); prev->next = next; ++i; } } Side Notes Because you stated you are tying to learn about C++ constructors (and I'm assuming data structures) I would suggest starting with a static array type similar to std::array as it's constructors a bit more trivial to implement or even just start with simple classes/struct that just hold simple data like a few ints or whatnot as you can get an idea for the semantics around the various constructors in C++. Also, the C++ standard library has two linked list types (std::list and std::foward_list) Finally, you might be better off using a std::initializer_list instead of a raw array as this give you iterators to the data you want to copy which is a bit nicer to use. Best of luck in your learning journey.
73,443,940
73,444,170
Is it bad to leave events unprotected?
I'm writing some code that includes events which are custom-implemented and class that uses these events and invokes them when something happens(ex. window closes). It looks something like this: // phony.h class Phony { public: Phony(); ~Phony(); // some stuff void i_invoke_click(); void i_invoke_resize(); private: Event<Arg1> click; Event<> resize; Event<Arg2> event3; Event<Arg3> event4; }; // event.h template <typename... Args> class Event { public: void invoke(Args... params) const void add(std::function<void(Args...)> func) void remove(std::function<void(Args...)> func) void operator+=(std::function<void(Args...)> func) // same as add void operator-=(std::function<void(Args...)> func) // same as remove void operator()(Args... params) // invoke private: std::list<std::function<void(Args...)>> invoke_list; }; Now I need to implement some interface so other classes could subscribe/unsubscribe to events like click. I have considered two ways to do this: Make access methods like subscribe_to_click(func)(which will make many methods and not convenient) Or make events public so you could directly access them via +=(which is convenient) But I think that second way of putting events violates encapsulation but I'm not sure in it. So the question is: Is it okay to leave events public or I should make it the ugly(but safe) way?
What I could suggest coming from a C# background is to use a base class like IObservable for the Events which implements some subscribe method or your approach with operator overloading. Then make the IObservables public by returning a reference that refers to the events themselves: #include <functional> #include <list> template <typename... Args> class IObservable { public: void operator+=(std::function<void(Args...)> func); // same as add void operator-=(std::function<void(Args...)> func); // same as remove }; template <typename... Args> class Event : public IObservable<Args...> { public: void operator()(Args... params); // invoke private: std::list<std::function<void(Args...)>> invoke_list; }; class Phony { public: Phony(); ~Phony(); void i_invoke_click(); void i_invoke_resize(); IObservable<int>& Click() { return click; } IObservable<>& Resize() { return resize; } IObservable<int>& Event3() { return event3; } IObservable<int>& Event4() { return event4; } private: Event<int> click; Event<> resize; Event<int> event3; Event<int> event4; }; void foo(int x); int main() { Phony p; p.Click() += &foo; // p.Click()(); no invoke possible }
73,443,971
73,444,142
C++ Move constructor for object with std::vector and std::array members
I'm currently implementing a Vector class that is supposed to handle the math. This class has two members std::vector<double> vector_ and std::array<std::size_t, 2> size_. Now I want to write a move constructor Vector(Vector&& other);. I've tried multiple ways, including Vector(Vector&& other) = default;, but none seems to do the job correctly. I always end up with both objects having the same size_ array, instead of the other having {0, 0}. Aren't the default move constructor or std::move(...) supposed to move the contents and set the other's content to their default values?
[...] and set the other's content to their default values? No. When not stated otherwise a moved from object is in a valid, but unspecified state. Setting all elements to some default would be rather wasteful. Further, a std::array does contain the elements. Its not just a pointer to some dynamically allocated elements that could cheaply be moved. The elements are right within the array. Hence you can only move the individual elements, the array as a whole can only be copied. A std::array is moveable when its elements are moveable, otherwise moving it will merely make a copy. For details I refer you to Is std::array movable?. TL;DR Vector(Vector&& other) = default; is fine. You just expected it do something it does not do. Neither does moving set the moved from elements to some default, nor does moving the std::array<size_t,2> actually move the elements, rather it copies them.
73,444,061
73,444,148
Passing std::ranges::views as parameters in C++20
I have a method that prints a list of integers (my actual method is a bit more complicated but it is also read-only): void printElements(const std::vector<int> &integersList) { std::for_each(integersList.begin(), integersList.end(), [](const auto& e){ std::cout << e << "\n"; }); } Now suppose I have the following vector: std::vector<int> vec{1,2,3,4,5,6,7,8,9,10}; Then I want to print even numbers only. To do this, I thought of employing the new std::ranges feature in C++20. I know that you can do this as follows: auto evenList = vec | std::views::filter([](auto i){ return i % 2 == 0; }); Now I would like to call printElements(evenList), however this obviously won't compile. What would be the solution to this? Also can I write a single function that will both print a std::vector and an object of the same type as my evenList? Or do I need to write two separate functions?
You can make printElements take any object by making it a function template. This will instantiate it for views as well as vectors. #include <algorithm> #include <iostream> #include <ranges> void printElements(std::ranges::input_range auto&& range) { std::ranges::for_each(range, [](const auto& e) { std::cout << e << '\n'; }); } Demo or: // ... #include <iterator> void printElements(std::ranges::input_range auto&& range) { using T = std::ranges::range_value_t<decltype(range)>; std::ranges::copy(range, std::ostream_iterator<T>(std::cout, "\n")); } Demo
73,444,110
73,444,204
comparing std::vector to a raw value of the same type give error
I was doing an exercise while I noticed this this code work okay: std::vector<std::string> x = { "st1", "st1" }; std::vector<std::string> y = { "st1", "st1" }; assert(x == y); while this give me error when trying to compile it std::vector<std::string> x = { "st1", "st1" }; assert(x == { "st1", "st1" }); I have no idea why is that the case, could someone explain why and how to force it to compile if there is way to do it.
The error should have told you something along the line of "{ "st1", "st1" } has no type". If you want to construct a second vector you need to call the constructor: assert(x == std::vector<std::string>{ "st1", "st1" });
73,444,207
73,444,790
C++: freopen (and I/O) just refuses to work
Today I'm having issues with my code. It appears that I can not get anything from input (whether file or stdin) as well as unable to print (whether from file or stdout). My code can have a lot of issues (well, this is code for a competitive programming problem, don't expect it to be good. It will be straight up horrendous and violate everything you know about C++). #include <bits/stdc++.h> #include <climits> #include <vector> using namespace std; #define mp make_pair #define endl "\n" #define ll long long #define ld long double const int nm = 1e3 + 1; const int mod = 1e9 + 7; void fastio(string fi, string fo){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); if (fi.length() > 0){ freopen(fi.c_str(), "r", stdin); } if (fo.length() > 0){ freopen(fo.c_str(), "w", stdout); } } int m, n; int demsm(int k, int p){ int c = 0, r = p; while (r <= k){ c += int(k / r); r *= p; } return c; } vector<pair<int, int>> uoc(int x){ vector<pair<int, int>> u; for (int i = 2; x != 1; i++){ int c = 0; while (x % i == 0){ c++; x /= i; } u.emplace_back(mp(i, c)); } return u; } int main(){ fastio("", ""); cin >> n >> m; cout << n << " " << m << endl; auto snt = uoc(m); for (auto i : snt){ cout << i.first << " " << i.second << endl; } int a = 1e9; for (auto i : snt){ a = min(a, demsm(n, i.first) / i.second); } cout << a << endl; }
This isn't an issue with freopen or I/O. Here a = min(a, demsm(n, i.first) / i.second); You are dividing by zero and this results a segmentation error. The reason why the program isn't printing anything is because of the way how these lines work. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); You can read about them in this question.
73,444,527
73,444,820
Get process's thread information in windows OS
I'm new in c++ programming and I'm coding a tool to enumerate information of all process running on windows OS. After researching, googling, I have found a useful library Ntdll.lib and header winternl.h that helping me gathering information about process by using NtQuerySystemInformation() function. Everything work fine, I have call that function and retrieved the array of structure SYSTEM_PROCESS_INFORMATION that contains information about the process entry, here is my piece of code: DWORD dwRet; DWORD dwSize = 0; NTSTATUS Status = STATUS_INFO_LENGTH_MISMATCH; while (true) { // Check if pointer p is not NULL then free it if (p != NULL) { VirtualFree(p, 0, MEM_RELEASE); } p = (PSYSTEM_PROCESS_INFORMATION)VirtualAlloc(NULL, dwSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); // Query system to get the process list information Status = NtQuerySystemInformation(SystemProcessInformation, (PVOID)p, (ULONG)dwSize, &dwRet); if (Status == STATUS_SUCCESS) { cout << "Query process information successfully!!" << endl; break; } else if (Status != STATUS_INFO_LENGTH_MISMATCH) { VirtualFree(p, 0, MEM_RELEASE); p = NULL; cout << "NtQuerySystemInformation failed with error code: " << Status << endl; return FALSE; } // Add more 16kb to buffer in case there is more process opened during this loop dwSize = dwRet + (2 << 14); } The problem appears when I was looking for thread details of processes, in particular, I don't know how to get the array of structure SYSTEM_THREAD_INFORMATION with NtQuerySystemInformation() function. I have read the docs here: https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntquerysysteminformation and it says that each SYSTEM_PROCESS_INFORMATION structure returned by NtQuerySystemInformation() has 1 or more SYSTEM_THREAD_INFORMATION structure followed in memory but I don't know how to interact with them. Anyone has an idea for my problem? I'm just a newbie in c++ programming and I'm studying in user mode code so sorry if my question is silly or not worth asking.
Starting from your PSYSTEM_PROCESS_INFORMATION p: while (p) { PSYSTEM_THREAD_INFORMATION pt = (PSYSTEM_THREAD_INFORMATION)(p + 1); for (int t = 0; t < p->NumberOfThreads; t++) { std::cout << "Start address of thread " << t << " is " << std::hex << pt->StartAddress << std::dec << std::endl; pt++; // Adds sizeof(SYSTEM_THREAD_INFORMATION) to the address in pt } if (p->NextEntryOffset) { p = PSYSTEM_PROCESS_INFORMATION((void *)p + NextEntryOffset); } else { p = nullptr; } }
73,446,020
73,446,182
Equation with abs() gives wrong answer (gcc/g++)
Somehow I get wrong result from equation which involves library function abs(). Here's my code where the issue is present: main.cpp ------------------------------------- #include <iostream> #include <cmath> #include "test999.h" using namespace std; int main() { float n = 11; ak r; r = test(n); printf("\n"); for(int i = 0; i < n; i++){ printf("r.yp[%d] = %3.7f \n", i, r.yp[i]); } return 0; } test999.h --------------------------------------- struct ak{ float yp[20]; }; ak test(int n){ float u[] = {0, 0, 0, 0, 0, 0, 0, 0.5, 4.5, 35, 10, 25, 40, 55}; ak r; float a, b; for(int i = 0; i < n; i++){ a = abs(u[i+3] - u[i+2]); b = abs(u[i+1] - u[i]); printf("i = %d a = u[%d](%2.4f) - u[%d](%2.4f) = %2.4f \n b = u[%d]-u[%d] = %2.4f (%2.4f - %2.4f) \n", i, i+3, u[i+3], i+2, u[i+2], a, i+1, u[i+1], i, u[i], b); if ((a+b) != 0.0f){ r.yp[i] = (a * u[i+1] + b * u[i+2]) / (a+b); } else{ r.yp[i] = (u[i+2] + u[i+1]) / 2.0f; } printf("yp[%d] = %2.4f \n\n", i, r.yp[i]); } return r; } and it results wrong value for equation of abs(0.5)-0.0 (case i=4) and abs(35.0)-4.5 (case i=6): Changing equation to use std::abs() calculates correctly: If I move everything to main.cpp module both cases works so, is it just that because of I have made defect code ... or rounding from 0.5 to 0.0 happened somewhere I should have taken into account... ?
There is std::abs(int) and there is std::abs(float). The former is inherited from C abs(int). In C there is no overload for floating points, it is called fabs (also available as std::fabs). You tripped over using namespace std; obfuscating what function is actually called. Note that you have it in main, but not in the header, which is actually good, but it still does harm in main, because once you place all code in main, suddenly a different function gets called. Without using namespace std;, abs(some_float) calls ::abs(int). With using namespace std;, abs(some_float) calls std::abs(float). Note that the headers inherited from C are allowed but not guaranteed to introduce the names in the global namespace, so you could also get a compiler error. Replace abs with std::abs and remove using namespace std. For more reasons to not pull in all names from std I refer you to Why is "using namespace std;" considered bad practice?
73,446,148
73,446,228
Partial emplate Argument Deducion C++
I have the following code: template <class B, class A> class C { A m_a; public: explicit C(A a) : m_a(a) {} }; int main() { C<int>(16); return 0; } that can not be compiled. My purpose is to automatically deduce class A using the constructor parameter but use manually mentioned class B. Is it possible?
Sure, but only with a helper function. As currently written, C<int> has to be the complete name of a type, which it obviously isn't. The constructor argument isn't considered until after the type of the object is determined. So write template <class B, class A> C<B,A> make_c(A a) { return C<B,A>{a}; } int main() { auto c = make_c<int>(16); and now you have a function template whose second type parameter can be deduced as you want, from the argument, before you have to write out the type it returns.
73,446,842
73,446,927
What does a semicolon after function inside function mean?
I saw an answer for a c++ challenge that had you copy a certain part of a string x times. std::string repeatString(int xTimes) { repeatString;(3); //What's happening here? } He seemed to have solved the challenge with this code and I'm guessing he solved it the wrong way but I'm still unsure what's happening. original challenge: https://edabit.com/challenge/vxpP4nnDhRr2Yc3Lo original answer by Marcus_2008
repeatString; is an expression that does nothing useful. Same for (3);. Its the same as 3; and does literally nothing. After removing that unnecessary fluff, the function is std::string repeatString(int) { //What's happening here? // - nothing at all } And this, not only does it not repeat a string, but it invokes undefined behavior when called, because it is declared to return a std::string but does not. Even changing the line to repeatString(3); would leave us with the same issue while return repeatString(3); would result in infinite recursion. It is not possible that this code solves the task. You must have misunderstood something, or the real code looks different.
73,447,085
73,474,435
Qt: Cannot read device, no error provided
I have some code for Qt below that connects two devices via UART if possible. If not possible, it will display an error string. void Hardware::initialisePort(QString portName) //Initialized at balance and controlboard { /*! \brief Method to initialise the com port * */ // setup the port in the appropriate way for the platform that the code is compiled for this->serialPort = new QextSerialPort(portName, QextSerialPort::EventDriven); //serialPort now points to this new QextSerialPort, and the string will come from this port. // setup port settings serialPort->setBaudRate(BAUD9600); serialPort->setFlowControl(FLOW_OFF); serialPort->setParity(PAR_NONE); serialPort->setDataBits(DATA_8); serialPort->setStopBits(STOP_1); // attempt to open the port for both reading and writing if (serialPort->open(QIODevice::ReadWrite) == true) { // connect the port ready to read signal to the handling slot connect(serialPort, SIGNAL(readyRead()), this, SLOT(serialDataReady())); //readyRead is just signal, not function, serialDataReady is function that breaks up Arduino string qDebug() << "Listening for data on" << serialPort->portName(); } else // could not open port communications { qDebug() << "Device failed to open:" << serialPort->errorString() << ":" << portName; // print the issue to the log with the port error string //logging() << "Could not open serial port connection: " << serialPort->errorString(); } } I have two ports initialized, as below: Balance::Balance() : Hardware() { // initialise members // null values for the unallocated masses lastStableMass = -1; lastUnstableMass = -1; stable = false; timeoutStatus = 0; hasTimedOut = false; calibrationInProgress = false; tareOffset = 0; this->initialisePort("/dev/tty01"); //Port name is /dev/tty01 timer.setInterval(2000); connect(&timer, SIGNAL(timeout()), this, SLOT(resend())); timer.start(); } ControlBoard::ControlBoard(QObject *obj) : Hardware(obj) { /*! \brief Constructor * */ this->initialisePort("/dev/ttyO4"); //Port name is /dev/tty04, and that is somewhere on the control board, don't worry about it //Initialise port is in hardware.cpp this->airTempMessage = ""; this->valveChangeMessage = ""; acknowledgementTimer = 0; calibrationTimer = 0; sendCalibration = -1; this->sampleTempTimer = new QTimer; connect(sampleTempTimer, SIGNAL(timeout()), this, SLOT(requestSampleTempUpdate())); hasTimedOut = false; valveOpen = false; airTemperature = 0; temporaryCalFactor = -1; compressorTimer = 0; requestValveUpdate(); } This is something I have received with the code: Device failed to open: "No Error has occurred" : "/dev/tty01" Listening for data on "/dev/ttyO4" I am unsure why. I have attempted to do the following: else // could not open port communications { connect(serialPort, SIGNAL(readyRead()), this, SLOT(serialDataReady())); //Even though the port is listed as cannot be opened, I attempted to see whether the error signal was a false flag by initializing it anyways. qDebug() << "Device failed to open:" << serialPort->errorString() << ":" << portName; // print the issue to the log with the port error string //logging() << "Could not open serial port connection: " << serialPort->errorString(); } This did not result in the port actually opening. Please let me know if more information is required to solve this issue; I will update this question accordingly.
There was a typo. The port was written as "tty01", when it should have been "ttyO1", O for Orange instead of a zero. Thanks to chehrlic for catching it, 0s and Os are a bit too similar in Linux.
73,447,272
73,447,857
Visual C++: cast to function type is illegal, g++ also yields an error
My generated code always used unnecessary many parenthesis simply to make certain, that the C++ code was actually doing what the AST expressed. This is first time I'm getting this compiler error, which I cannot explain -- also before I've used custom types. (define G_ERROR to get an error...) Visual C++ 2019 yields the following error: cl -c tmp0.cpp -I ..\Documents\WORK\boost_1_77_0 -DG_ERROR tmp0.cpp(32): error C2066: cast to function type is illegal tmp0.cpp(40): error C2675: unary '+': 'abstractValue<32>' does not define this operator or a conversion to a type acceptable to the predefined operator tmp0.cpp(40): error C2088: '+': illegal for class g++ v10 yields the following error: g++-10 -std=c++11 -c tmp0.cpp -I /mnt/c/Users/userName/Documents/WORK/boost_1_77_0/ -DG_ERROR tmp0.cpp:40:3: error: no match for ‘operator+’ (operand type is ‘abstractValue<>’) #include <vector> #include <boost/optional.hpp> #include <type_traits> #include <functional> #include <initializer_list> #include <set> struct undetermined { }; template<std::size_t SIZE=32> class abstractValue { public: abstractValue(const double); abstractValue(const undetermined&); abstractValue operator+(const abstractValue&) const; }; struct instance { double DTEMP; abstractValue<> function_231( std::vector<boost::optional<abstractValue<>> >&_r ) const{ auto &r = _r.at(231); if ( !r )r = #ifdef G_ERROR ( #endif abstractValue<>( undetermined() ) #ifdef G_ERROR ) #endif +( abstractValue<>( DTEMP ) ); return r.value(); } };
abstractValue<>(undetermined()) Because both abstractValue<> and undetermined are types, there are two interpretations of this without further context: It is a functional-style explicit cast expression creating a prvalue of type abstractValue<> with (undetermined()) its initializer. It is a type-id, namely the type of a function returning abstract<> with a single parameter of type "function without parameters returning undetermined" (which is adjusted to "pointer to function without parameters returning undetermined"). You want it to mean the first, not the second. When writing abstractValue<>(undetermined()) + /*...*/ it cannot have the meaning of 2. and + can only be the binary + operator, but because there are C-style explicit cast expressions in the form of (T)E where T is a type and E an expression, in (abstractValue<>(undetermined())) + /*...*/ the whole expression could also be such a C-style explicit cast expression with abstractValue<>(undetermined()) being T and +/*...*/ being E with + the unary +. Because the grammar is ambiguous here, there is a rule saying that any construct that could be interpreted as a type-id in such a situation, is interpreted as a type-id. Therefore the interpretation as 2. is chosen here. You can avoid this by either simply not using the extra parentheses (as seen they can not always be added without affecting the meaning of an expression) or you can use brace-initialization instead of initialization with parentheses, because braces cannot appear in a function type, disqualifying the 2. immediately in all contexts: abstractValue<>{undetermined()} or abstractValue<>(undetermined{}) or abstractValue<>{undetermined{}}
73,447,278
73,447,407
C++ reference calls 'wrong' destructor
Why does below snippet print: Constructing Working on this Constructing working on that Destructing working on that Destructing working on that I would expect "constructing this + that" and "destructing this that". So the idea here is to have to have a reference to a workingItem and then do something in the destructor if something goes out of scope. It seems that this does not work, and my question is why? Does this cause a memory leak? Also why don't I get "destructing this" because I did not overwrite a? I can get this working by making workingItem a pointer, but my question is: is there also a way to get this working by using a ref? #include <iostream> class A { private: std::string str; public: A(const std::string& s) : str(s) { std::cout << "Constructing "<<s<<std::endl; }; ~A() { std::cout << "Destructing "<<str<<std::endl; }; }; int main() { A a("Working on this"); A& workingItem=a; A a2("working on that"); workingItem=a2; }
Implement a operator= to get the full picture: #include <iostream> class A { private: std::string str; public: A(const std::string& s) : str(s) { std::cout << "Constructing "<<s<<std::endl; }; ~A() { std::cout << "Destructing "<<str<<std::endl; }; A& operator=(const A& other){ std::cout << "assign " << other.str << " to " << str <<"\n"; str = other.str; return *this; } }; int main() { A a("Working on this"); A& workingItem=a; A a2("working on that"); workingItem=a2; } Output is: Constructing Working on this Constructing working on that assign working on that to Working on this Destructing working on that Destructing working on that You cannot rebind references. This line A& workingItem=a; initializes the reference workingItem to refer to a. This line is something completely different: workingItem=a2; it assigns a2 to the object refered to by workingItem, and that is a1. It is the same as a1 = a2;. Hence you end up with two identical As that get destroyed when main returns. In general it is important to be aware of the difference between initialization, T x = y;, and assignment, x = y;.
73,447,342
73,447,737
CMake and GoogleTest weird behaviour with comparison when changing build type from Debug to Release
Context I am writing a function which calculates some exponential value for a timer application. It simply takes 2^x until some threshold maxVal, in which case the threshold should be returned. Also, in all cases, edge cases should be accepted. util.cpp: #include "util.h" #include <iostream> int calculateExponentialBackoffDelay(int x, int maxVal) { int y; if(x <= 0 || maxVal <= 0) return maxVal; else if (x > maxVal) return maxVal; y = std::pow(2, x); std::cout << "y = " << y << std::endl; if(y > maxVal) return maxVal; else if(y < 0) return maxVal; else return y; } Now I make a CMake configuration with a GoogleTest dependency fetch. CMakeLists.txt: cmake_minimum_required(VERSION 3.14) project(my_project) # GoogleTest requires at least C++14 set(CMAKE_CXX_STANDARD 14) set(CMAKE_BUILD_TYPE Release) include(FetchContent) FetchContent_Declare( googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG release-1.12.1 ) # For Windows: Prevent overriding the parent project's compiler/linker settings set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) FetchContent_MakeAvailable(googletest) enable_testing() include_directories( ${CMAKE_CURRENT_LIST_DIR}/ ) # Add the main source compilation units add_executable( test_calc test_calc.cpp util.cpp ) target_link_libraries( test_calc GTest::gtest_main ) include(GoogleTest) gtest_discover_tests(test_calc) I run a test on the function that I have written which tests some boundary conditions. One of which is testing that if 2^x > maxVal, then maxVal should just be returned (because the result of the 2^x is above the maximum value). This is the threshold. test_calc.cpp: #include "util.h" #include <climits> #include <gtest/gtest.h> TEST(util_tests, ExponentialBackoff) { int x, maxVal, res; // Test x = maxVal and maxVal = 1000 // Expected output: 1000 maxVal = 1000; x = maxVal; EXPECT_EQ(maxVal, calculateExponentialBackoffDelay(x, maxVal)); } When I set x and maxVal to 1000, 2^(1000) is calculated and because it's such a big number, there is an overflow / wraparound to a really negative number (-2147483`648). That is expected, and therefore my test will expect the result of x=1000, maxVal=1000 to be < 0. Problem This is where things go unexpectedly. I run ctest inside my build directory and all test cases pass. Then I change one line in CMakeLists.txt from ... : set(CMAKE_BUILD_TYPE Debug) ... to ... set(CMAKE_BUILD_TYPE Release) ... and that test case fails: 1: Expected equality of these values: 1: maxVal 1: Which is: 1000 1: calculateExponentialBackoffDelay(x, maxVal) 1: Which is: -2147483648 So for some reason, the case where y < 0 inside the function body is not being reached and instead, we are returning the wraparound result. Why is this? What am I doing wrong? I tried using the Linux strip -s test_calc to check if it was a symbols thing while keeping the debug configuration in CMake, only to find that test cases still pass. What else does CMake do to change the comparison behaviour of the resulting binary?
Floating-integral conversions A prvalue of floating-point type can be converted to a prvalue of any integer type. The fractional part is truncated, that is, the fractional part is discarded. If the value cannot fit into the destination type, the behavior is undefined. - This is it. The behavior is undefined. Any expectations for results of int y = std::pow(2, x) with x > 31 is considered to be invalid and may lead to any result of the function calculateExponentialBackoffDelay. In this particular case, compilers know y = std::pow(2, x) is always greater than 0 for valid values of x and drop the branch if (y < 0) off.
73,447,593
73,452,569
How to cut a part of a shape with the help of another painted shape above?
On the screen below I have the image with the painted translucent rectangle and with the painted opaque rectangle. My purpose is to cut the area of the opaque rectangle - delete pixels in the translucent rectangle in order to see the initial image. cairo_surface_t *surface = cairo_xlib_surface_create(xdisplay, xroot, DefaultVisual(xdisplay, scr), DisplayWidth(xdisplay, scr), DisplayHeight(xdisplay, scr)); cairo_t *cr = cairo_create(surface); cairo_surface_write_to_png( surface, "test.png"); cairo_surface_t *surfaceTmp = cairo_image_surface_create_from_png("./test.png"); if (xevent.type == MotionNotify && isPressed == true) { int tmp_x = xevent.xmotion.x_root; int tmp_y = xevent.xmotion.y_root; cairo_save(cr); cairo_set_source_surface(cr, surfaceTmp, 1, 1); cairo_paint(cr); cairo_set_source_rgba(cr, 0, 0, 0, 0.2); cairo_rectangle(cr, 0, 0, DisplayWidth(xdisplay, scr), DisplayHeight(xdisplay, scr)); cairo_fill(cr); cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR); cairo_rectangle(cr, init_x, init_y, tmp_x - init_x, tmp_y - init_y); // set rectangle cairo_fill(cr); cairo_restore(cr); } Why do I have this black rectangle? I thought that CAIRO_OPERATOR_CLEAR should delete the shape part beneath. The desired outcome:
Maybe, since cairo's drawings change pixels directly (=not buffered), once you draw something, there remain no underlying original pixels that can be recovered afterwards. If you'd like to hole the rectangle, try the fill rule: CAIRO_FILL_RULE_EVEN_ODD. cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD); // The default is CAIRO_FILL_RULE_WINDING. cairo_set_source_rgba(cr, 0, 0, 0, 0.2); cairo_rectangle(cr, 0, 0, DisplayWidth(xdisplay, scr), DisplayHeight(xdisplay, scr)); //cairo_fill(cr); //cairo_set_operator(cr, CAIRO_OPERATOR_CLEAR); cairo_rectangle(cr, init_x, init_y, tmp_x - init_x, tmp_y - init_y); // set rectangle cairo_fill(cr);
73,449,114
73,449,198
How to declare and initialize a vector of semaphores in c++?
Say I have n different resources. Let's say n = 5 as an example, but n can be large and optionally an input value. I want to initialize a vector of n binary semaphores. How do I do that? I believe the problem is because the constructor for binary_semaphore or counting_semaphore has been marked explicit. I've tried the vector constructor for n objects of the same value, and also push_back and emplace_back, but nothing seems to work. Is there a way to solve this problem?
Semaphores (along with many other mutex-like types... including mutex) are non-moveable. You cannot put such a type in a vector. This is not about explicit constructors; it's about the lack of a copy or move constructor. Allocating an array of these is made difficult by the lack of a default constructor. You can try to work around this by wrapping the semaphore in a type that does have a default constructor, for which you would use some default count. struct default_binary_semaphore { std::binary_semaphore sem; //Make it public for easy access to the semaphore constexpr default_binary_semaphore() : sem (default_value) {} constexpr explicit default_binary_semaphore(auto count) : sem(count) {} }; Note that, while you can allocate arrays of this type, the type is still non-moveable.
73,449,347
73,449,458
Getting the implicitly deleted error when using a struct
I'm getting this error: <source>:48:32: error: use of deleted function 'FPTask_sim::Data_T::Data_T()' 48 | FPTask_sim::Data_T FPTask_sim::_data; | ^~~~~ <source>:40:9: note: 'FPTask_sim::Data_T::Data_T()' is implicitly deleted because the default definition would be ill-formed: 40 | } Data_T; | ^~~~~~ You can recreate the error using stripped version of my code: (NOTE: comment the "#define BREAK_EVERYTHING" and the code will compile) #define BREAK_EVERYTHING namespace tinyfsm { struct Event {}; } namespace EventConsts { struct EventCode_T {}; struct Event_T {}; struct EventStruct_T : tinyfsm::Event { #ifdef BREAK_EVERYTHING EventStruct_T(const Event_T& Event); #else struct Event { }; #endif }; } class FPTask_sim { public: FPTask_sim(); typedef struct { tinyfsm::Event ARG_react_01_unused_arg01; EventConsts::EventStruct_T ARG_react_02_unused_arg01; // These lines seem to be causing the issue EventConsts::EventStruct_T ARG_dispatch_e; // These lines seem to be causing the issue } Data_T; static Data_T _data; static Data_T _call_data; }; FPTask_sim::Data_T FPTask_sim::_data; int main() { bool exampleVariable; } I'm thinking this is being caused by the EventStruct_T(const Event_T& Event); line, specifically because its being passed by reference and the overall object "_data" is static. Not sure how to fix this though. Thanks! EDITS: Sorry, forgot to include the constructor that is in it already. It looks like it just copies the Event_T obj to EventStruct_T. If Im understanding what you are saying, I need to either give values when declaring the object or add in the blank default constructor. Right? #define BREAK_EVERYTHING namespace tinyfsm { struct Event {}; } namespace EventConsts { struct Event_T {bool a;}; struct EventStruct_T : tinyfsm::Event { bool a; #ifdef BREAK_EVERYTHING //EventStruct_T(){} // New default constructor? EventStruct_T() = default; // Answer provided by user17732522 EventStruct_T(const Event_T& Event); #else struct Event { }; #endif }; } class FPTask_sim { public: FPTask_sim(); typedef struct { tinyfsm::Event ARG_react_01_unused_arg01; EventConsts::EventStruct_T ARG_react_02_unused_arg01; // These lines seem to be causing the issue EventConsts::EventStruct_T ARG_dispatch_e; // These lines seem to be causing the issue } Data_T; static Data_T _data; static Data_T _call_data; }; FPTask_sim::Data_T FPTask_sim::_data; int main() { bool exampleVariable; } // Current constructor in separate file EventConsts::EventStruct_T::EventStruct_T(const EventConsts::Event_T& Event) : a(Event.a), {}
If you declare any constructor for a class, then the default constructor (constructor not requiring any argument) will not be declared implicitly. So then there is no constructor to construct e.g. FPTask_sim::_data.ARG_react_02_unused_arg01 when you are trying to initialize it without constructor argument in FPTask_sim::Data_T FPTask_sim::_data;. Either provide arguments to the initializer of FPTask_sim::_data so that FPTask_sim::_data.ARG_react_02_unused_arg01 and the other are given arguments from which they can be constructed, give them default-initializers in the definition of EventStruct_T or define a default constructor for EventStruct_T yourself.
73,449,896
73,496,990
How to improve performance of writing files in UWP
In the following part of my UWP application, I have a performance bottle-neck of creating a lot of large TIFF files. Is there any way to make it run faster without too many conversions and data copies? Due to platform restrictions, I am not allowed to use fopen (access denied). std::ostringstream output_TIFF_stream; TIFF* ofo = TIFFStreamOpen("MemTIFF", &output_TIFF_stream); ... TIFFWriteRawStrip(ofo, 0, currentFrame->image, bufferSize); TIFFClose(ofo); auto str = output_TIFF_stream.str(); auto size = str.length(); unsigned char* chars = (unsigned char*)str.c_str(); auto byteArray = ref new Array<unsigned char>(chars, size); DataWriter^ dataWriter = ref new DataWriter(); dataWriter->WriteBytes(byteArray); IBuffer^ buffer = dataWriter->DetachBuffer(); create_task(_destinationFolder->CreateFileAsync(fileName)) .then([](StorageFile^ file) { return file->OpenTransactedWriteAsync(); }) .then([buffer](StorageStreamTransaction^ transaction) { create_task(transaction->Stream->WriteAsync(buffer)).wait(); return transaction; }) .then([](StorageStreamTransaction^ transaction) { return create_task(transaction->CommitAsync()); }) .wait(); I have tried broadFileSystemAccess but it has same problem. fopen still doesn't work.
I haven't found any way to speed up I/O operations in UWP. If you are writing an I/O speed critical application. I recommend using WPF or if you friendly with WRL, then the new Windows APP SDK.
73,450,877
73,450,928
Getting error when overloading << operator
I have a Class called "Vector". It consists of two private fields: std::vector<double> coordinates and int len. Methoddim() returns len. I am overloading operator << like that: friend std::ostream& operator<<(std::ostream& os, Vector& vec ) { std:: cout << "("; for ( int i = 0; i < vec.dim(); i++ ) { if ( i != vec.dim()-1){ os << vec[i] << ", "; } else { os << vec[i]; } } os << ')'; return os; } An operator + like that: friend Vector operator +(Vector& first, Vector& second) { if(first.dim() != second.dim()){ throw std::length_error{"Vectors must be the same size"}; }else { Vector localVec(first.dim()); // same as {0,0,0...,0} - first.dim() times for (int i = 0; i < first.dim(); i++){ localVec[i] = first[i] + second[i]; } return localVec; } } And operator [] like that: double& operator[](int index) { return this->coordinates[index]; } And here's the problem: Vector x{1,2,4}; Vector y{1,2,3}; Vector z = x + y; std:: cout << z; // it works perfectly fine - (2, 4, 7) std:: cout << x + y; // it gives me an error could not match 'unique_ptr<type-parameter-0-2, type-parameter-0-3>' against 'Vector' operator<<(basic_ostream<_CharT, _Traits>& __os, unique_ptr<_Yp, _Dp> const& __p) It seems to me that this error is related to parameter Vector& vec , but I don't know whether it's right and what should I do to fix it. If anyone could give me a hint (or tell me what I should read more about) - I would be very grateful. Here's full code: class Vector { private: std::vector <double> coordinates; int len; public: Vector(): len{0}, coordinates{} {}; Vector(std::initializer_list <double> coordinates_): len{static_cast <int>( coordinates_.size())}, coordinates{coordinates_} {} Vector(int len) : len{len} { for(int i = 0; i < len; i++){ coordinates.push_back(0); } } int dim() const { return this->len; } double& operator[](int index) { return this->coordinates[index]; } friend std::ostream& operator<<(std::ostream& os, Vector& vec ) { std:: cout << "("; for ( int i = 0; i < vec.dim(); i++ ) { if ( i != vec.dim()-1){ os << vec[i] << ", "; } else { os << vec[i]; } } os << ')'; return os; } friend Vector operator +(Vector& first, Vector& second) { if(first.dim() != second.dim()){ throw std::length_error{"Vectors must be the same size"}; }else { Vector localVec(first.dim()); for (int i = 0; i < first.dim(); i++){ localVec[i] = first[i] + second[i]; } return localVec; } } };
A temporary cannot bind to a non-const reference argument. You are missing const in at least two places. Most importantly here: friend std::ostream& operator<<(std::ostream& os, const Vector& vec ) // ^^ And there should a const overload of operator[]
73,451,202
73,452,198
Not able to send a JSON request using libcurl in C++
I am trying to access a GraphQL server with C++ and I am using the libcurl library to make the HTTP Post request. I got started with libcurl after reading the docs and I was testing the requests that were created using a test endpoint at hookbin.com Here is the sample code: int main(int argc, char* argv[]) { CURL* handle = curl_easy_init(); curl_easy_setopt(handle, CURLOPT_URL, "https://hookb.in/YVk7VyoEyesQjy0QmdDl"); struct curl_slist* headers = NULL; headers = curl_slist_append(headers, "Accept: application/json"); headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, "charset: utf-8"); curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers); string data = "{\"hi\" : \"there\"}"; cout << data << endl; curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data); CURLcode success = curl_easy_perform(handle); return 0; } When I send this post request I expect the request body to be the json {"hi": "there"} but I get some weird nonsense in the body. Here is what the request body looks like: Why is this happening? How do I fix this?
curl_easy_setopt is a C function and can't deal with std::string data and CURLOPT_POSTFIELDS expects char* postdata. Call std::string::c_str() for getting char*. curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data.c_str());
73,452,194
73,701,494
VCPKG + CMAKE not finding compatible version with requested version ""
I am trying to use VCPKG and CMAKE on a cpp project and am using the CPR library. I have been struggling to figure out what could be the cause of this error, re ran the get-started guide and other tutorials / blogs that are using cpr with vcpkg and is running fine with almost the exact same cmake config. What am I doing wrong? I have ran the follow commands vcpkg install vcpkg integrate install The cmake config I am using cmake_minimum_required(VERSION 3.0.0) project(Testing VERSION 0.1.0) include(CTest) enable_testing() add_executable(Testing main.cpp) set(CPACK_PROJECT_NAME ${PROJECT_NAME}) set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) include(CPack) find_package(cpr CONFIG REQUIRED) target_link_libraries(cpr PRIVATE cpr::cpr) Full error output [proc] Executing command: "C:\Program Files\CMake\bin\cmake.EXE" --no-warn-unused-cli -DCMAKE_TOOLCHAIN_FILE:STRING=C:/tools/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET:STRING=x64-windows -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -Se:/programming/2022/cpp/Testing/cpp-vcpkg-cmake-example -Be:/programming/2022/cpp/Testing/cpp-vcpkg-cmake-example/build -G "Visual Studio 17 2022" -T host=x86 -A win32 [cmake] Not searching for unused variables given on the command line. [cmake] -- Selecting Windows SDK version 10.0.19041.0 to target Windows 10.0.19044. [cmake] CMake Error at C:/tools/vcpkg/scripts/buildsystems/vcpkg.cmake:826 (_find_package): [cmake] Could not find a configuration file for package "cpr" that is compatible [cmake] with requested version "". [cmake] [cmake] The following configuration files were considered but not accepted: [cmake] [cmake] C:/tools/vcpkg/installed/x64-windows/share/cpr/cprConfig.cmake, version: 1.9.0 (64bit) [cmake] [cmake] Call Stack (most recent call first): [cmake] CMakeLists.txt:13 (find_package) [cmake] [cmake] [cmake] -- Configuring incomplete, errors occurred! [cmake] See also "E:/programming/2022/cpp/Testing/cpp-vcpkg-cmake-example/build/CMakeFiles/CMakeOutput.log". I have thought about adding adding specific version cpr to cmake but could not figure out how to do it, but that should not even be the underlying problem in this situation.
-DVCPKG_TARGET_TRIPLET:STRING=x64-windows means x64-windows triplet/libraries will be used (->vcvars64) -G "Visual Studio 17 2022" means VS 2022 will be used (defaults to x64) -T host=x86 means VS2022 x86 host tools will be used -> vcvars(32|x86_<?>)? -A win32 means VS2022 will try to build for x86/win32 (overrides the default of x64). (-> vcvars32) As such VCPKG_TARGET_TRIPLET=x64-windows is incompatible with -A win32. Do either not pass the -A flag to cmake or don't set VCPKG_TARGET_TRIPLET and let the vcpkg toolchain automatically select it. CMake is telling you that the libraries it found (x64) cannot be used for the targeted architecture (x86)
73,452,904
73,453,018
how to convert values of type float and double into binary format and push into vector of type uint8_t?
I want to know how to convert values of float and double into binary format and push into vector of type uint8_t Eg : float x = 23.22; double z = 2.32232; and store them into vector while serializing vector<uint8_t> data. and also convert back into original value while deserializing. Is there any way to do this?
If you just need to push them into vector and pop them (like a stack) you can do this: void push( std::vector<uint8_t> &v, float f ) { auto offs = v.size(); v.resize( offs + sizeof( f ) ); std::memcpy( v.data() + offs, &f, sizeof( f ) ); } float popFloat( std::vector<uint8_t> &v ) { float f = 0; if( v.size() >= sizeof( f ) ) { auto offs = v.size() - sizeof( f ); std::memcpy( &f, v.data() + offs, sizeof( f ) ); v.resize( offs ); } return f; } Note this would store them in not portable format, but should work for storing/reading them to/from file on the same hardware. You may rewrite those 2 functions as template and it will work with all integral and floating point types ( short int long double etc )
73,452,921
73,453,035
I can´t delete a certain node in my linked list
I have the next linked list: #include <iostream> #include <string> #include <cstddef> using namespace std; //Node class class Node { public: string name; string age; Node *next; Node *prev; Node(string name, string age) { this->name = name; this->age = age; this->next = NULL; this->prev = NULL; } }; //Doubly circular Linked list class class List { private: Node *first; Node *last; public: List() { this->first = NULL; this->last = NULL; } void deleteNode(string name) { Node *start = this->first; if (start == NULL) { return; } Node *curr = start, *prev_1 = NULL; while (curr->name != name) { if (curr->next == start) { printf("\nList doesn't have node with value = %d", name); return; } prev_1 = curr; curr = curr->next; } if (curr->next == start && prev_1 == NULL) { (start) = NULL; free(curr); return; } if (curr == start) { prev_1 = (start)->prev; start = (start)->next; prev_1->next = start; (start)->prev = prev_1; free(curr); } else if (curr->next == start) { prev_1->next = start; (start)->prev = prev_1; free(curr); } else { Node *temp = curr->next; prev_1->next = temp; temp->prev = prev_1; free(curr); } } void add(string name, string age) { Node *node = new Node(name, age); if (this->first == NULL) { this->first = node; this->first->next = node; this->first->prev = node; this->last = node; } else { this->last->next = node; node->next = this->first; node->prev = this->last; this->last = node; this->first->prev = this->last; } } void print() { Node *aux; aux = this->first; while (aux != NULL) { cout << aux->name << ", " << aux->age<<endl; aux = aux->next; if (aux == this->first) { break; } } } }; int main(int argc, char const *argv[]) { List list; list.add("David", "25"); list.add("James", "45"); list.add("Charles", "78"); list.add("Katty", "96"); cout<<"List without delete any node"<<endl; list.print(); //trying to delete a certain node list.deleteNode("David"); cout<<"printing list without David because I deleted him above"<<endl; list.print(); return 0; } In my function deleteNode I try to send a name to delete it from the linked list, but when in run my code it doesn't work, it only shows me the next: List without delete any node David, 25 James, 45 Charles, 78 Katty, 96 And my expected output would be: List without delete any node David, 25 James, 45 Charles, 78 Katty, 96 printing list without David because I deleted him above James, 45 Charles, 78 Katty, 96 I don´t know what else to do, I hope you can help me, thanks.
Fors starters, free is the wrong way to free a pointer allocated with new. Use delete instead. Also, it's generally best to pass strings as const references. Your deleteNode function looks really complicated. Let me simplify it for you. Tell me what you think of this: void deleteNode(const string& name) { Node *start = this->first; while ((start != nullptr) && (start->name != name)) { start = start->next; } if (start == nullptr) { return; } Node* prev = start->prev; Node* next = start->next; if (prev != nullptr) { prev->next = next; } else { first = next; } if (next != nullptr) { next->prev = prev; } else { last = prev; } delete start; } Likewise, add can be simplified to just: void add(const string& name, const string& age) { Node *node = new Node(name, age); if (this->last == NULL) // first insert { first = node; last = node; } else { last->next = node; node->prev = last; last = node; } }
73,453,064
73,453,219
C++ Typecast int pointer to void pointer to char pointer?
Hello im confused by typecasting pointers. I understand that void can hold any type. So if i have an int * with a value inside of it then i make a void * to the int * can i then typecast it to a char? It's quite hard to explain what i mean and the title might be wrong but will this work? And is it safe to do this. I've seen it used quite alot in C. Is this bad practise. int main() { int* a = new int{ 65 }; void* v = static_cast<int*>(a); std::cout << *(static_cast<char *>(v)); }
I understand that void can hold any type. You understand it wrong. Pointer does not hold data, it points to it. So integer pointer points to memory with holds integer, float pointer points where float is etc. Void pointer just points to some memory, but it says - I do not know what kind of data is there. Now conversion. Technically you can convert almost any pointer to any (there are exceptions like function pointers or pointers to a member, but they are completely different beasts and it is not what you are asking about) as they all just pointers. But problem happens when you try to access memory where they point to. So if you have int in memory and try to read it as float or vice versa - that's illegal. Now therte is one exception - you can access any data through pointer to char (or unsigned char) as char represents byte. Void pointer is irrelevant here, you can convert from pointer of one type to another without void * involved: int main() { int* a = new int{ 65 }; unsigned char *uptr = reinterpret_cast<unsigned char *>( a ); for( size_t i = 0; i < sizeof(int); ++i ) std::cout << static_cast<unsigned int>( uptr[i] ) << ' '; } Live example Note I casted uptr[i] to unsigned int, that is to print bytes as numbers, as C++ stream ( std::cout in this case) will print character as symbol, which would be meaningless in this case.
73,453,098
73,453,125
How to convert a raw pointer to unique_ptr?
I have this sample code: std::unique_ptr<Base> some_function() { //I cannot use unique ptr here becuase it will get freed when the function return i guess Derived* derived = new Derived; return static_cast<std::unique_ptr<Base>>(derived); } Is using static_cast here is a good solution? Are there other alternatives to return unique_ptr? And return std::unique_ptr<Command>(derived); if I return like this, will the ptr be freed at the end of the return expression since it is anynomous? And what is the workaround if I don't want to use raw pointers in Derived* derived = new Derived;?
I cannot use unique ptr here becuase it will get freed when the function return i guess You can simply return it and the ownership of the raw pointer stored in the smart pointer will be transferred from your local variable to the std::unique_ptr<Base>. std::unique_ptr<Base> some_function() { auto derived = std::make_unique<Derived>(); // use derived in here ... return derived; // and return it by value } Demo
73,453,234
73,453,432
Are function scope static constexpr variable static storage duration
First I'll start by saying the question is maybe wrong, as I am not sure what is the issue with the following code. #include <array> #include <cstdint> #include <iostream> template <typename T> struct PixelRGB { T r {}; T g {}; T b {}; }; using PixelRGBui8 = PixelRGB<uint8_t>; template <typename Pixel_T> class FrameRowView { public: FrameRowView(const uint32_t& width) : m_width { width } { } const uint32_t& m_width; }; double bar(auto& view) { std::array<PixelRGBui8, 128> arrayA = {}; std::cout << "width: " << view.m_width << " " << arrayA.data() << "\n"; return 42.0; } void foo() { static constexpr auto Width = 16; auto frameRowPrev = FrameRowView<PixelRGBui8> { Width }; auto val = bar(frameRowPrev); std::cout << "frameRowPrev: " << frameRowPrev.m_width << "\n"; } int main([[maybe_unused]] int argc, [[maybe_unused]] char* argv[]) { foo(); return EXIT_SUCCESS; } and on compiler explorer Now the expected output is width: 16. Clang in -O0 and -O3 output the right answer but in -O0 ASAN gives me an error about stack-use-after-scope. ==1==ERROR: AddressSanitizer: stack-use-after-scope on address 0x7fe67e200040 at pc 0x55c0732b8ac1 bp 0x7fff5d95d590 sp 0x7fff5d95d588 READ of size 4 at 0x7fe67e200040 thread T0 #0 0x55c0732b8ac0 in double bar<FrameRowView<PixelRGB<unsigned char>>>(FrameRowView<PixelRGB<unsigned char>>&) /app/example.cpp:27:34 #1 0x55c0732b8621 in foo() /app/example.cpp:36:14 #2 0x55c0732b874a in main /app/example.cpp:43:3 #3 0x7fe6807190b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x240b2) (BuildId: 9fdb74e7b217d06c93172a8243f8547f947ee6d1) #4 0x55c0731e137d in _start (/app/output.s+0x2137d) Address 0x7fe67e200040 is located in stack of thread T0 at offset 64 in frame #0 0x55c0732b84ff in foo() /app/example.cpp:32 This frame has 2 object(s): [32, 40) 'frameRowPrev' (line 35) [64, 68) 'ref.tmp' (line 35) <== Memory access at offset 64 is inside this variable HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork (longjmp and C++ exceptions are supported) MSVC in /O0 output the right answer but in /O2 output garbage. Actually if you play with the size of the array named arrayA in the function bar and set it to 1 the output is actually good. I am tempted to say it is a false positive on ASAN and a bug from MSVC? But it could be my bug too. Does anybody know the answer to this riddle?
Because 16 is int by default in C++ standard, Width is an int variable; then you pass it as a const uint32_t& parameter, so possibly it causes a copy to make a temporary uint32_t variable, and pass it to this const reference. After the function ends, this temporary variable is destructed, so your reference refers to an invalid variable, which causes undefined behavior. See https://godbolt.org/z/GqzvYPW47, and as you make Width a uint32_t or an int variable, it will call different ctor for rvalue and const lvalue differ there. If you make Width a uint32_t variable, it will be definitely right.
73,453,375
73,453,431
Why is there a difference between the following lines of code? (Recursion based question)
Here's the first part: bool coinChangeFn(vector<int>& coins, int amount, int level, int& result) { if (amount < 0) { cout << "Amount is less than 0!" << endl; return false; } if (amount == 0) { cout << "Amount is 0. Level is " << level << endl; result = min(result, level); return true; } bool flag = false; for (auto coin : coins) { cout << "Amount: " << amount << " Level: " << level << " Coin: " << coin << endl; bool temp = coinChangeFn(coins, amount - coin, level + 1, result); // THIS LINE flag = flag || temp; // THIS LINE } return flag; } int coinChange(vector<int>& coins, int amount) { int result{INT_MAX}; return coinChangeFn(coins, amount, 0, result) ? result : -1; } And here's the second version of the code bool coinChangeFn(vector<int>& coins, int amount, int level, int& result) { if (amount < 0) { cout << "Amount is less than 0!" << endl; return false; } if (amount == 0) { cout << "Amount is 0. Level is " << level << endl; result = min(result, level); return true; } bool flag = false; for (auto coin : coins) { cout << "Amount: " << amount << " Level: " << level << " Coin: " << coin << endl; flag = flag || coinChangeFn(coins, amount - coin, level + 1, result); // THIS LINE } return flag; } int coinChange(vector<int>& coins, int amount) { int result{INT_MAX}; return coinChangeFn(coins, amount, 0, result) ? result : -1; } I've marked the code under question as "THIS LINE" in the comments. I expected them to have the same behavior, however the first version stopped the recursion earlier than expected.
You’re seeing the effect of short-circuit evaluation. In C++, since true || anything is true, if the first operand to || is true, then the second argument isn’t evaluated. Therefore, if you write flag = flag || /* recursive call */; and flag is already true, then no call will be made. On the other hand, the bitwise OR operator | doesn’t short-circuit. Therefore, if you write flag |= /* recursive call */; then the call will always be made.
73,453,622
73,454,047
Store an lvalue or an rvalue in the same object using variants
I am reading a technique that is used to store an lvalue or an rvalue in the Same Object. Please find the description of this here. The overloaded trick is implemented. However when the overload struct is defined , an addition overload constructor is defined, in which the function pointers that are produced when the lambdas are decayed, are passed as arguments template<typename... Functions> struct overload : Functions... { using Functions::operator()...; overload(Functions... functions) : Functions(functions)... {} }; Why is it needed to explicitly define this constructor? Here a live demo. Analysing the code using the cppinsights the template instantiation for the above piece of code is the following inline overload(__lambda_39_13 __functions0, __lambda_40_13 __functions1, __lambda_41_13 __functions2) : __lambda_39_13(__functions0) , __lambda_40_13(__functions1) , __lambda_41_13(__functions2) { } It is not clear to me how this template instantiation is generated . Using explicitly custom deduction guide does not compile Have a look in the following modified demo The following error is produced :38:9: error: no matching function for call to 'overload&) [with T = ...
You are trying to initialize overload via parenthesized initialization, e.g. here: overload( [](Value<T> const& value) -> T const& { return value.value_; }, [](NonConstReference<T> const& value) -> T const& { return value.value_; }, [](ConstReference<T> const& value) -> T const& { return value.value_; } ) In C++17 parenthesized initialization with two or more arguments always requires a constructor to be available accepting the arguments in the initializer. If you don't declare any constructor in overload then that can't possible work since implicitly declared constructors can only be the default, copy or move constructors, none of which accepts three arguments. You are also not inheriting any constructors from overload's base classes (and even if you were that would not help you). The deduction guide can't change the fact that there is no constructor to choose, no matter how the template arguments are decided. However, if the constructor is not declared, then overload is an aggregate class and you could use aggregate initialization instead of initialization by a constructor. Aggregate initialization will not call any constructor, but instead initializes the base class subobjects (followed by direct member subobjects if there were any) one-by-one in order from the initializers in the initializer list. This requires only that you use braces instead of parentheses in C++17. Aggregate initialization was not considered with parentheses in C++17: overload{ [](Value<T> const& value) -> T const& { return value.value_; }, [](NonConstReference<T> const& value) -> T const& { return value.value_; }, [](ConstReference<T> const& value) -> T const& { return value.value_; } } Unfortunately in C++17 there was no automatic deduction guide for aggregate initialization, so you will have to still add the deduction you suggested in your modified demo. If you were using C++20 (and a compiler fully implementing it), then you would need neither the deduction guide nor the braces to make use of aggregate initialization here, since a sufficient automatic deduction guide for aggregate initialization was introduced and aggregate initialization with parentheses was made possible. The original would just work without having to define the constructor.
73,453,867
73,464,478
Error using large Eigen matrix: " OBJECT_ALLOCATED_ON_STACK_IS_TOO_BIG"
I have been using Eigen matrices to test a new code I wrote, and I just ran into this issue for the first time. I just started reading about "Fixed vs. Dynamic size" in Eigen matrices and I thought I was using "dynamic" matrices for large sizes, but when I try using larger number of grids I get the error: static assertion failed: OBJECT_ALLOCATED_ON_STACK_IS_TOO_BIG Example code: static const int nx = 128; static const int ny = 128; using namespace std; using namespace Eigen; int main(){ Eigen::Matrix<double, (ny+1), nx> X; //ERROR HERE X.setZero(); //other similar initializations } This code is running fine for smaller sizes of nx; ny; but not the case I am showing. Ideally, I would like to run something as large as nx=1024; and ny=1024; Is this not possible using Eigen matrices? Thanks.
As people pointed out in the comments, using the following fixes the issue: Eigen::MatrixXd or Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>
73,454,879
73,454,967
Finding a string inside all subdirectories
I try to code a program that behaves like grep -r function. So far I can list all the subdirectories and folders inside of them recursively but what i need to do is to find a string inside all of these files and record them in a .log file. I am building with CMake on Ubuntu. The program compiles fine but probably I have something wrong with this function.(it basically saves the values found in a log file) It's supposed to put inside the log file the following-> Directory:(line number):(the full line) After the changes, the function works fine, I can see the directories and the line number of the searched word. The problem now is that I cannot see the line in the .log file, it shows in binary and not as a string. Do anyone know the reason ? void showing_all_files(std::string path, std::string search) { std::ofstream log_file; log_file.open("grep_ex.log"); for (const auto & entry : fs::recursive_directory_iterator(path)) { int line_no = 0; string line; ifstream infile(path); while(getline(infile, line)) { ++line_no; auto pos = line.find(search); if(pos != string::npos) { log_file << entry << ":" << line_no << ":" << line << endl; } } // log_file << entry.path() << std::endl; } log_file.close(); }
ifstream infile(path); Should be ifstream infile(entry.path());.
73,455,046
73,480,871
How to set _GLIBCXX_USE_CXX11_ABI=0 in Makefile
In CMakelists.txt we can use add_compile_definitions(_GLIBCXX_USE_CXX11_ABI=0), how can I set _GLIBCXX_USE_CXX11_ABI in makefile?
As @Alan Birtles said, I do it like this : g++ $^ -std=c++14 -D_GLIBCXX_USE_CXX11_ABI=0 $(INCLUDE) $(LIB) -o $@
73,455,453
73,456,884
how to use decltype(*this) in clang
Here is my code. If i don't comment out the // typedef auto getFoo1() -> decltype(*this);,the program works on gcc,but it compiles failed on clang (https://godbolt.org/z/jzs3f6oM7). class Foo { public: // not work on clang but work on gcc // typedef auto getFoo1() -> decltype(*this); auto getFoo2() -> decltype(*this); }; int main() { Foo f; return 0; } The error is <Compilation failed> # For more information see the output window x86-64 clang 14.0.0 - 1232ms Output of x86-64 clang 14.0.0 (Compiler #1) <source>:6:41: error: invalid use of 'this' outside of a non-static member function typedef auto getFoo1() -> decltype(*this); And I want to know, what is the difference between the getFoo1() and the getFoo2()? And if getFoo1() and getFoo2() exists in memory or other place when running?
There are only few places where this is allowed to appear and [expr.prim.this] lists them all, namely it can appear in declarations of member functions, member function templates and default initializers of non-static data members. A typedef declares a type alias, so neither of those above, and therefore this is not allowed to appear in the typedef declaration. GCC is wrong to accept it. This rule also makes sense. this only really makes sense in a non-static member function definition. Its value and also its type depend on that. For example this ought to be const-qualified if and only if the non-static member function is const-qualified. However a typedef of the form typedef auto getFoo1() -> decltype(*this); has nothing to do with member functions. It simply declares a type alias for an ordinary function type that could be used to declare any function, whether member function or not, and potentially in any class. What type should this even have then in this context? Foo*, const Foo*, etc? If you need to just refer to the class type itself, use Foo directly instead of going through decltype(*this).
73,456,694
73,456,775
How to change wstring value in struct?
I don't know how to change wstring value in struct . I don't know where is my error. do you help me ? I can't understand why string value change success, wstring value change failed . struct TestStruct{ string falg1; wstring falg2; TestStruct setFlag1(string str ) { falg1 = str; return *this; } TestStruct setFlag2(wstring str ) { falg2 = str; return *this; } }; int main(int argc, char ** argv) { TestStruct testStruct; testStruct.setFlag1("string") .setFlag2(L"Wstring"); wcout << "string length:" << testStruct.falg1.size() << endl; wcout << "Wstring content:" << '[' << testStruct.falg2 << ']' << endl; wcout << "Wstring length:" << '[' << testStruct.falg2.size() << ']' << endl; } The output content is : string length:6 Wstring content:[] Wstring length:[0]
I am not sure why are you trying to return a copy of your struct, the code looks really weird. I would use a method returning nothing and then setting the flags works as expected: #include <string> #include <iostream> struct TestStruct{ std::string falg1; std::wstring falg2; void setFlag1(std::string str ) { falg1 = str; } void setFlag2(std::wstring str ) { falg2 = str; } }; int main(int argc, char ** argv) { TestStruct testStruct; testStruct.setFlag1("string"); testStruct.setFlag2(L"Wstring"); std::wcout << "string length:" << testStruct.falg1.size() << std::endl; std::wcout << "Wstring content:" << '[' << testStruct.falg2 << ']' << std::endl; std::wcout << "Wstring length:" << '[' << testStruct.falg2.size() << ']' << std::endl; } Output: string length:6 Wstring content:[Wstring] Wstring length:[7] As @Acanogua and @UnholySheep pointed out, it is also possible to return references and then chain the function calls as you tried in your example: struct TestStruct{ std::string falg1; std::wstring falg2; TestStruct& setFlag1(std::string str ) { falg1 = str; return *this; } TestStruct& setFlag2(std::wstring str ) { falg2 = str; return *this; } }; int main(int argc, char ** argv) { TestStruct testStruct; testStruct.setFlag1("string").setFlag2(L"Wstring"); std::wcout << "string length:" << testStruct.falg1.size() << std::endl; std::wcout << "Wstring content:" << '[' << testStruct.falg2 << ']' << std::endl; std::wcout << "Wstring length:" << '[' << testStruct.falg2.size() << ']' << std::endl; }
73,457,393
73,457,591
enum in struct by c++
I have segment of code which from C by compiling in C++. But it fail. Does anyone know to modify? /* types of expressions */ typedef enum { JAM_ILLEGAL_EXPR_TYPE = 0, JAM_INTEGER_EXPR, JAM_BOOLEAN_EXPR, JAM_INT_OR_BOOL_EXPR, JAM_ARRAY_REFERENCE, JAM_EXPR_MAX } JAME_EXPRESSION_TYPE; enum OPERATOR_TYPE { ADD = 0, SUB, UMINUS, MULT, DIV, MOD, NOT, AND, OR, BITWISE_NOT, BITWISE_AND, BITWISE_OR, BITWISE_XOR, LEFT_SHIFT, RIGHT_SHIFT, DOT_DOT, EQUALITY, INEQUALITY, GREATER_THAN, LESS_THAN, GREATER_OR_EQUAL, LESS_OR_EQUAL, ABS, INT, LOG2, SQRT, CIEL, FLOOR, ARRAY, POUND, DOLLAR, ARRAY_RANGE, ARRAY_ALL }; typedef enum OPERATOR_TYPE OPERATOR_TYPE; typedef struct EXP_STACK { OPERATOR_TYPE child_otype; JAME_EXPRESSION_TYPE type; long val; long loper; /* left and right operands for DIV */ long roper; /* we save it for CEIL/FLOOR's use */ } EXPN_STACK; #define YYSTYPE EXPN_STACK /* must be a #define for yacc */ YYSTYPE jam_null_expression = {0,0,0,0,0};//line 221 I got message: "[Error] JAMEXP.C@221,31: invalid conversion from 'int' to 'OPERATOR_TYPE' [-fpermissive]\r\n" "[Error] JAMEXP.C@221,33: invalid conversion from 'int' to 'JAME_EXPRESSION_TYPE' [-fpermissive]\r\n"
C++ does not allow implicit conversion from int to enum. You can use static_cast. However, anyhow it would be better to spell it out explicitly, then there is no need for the cast: YYSTYPE jam_null_expression = {ADD ,JAM_ILLEGAL_EXPR_TYPE ,0,0,0}; Note that in C++ there is no need for the typedefs and that there are scoped enums, which are even more restrictive and for that reason considered more safe to use.
73,457,572
73,457,629
Why does capturing by value in lambda work although object is deleted?
Why does this code work? // Online C compiler to run C program online #include <cstdio> #include <vector> #include <functional> #include <memory> #include <iostream> using FilterContainer = std::vector<std::function<bool(int)>>; FilterContainer filters; class Widget { public: int divisor = 0; void addFilter() const; Widget(int a):divisor(a){} }; void Widget::addFilter() const { auto divisorCopy = divisor; filters.emplace_back( [=](int value) { return value % divisorCopy == 0; } ); } void doSomeWork() { auto pw = std::make_unique<Widget>(5); pw->addFilter(); } int main() { doSomeWork(); std::cout<< filters[0](10); return 0; } The object widget is deleted after doSomeWork(), so why is divisor still copied succesfully in divisorCopy? When the function in filters is executed, divisor should be non-existent.
You don't capture the Widget object, you capture the local variable divisorCopy by value. This of course creates a copy of the divisorCopy value, stored internally in the lambda object. This lambda-local copy is separate and distinct from the original divisorCopy variable. When addFilter function returns, the lambda-local copy still lives on and can be used. The destruction of the Widget object isn't related to what happens.
73,457,833
73,457,904
Cant put a number into 2d array idk why
ok so im trying to print all characters in a computer. I did a nested loop to put all numbers into the 2d array and print them. int count = 0; char counte[4][5] = {{' ',' ',' ',' ',' '}, {' ',' ',' ',' ',' '}, {' ',' ',' ',' ',' '}, {' ',' ',' ',' ',' '}}; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { count++; char thing =static_cast<char>(count); counte[i][j] = thing; } } for (int i = 0; i < 4; i++) { cout << "\n"; for (int j = 0; j < 5; j++) { cout << counte[i][j]; } } The problem is, when i try to print them it shows whitespaces!!!111! pls help i think the bug is in the first nested loop :c.
The characters you are trying to print aren't visible characters. You can check what visible ones (starting from 33) at ASCII table
73,457,913
73,457,981
C++ 11 conditional template alias to function
In C++ 11, I want to make a template alias with two specializations that resolve to a different function each. void functionA(); void functionB(); template<typename T = char> using Loc_snprintf = functionA; template<> using Loc_snprintf<wchar_t> = functionB; So I can call e.g. Loc_snprintf<>() and it's resolve to functionA(). Apparently seems impossible (to compile). Is there something ultimately simple that mimics it (maybe using a class template)?
In C++11 it's not really possible to create aliases of specializations. You must create actual specializations: template<typename T = char> void Loc_snprintf() { functionA(); } template<> void Loc_snprintf<wchar_t>() { functionB(); } With C++14 it would be possible to use variable templates to create a kind of alias.
73,458,049
73,458,564
How can I pass a function as an optional parameter in C++?
I have two functions that are quite similar, so I'm trying reduce the code duplication. I thought I can create a new function MyFunction() that be called both with or without a func that can be optionally applied to the arguments. So the default for func should be a function that just returns i. I'm not sure if my code is correct and also couldn't find out how to define a default function. I have something like this (comment out MyFunction to run the code) #include <vector> #include <string> #include <algorithm> #include <cctype> #include <iomanip> #include <iostream> int somefunc(int b, int i){ return i-b; // simplified } std::vector<int> MyOldFunction1(const int a, std::vector<int> list) { std::transform(list.begin(), list.end(), list.begin(), [a](int i) -> int {return a*i;}); return list; } std::vector<int> MyOldFunction2(const int a, std::vector<int> list, const int b) { std::transform(list.begin(), list.end(), list.begin(), [a,b](int i) -> int {return a*somefunc(b,i);}); return list; } // Suggested combination (not working) std::vector<int> MyFunction(const int a, std::vector<int> list, std::function<int,int> &f, const int b) { std::transform(list.begin(), list.end(), list.begin(), [a,b](int i) -> int {return a*f(b,i);}); return list; } void PrintVector(std::vector<int> a) { for(auto i=a.begin(); i!=a.end(); ++i){ std::cout<<(*i); } std::cout<<std::endl; } int main () { int p[] = {1, 2, 3, 4, 5}; std::vector<int> a(p, p+5); PrintVector(MyOldFunction1(1,a)); // 1,2,3,4,5 PrintVector(MyOldFunction2(1,a,1)); // 0,1,2,3,4 } Is there a more efficient/clean way to do this? Any advice is appreciated!
You can have a default parameter of type std::function<int(int)>, e.g. std::vector<int> MyFunction(const int a, std::vector<int> list, std::function<int(int)> func = [](int i) -> int { return i; }) { std::transform(list.begin(), list.end(), list.begin(), [a, func](int i) -> int { return a*func(i); }); return list; } You can then pass a lambda that calls somefunc with your b, e.g. [b = 2](int i) -> int { return somefunc(b, i); } See it on coliru Aside: You need to drop the const from the parameter list if you intend to modify it in the body. Further aside: With C++20 you can template this and still communicate that func must accept an int and return an int: template<typename Func = decltype([](int i) -> int { return i; })> requires(std::is_invocable_r_v<int, Func, int>) std::vector<int> MyFunction(const int a, std::vector<int> list, Func func = {}) { std::transform(list.begin(), list.end(), list.begin(), [a, func](int i) -> int { return a*func(i); }); return list; }
73,458,592
73,472,114
C++ ffmpeg encoded audio is distorted
I've made a demuxer/muxer program that takes a video as an input, takes audio and video, then just encodes that red information. So far the video is working fine but the audio is faulty. I can hear the original audio of the input in the background but there is a distorted static sound on the front. I'm setting the AVFrame I got from the demuxer and some information about AVCodecContext in the encoder. The rest is some what similar to ffmpegs muxing example Here is what I've done so far: int video_encoder::write_audio_frame(AVFormatContext *oc, OutputStream *ost) { AVCodecContext *c; AVFrame *frame; int ret; int dst_nb_samples; c = ost->enc; #if __AUDIO_ENABLED c->bit_rate = input_sample_fmt.bit_rate; c->sample_rate = input_sample_fmt.sample_rate; c->time_base = input_sample_fmt.time_base; c->sample_fmt = input_sample_fmt.sample_fmt; c->channel_layout = input_sample_fmt.channel_layout; //c-> = input_sample_fmt.channel_layout #endif frame = get_audio_frame(ost); if (frame) { /* convert samples from native format to destination codec format, using the resampler */ /* compute destination number of samples */ dst_nb_samples = av_rescale_rnd(swr_get_delay(ost->swr_ctx, c->sample_rate) + frame->nb_samples, c->sample_rate, c->sample_rate, AV_ROUND_UP); //av_assert0(dst_nb_samples == frame->nb_samples); /* when we pass a frame to the encoder, it may keep a reference to it * internally; * make sure we do not overwrite it here */ ret = av_frame_make_writable(ost->frame); if (ret < 0) exit(1); /* convert to destination format */ ret = swr_convert(ost->swr_ctx, ost->frame->data, dst_nb_samples, (const uint8_t **)frame->data, frame->nb_samples); if (ret < 0) { fprintf(stderr, "Error while converting\n"); exit(1); } frame = ost->frame; frame->pts = av_rescale_q(ost->samples_count, (AVRational){1, c->sample_rate}, c->time_base); ost->samples_count += dst_nb_samples; } return write_frame(oc, c, ost->st, frame, ost->tmp_pkt); } void video_encoder::set_audio_frame(AVFrame* audio, AVCodecContext* c_ctx) { audio_data = *audio; input_sample_fmt = *c_ctx; //std::cout << audio-> << std::endl; } AVFrame* video_encoder::get_audio_frame(OutputStream *ost) { AVFrame *frame = &audio_data; int j, i, v; int16_t *q = (int16_t*)frame->data[0]; //(int16_t)*audio_frame->data[0]; /* check if we want to generate more frames */ if (av_compare_ts(ost->next_pts, ost->enc->time_base, STREAM_DURATION, (AVRational){ 1, 1 }) > 0) return NULL; for (j = 0; j <frame->nb_samples; j++) { #if !__AUDIO_ENABLED v = (int)(sin(ost->t) * 10000); #endif for (i = 0; i < ost->enc->channels; i++) #if !__AUDIO_ENABLED *q++ = v; #endif ost->t += ost->tincr; ost->tincr += ost->tincr2; } frame->pts = ost->next_pts; ost->next_pts += frame->nb_samples; #if __AUDIO_ENABLED return frame; #else return frame; #endif }
You should match input and output sample rates. Your output buffer is allocated regarding your output audio specifications. However, as they are different than your input audio specifications; either it is underflowing and unable to fill your buffer in a input compatible way, or overflowing. The latter one is unlikely, as you mentioned that you hear the audio but in a distorde way.
73,458,763
73,458,946
type deduction guide on variadic template function
I found some solutions for type deduction guides for variadic classes but not for functions like I intent to use. First, this works as expected: template<typename... T> void print(T&&... args) { ((std::cout << args),...); } int main() { print("Hello ", "World! ", "The answer is ", 42); } gives: Hello World! The answer is 42 As 2nd, I want to constraint the template argument count using C++20 concept as: constexpr auto MAX_ARGS = 4; template<typename... T> concept ArgsT = requires(T... args) { // count must be even requires (sizeof...(T)) % 2 == 0; // the count is limited by arg count size requires (sizeof...(T)) / (2*MAX_ARGS+1) == 0; }; template<ArgsT... T> void print(T&&... args) { ((std::cout << args),...); } and the problem starts with constraints not satisfied ... So, next a type deduction guide shall help here, and here I am: template<ArgsT... T> void print(T&&... args) { ((std::cout << args),...); } template<typename... T> auto print(T&&... args) -> template<typename T> auto print<T...>(T&&...); int main() { print("Hello ", "World! ", "The answer is ", 42); } gives error error: expected a type, see godbolt.org Clang gives some hints, but finally I wasn't able to write the deduction guide with this. How does it look so that the constraint function print(...) compiles, or even rejects due to violated concepts? It must compile on the Big 3 compiler.
template<ArgsT... T> is incorrect, ArgsT only applies to a single type, that is, it only checks whether ArgsT<T> is satisfied, so it will never be satisfied. You should use requires-clause for this template<class... T> requires (sizeof...(T) % 2 == 0) && ((sizeof...(T)) / (2*MAX_ARGS+1) == 0) void print(T&&... args) { ((std::cout << args),...); }
73,458,805
73,458,876
How can I append int variable to string to print path of my DFS algorithm?
I am trying to print the path through a graph made by my DFS algorithm. I am having errors which I do not understand. void GraphTraversal::printPath(std::vector<const Node *> &path) { string myPath; for(int i = 0; i<path.size(); i++) { string dfspath = to_string(dfspath[i].getNodeID()); // i get an error here - expression must have class type but it has type "char" std::cout<<dfspath; } paths.insert(myPath); } I have coded my DFS algorithm as such. void GraphTraversal::DFS(set<const Node *> &visited, vector<const Node *> &path, const Node *src, const Node *dst) { visited.insert(src); path.push_back(src); if (src == dst) { printPath(); } for(const auto &e: src->getOutEdges()) { if(!visited.count(e->getDst())){ DFS( visited, path, e->getDst(), dst); } } visited.erase(src); path.pop_back(); } The output I would like from my printPath method is for string singlePath to output "START: 1->2->4->5->END" with the digits being the nodeID.
You declare a string variable named path, but your parameter is already named path. So path[i] actually refers to the string, not to the vector. Also, path[i] is a const Node*, so you must call it's function with : path[i]->getNodeID().
73,458,871
73,562,028
Division using GMP's low-level API
I'm using GMP's low-level interface (mpn_, see https://gmplib.org/manual/Low_002dlevel-Functions) to do some fixed-size 192 bit (three limb) integer calculations. Currently I am trying to divide one random uint192 by another random uint192 and fail to select the right function. There are multiple candidates: mpn_tdiv_qr - Documentation says "most significant limb of the divisor must be non-zero" mpn_divrem - Documentation says "obsolete" mpn_divrem_1 - Takes a single limb as a divisor mpn_divexact_1 - Documentation says "expecting ... to divide exactly" So there is an obsolete function (mpn_divrem), a function that takes small (<= 64bit) divisors only (mpn_divrem_1), one that has undefined behavior with remainders (mpn_divexact_1) and one that takes large (>= 129bit) divisors only (mpn_tdiv_qr). I tried mpn_tdiv_qr since I thought I'm misunderstanding the documentation and because it replaces the obsolete function. But it actually crashes when most significant limb is zero. Did I miss something? How can I divide two random 3-limb-numbers? Or numbers with a divisor of 65..128 non-zero bits (e.g. 0xffffffff'ffffffffffffffff'ffffffffffffffff / 0xff'ffffffffffffffff)?
Ok, solution is simple: Instead of passing the number of allocated limbs to mpn_tdiv_qr pass the number of limbs minus the number of leading zero limbs of the divisor instead. E.g. when using 3 limbs and a concrete divisor has limb[2] == 0, limb[1] != 0 and limb[0] == 0 a 2 is passed for the divisor length. This way it is guaranteed that the most significant limb (in this case [1]) is non-zero.
73,458,902
73,459,071
Class member template function call not being deducted
I am having trouble understanding why the following does not compile. I have the following code like so (some code ommited): Header: template <typename KeyType, typename ElementType> class TUnorderedMap { public: ElementType* Find(const KeyType Key); const ElementType* Find(const KeyType Key) const; }; struct Foo { }; Source file: void Lookup() { TUnorderedMap <Foo*, Foo> NodeToWidgetLookup; Foo TempFoo; const Foo* SelectionTarget = &TempFoo; // Issue here in this call NodeToWidgetLookup.Find(SelectionTarget); // Issue here in this call NodeToWidgetLookup.Find(SelectionTarget); } Error message: What is the issue here? Why is neither of the Find functions accepted?
What is the issue here? Why is neither of the Find functions accepted? With the given instantiation TUnorderedMap <Foo*, Foo> NodeToWidgetLookup; The function Find expects a const pointer Foo *const: const ElementType* Find(Foo* const Key) const; While you are trying to pass a non-const pointer to const argument const Foo*: const Foo* SelectionTarget You can either change the template arguments like this: TUnorderedMap <const Foo*, Foo> NodeToWidgetLookup; Or make your argument point to a non-const instance: Foo* SelectionTarget; If you want to take all pointer overloads, you may want to declare an overload that is a function template itself: template<typename Key> const ElementType* Find(const Key* key) const { static_assert(std::is_same<Key*, KeyType>::value, "The types don't match"); ... } The template ignores cv-qualifiers of the pointed to object of and the (outermost) pointer part of the argument, but it won't be applicable for non-pointer types. Thanks to overload resolution rules you also can mix it with a non-template overload: ElementType* Find(const KeyType Key); const ElementType* Find(const KeyType Key) const; template<typename Key> const ElementType* Find(const Key* key) const; But be advised, that non-template functions in this scenario precede the function template in the overload resolution candidate list.
73,459,254
73,459,373
Why isn't the original value getting incremented twice even though I have two increments
I'm new at programming and can someone explain to me how this code work? #include <iostream> using namespace std; int main () { int a = 3, b = 4; decltype(a) c = a; decltype((b)) d = a; ++c; ++d; cout << c << " " << d << endl; } I'm quite confused how this code run as they give me a result of 4 4, shouldn't be like 5 5? Because it was incremented two times by c and d? I'm getting the hang of decltype but this assignment caught me confused how code works again.
decltype(a) c = a; becomes int c = a; so c is a copy of a with a value of 3. decltype((b)) d = a; becomes int& d = a; because (expr) in a decltype will deduce a reference to the expression type. So we have c as a stand alone variable with a value of 3 and d which refers to a which also has a value of 3. when you increment both c and d both of those 3s becomes 4s and that is why you get 4 4 as the output
73,459,948
73,460,785
C++ vector remove by value gives off an error
I've followed another question to create a template function that removes a member from a vector by value, however when I try to compile it I'm getting this error: /usr/include/c++/11/bits/predefined_ops.h: In instantiation of ‘bool __gnu_cxx::__ops::_Iter_equals_val<_Value>::operator()(_Iterator) [with _Iterator = __gnu_cxx::__normal_iterator<Types::segment*, std::vector<Types::segment> >; _Value = const Types::segment]’: /usr/include/c++/11/bits/stl_algo.h:822:13: required from ‘_ForwardIterator std::__remove_if(_ForwardIterator, _ForwardIterator, _Predicate) [with _ForwardIterator = __gnu_cxx::__normal_iterator<Types::segment*, std::vector<Types::segment> >; _Predicate = __gnu_cxx::__ops::_Iter_equals_val<const Types::segment>]’ /usr/include/c++/11/bits/stl_algo.h:860:30: required from ‘_FIter std::remove(_FIter, _FIter, const _Tp&) [with _FIter = __gnu_cxx::__normal_iterator<Types::segment*, std::vector<Types::segment> >; _Tp = Types::segment]’ /home/turgut/Desktop/CppProjects/videoo-render/src/utils/array_man.h:49:34: required from ‘void Utils::remove_element(std::vector<T>*, seek) [with vector_type = Types::segment; seek = Types::segment]’ /home/turgut/Desktop/CppProjects/videoo-render/src/Application.cpp:184:59: required from here /usr/include/c++/11/bits/predefined_ops.h:270:24: error: no match for ‘operator==’ (operand types are ‘Types::segment’ and ‘const Types::segment’) 270 | { return *__it == _M_value; } Here is what my function looks like: template<typename vector_type, typename seek> void remove_element(std::vector<vector_type>* vector, seek obj) { vector->erase(std::remove(vector->begin(), vector->end(), (seek)obj), vector->end()); } And here is how I use it: for(auto segment: opengl_engine->_textures){ if(must_delete){ Utils::remove_element<Types::segment, Types::segment>(&(opengl_engine->_textures), segment); } }
Here is a toy example that does what you're trying to do. #include <iostream> #include <list> #include <vector> template <typename Container> void remove_all_by_value(Container& c, typename Container::value_type val) { c.erase(std::remove_if(c.begin(), c.end(), [&val](const auto& a) { return a == val; }), c.end()); } template <typename Container> void print_container(const Container& c) { for (const auto& i : c) { std::cout << i << ' '; } std::cout << '\n'; } int main() { std::vector<int> one{1, 2, 3, 2, 4, 2, 5}; print_container(one); remove_all_by_value(one, 2); print_container(one); std::cout << '\n'; std::list<int> two{1, 2, 3, 2, 4, 2, 5}; print_container(two); remove_all_by_value(two, 2); print_container(two); } std::remove_if will remove all objects that match the criteria in the provided lambda. This removes the need to have a loop at all. I haven't been bothered to install a C++20 compiler yet, so it's very likely that there exists a more elegant version that utilizes concepts and ranges.
73,460,136
73,460,468
What STL function can I use to replace "while (var != nullptr)" loop?
In book C++ Core Guidelines Explained: Best Practices for Modern C++ there is a quote: There is a proverb in modern C++: “When you use explicit loops, you don’t know the algorithms of the STL.” I am writing a program at the moment, which uses an explicit for loop, that changes an object pointed to by a variable in each iteration, until it points to nullptr. for(auto object = get_object(arg);object != nullptr;object = get_object_next(arg)) { if (condition) { vector_of_objects.push_back(object); } } What STL function would be better suited for this than an explicit for loop?
Algorithms are ultimately built on iterators. Your loop is not. Therefore, there is no algorithm to fit it. Now, if you're using this particular get_object/get_object_next interface frequently, it might be worthwhile to develop an iterator/range version of it. Presumably this would be some form of InputIterator/Range. The iterator would store the arg and a current object. ++ would replace the current object with get_object_next(arg). It's a pretty simple interface, and the C++20 concepts system makes writing conforming iterators easier than ever (at the very least, it's easy to check to see if it is a valid std::input_iterator). But if you only have a couple of places that use these loops, it's probably not worthwhile. Of course, "couple of places" and "used frequently" are states that can change over time. So it may be worthwhile to provide a range/iterator interface if you think it might be frequently used.
73,461,218
73,461,279
Can you write OpenGL shader in different file and later link it to the program?
Can you write OpenGL shader in a different file and later link it to the program? and if it's possible how? writing OpenGL shader in string makes my code messy. Here is example code for shaders: const char* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "layout (location = 1) in vec3 aColor;\n" "\n" "out vec3 ourColor;\n" "uniform vec2 angleValues;\n" "\n" "void main()\n" "{\n" "gl_Position = vec4(aPos.x * angleValues.x - aPos.y * angleValues.y, aPos.y * angleValues.x + aPos.x * angleValues.y , aPos.z, 1.0);\n" "ourColor = aColor;\n" "}\n"; const char* fragmentShaderSource = "#version 330 core\n" "out vec4 FragColor;\n" "in vec3 ourColor;\n" "\n" "void main()\n" "{\n" "FragColor = vec4(ourColor, 1.0);\n" "}\n";
Yes, you can have files like my_shader.vs or my_fragment.fs and link them like in this Shader class Just initialize it like this: shader = Shader("./shaders/my_shader.vs", "./shaders/my_fragment.fs");
73,461,523
73,465,007
For a recursive call without a base condition, why does the compiler not show an error during compilation?
I have been programming using the C++ language for quite some time now. I recently came across a situation for which I need help. For a recursive call without a base condition, why does the compiler not show an error during compilation? I, however, receive an error message during runtime. Take the following for an example. Thanks! #include <iostream> #include <climits> int fibonacci(int n){ return fibonacci(n - 1) + fibonacci(n - 2); } int main(){ int ans = fibonacci(6); std::cout << ans << std::endl; }
Modern compilers, in their quest to help you out and generate near-optimal code, will indeed recognize that this function never terminates. However, nothing in the C or C++ language specifications requires that. In contrast to languages like Prolog or Haskell, C/C++ do not guarantee any semantic analysis of your program. A very simple compiler would turn your code int fibonacci(int n){ return fibonacci(n - 1) + fibonacci(n - 2); } into a sequence of low-level instructions equivalent to set a = n - 1 set b = n - 2 put a in the stack position or register for the first int argument call function fibonacci move the return value into temporary x put b in the stack position or register for the first int argument call function fibonacci move the return value into temporary y set z = x + y move z into the stack position or register for the function return value return to caller This is a perfectly legal compilation of your program, and does not require any errors or warnings to be generated. Obviously, during execution, the "move the return value into temporary x" and later instructions (most significantly, the "return to caller") will never be reached. This will generate an infinite recursion loop until the machine stack space is exhausted.
73,461,831
73,461,882
std::map::find does not access operator==
I created a class MyString and overloaded operator==. MyString can be used without any problems class MyString { public: bool operator== (const MyString& obj) const; }; I want to use MyString as key in std::map. std::map<MyString, value> m_xxx; I can access the inserted data by iterating. for (auto& it : m_ini) { MyString first = it.first; for (auto& sit : it.second) { MyString key = sit.first; MyString value = sit.second; int i = 0; } } But when using std::map::find the data I inserted cannot be searched auto& it = m_ini.find(section); if (it == m_ini.end()) I take for granted that std::map::find will do the comparison through my operator==.But in VS debugger std::map::find single step doesn't break down at my operator== . I don't know where the problem is, can anyone help me!
std::map does not use operator==. It is a sorted container and by default operator< is used to compare keys of elements in the map. std::map has 4 template arguments: template< class Key, class T, class Compare = std::less<Key>, class Allocator = std::allocator<std::pair<const Key, T> > > class map The third one can be used to select a different comparator. std::less<Key> uses the keys operator<. Actually a std::map does not care about equality. Two keys a and b are considered equivalent when !(a<b) && !(b<a). Keys are not required to have an operator==.
73,462,506
73,462,677
How to delete specific line from text file c++
This is my text file content. 1 2 3 I want to delete line of this file. #include <iostream> #include <fstream> #include <string> std::fstream file("havai.txt", ios::app | ios::in | ios::out); int main() { std::string line; int number; std::cout << "Enter the number: "; std::cin >> number; while (file.good()) { getline(file, line); if (std::to_string(number) == line) { // how to delete that line of my text file } } return 0; } how to delete that line in if statement?
Removing data from a file is far more complicated than it appears. It is almost always orders of magnitude easier to create a new file and write the information to be kept into it. Open File A for reading. Open File B for writing. For each line in File A: If it's not a line to be discarded, write it to File B. Close File A Close File B Replace File A with File B.
73,462,947
73,463,034
Question about overloaded operator T() in C++ template class
I have this little piece of code: template<typename T> class Test { public: //operator T() const { return toto; } T toto{ nullptr }; }; void function(int* a) {} int main(int argc, char** argv) { Test<int*> a; function(a); return 0; } It doesn't compile unless the line operator T() const { return toto; } is un-commented. This magically works, but I am not sure why (if I un-comment the line). I do understand that if the line is commented, the type of a when passed to function() is incompatible with the expected type int*. So, of course, the compiler complains ... no problem. I also understand that the operator returns the actual type of the object, therefore in this particular case the compiler is happy. I don't understand why the operator is called in this particular case. Is doing function(a) the same thing as doing function(a()), only the () are implicit?
operator T() const { return toto; } is a user defined conversion operator, it is not operator(). It's used to define that your class is convertible to a different type. operator() would look like this instead: void operator()() const { ... } In your case, you are using int* as T. If you substitute it yourself in the operator, you will see that it becomes operator int*() const { return toto; } which means "my class can be converted to an int* and the result of that conversion is evaluated as return toto;". The function function() only accepts an int* as its argument. When you provide a Test instance, the call is only legal if there is a way to convert from Test to int*, which is why the operator T is required for the code to compile.
73,462,991
73,463,083
CMake: Cannot link to a static library in a subdirectory
I have the following folder structure in my c++ project *--build |---(building cmake here) | *--main.cpp | *--CMakeLists.txt (root) | *--modules |---application |------app.h |------app.cpp |------CMakeLists.txt And the code below for both CMakeLists.txt files: CMakeLists.txt (module) cmake_minimum_required(VERSION 3.15.2) file(GLOB APPLICATION_HEADERS *.h *.hpp) file(GLOB APPLICATION_SRC *.c *.cpp) add_library(app_lib STATIC ${APPLICATION_HEADERS} ${APPLICATION_SRC}) target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_LIST_DIR}) CMakeLists.txt (root) cmake_minimum_required(VERSION 3.15.2) project(main) enable_language(C CXX) #set directories set(CMAKE_BINARY_DIR build) set(CMAKE_CONFIGURATION_TYPES UNIX) set(CMAKE_MODULES_DIR ${SOURCE_DIR}/cmake) add_executable(${PROJECT_NAME} main.cpp) # Build sub-modules include_directories(modules/application) add_subdirectory(modules/application) find_library(MY_APP_LIB app_lib REQUIRED) target_link_libraries(${PROJECT_NAME} PUBLIC ${MY_APP_LIB}) However, when I do cmake .. in my build directory, it seems like my app library just doesn't build and it doesn't link to it. I end up with the following error: CMake Error at CMakeLists.txt:80 (find_library): Could not find MY_APP_LIB using the following names: app_lib I tried looking at other stackoverflow questions but it seems like I'm missing something. Any help is appreciated! Thanks!
You don't need to use find_* to locate the library. In fact you cannot locate the library this way, since find_library searches the file system for the library during configuration, i.e. before anything gets compiled. There's good news though: If the targets are created in the same cmake project, you can simply use the name of the cmake target as parameter for target_link_libraries: ... add_library(app_lib STATIC ${APPLICATION_HEADERS} ${APPLICATION_SRC}) # note: this should be a property of the library, not of the target created in the parent dir target_include_directories(app_lib PUBLIC .) ... add_subdirectory(modules/application) target_link_libraries(${PROJECT_NAME} PUBLIC app_lib)
73,463,183
73,463,564
Address Sanitizer Heap buffer Overflow
I was trying to solve this problem on leet code it works fine on my vs code and gcc compiler but i'm getting this Runtime error: Address sanitizer Heap buffer Overflow error message with a long list of address or something on the website. Help me fix it. Here's the code class Solution { public: char nextGreatestLetter(vector<char> v, char a) { int l=v.size()-1; if (v[l] < a) { return v[0]; } int i = 0; while (v[i] <= a) { i++; } return v[i]; } }; p.s the array is sorted in ascending order
This code snippet has a lot of problems: The while loop isn't guaranteed to terminate. If the last character of v is == a, then the first v[l] < a test will be false, but v[i] <= a might be true all the way through the array (it looks like v is meant to be pre-sorted into ascending order), which will have you eventually accessing v[i] for a value of i >= v.size(). That is an illegal/undefined array access and might be the source of the error message you report, if the test platform had strict bounds-checking enabled. The logic of returning v[0] if a is greater than any character in v (again, inferring from the loop that v is supposed to be pre-sorted into ascending order) also seems flawed. Why not return the value of a instead? The caller can easily see that if the return value was <= a, then there clearly was no element of v greater than a. It's almost certainly worth your time to handle cases where the passed-in v array is empty (v.size() == 0) or not actually pre-sorted, i.e. by caching n = v.size() and changing the loop condition to while (i < n && v[i] <= a). Don't let fragile functions creep into your codebase!
73,463,466
73,465,244
How can I force the user of a library template to explicitly tag particular template parameters as acceptable (but only sometimes)?
I have a family of classes in a library that can be "installed" in another class, either as a single member or as an array, dependent on the application. The arrays are indexed with an integer or enum type, dependent on the application (void is used when an array is not meaningful). The installable class itself has no control over the indexing; the application using the class defines the index. However, I imagine that unwanted specialziations could be created by a typo and compile OK. I want to constrain the indexing types to only the ones intended for the application, by making the client signal back to the library which associations are OK. I couldn't see a pure template metaprogramming approach, so I thought I'd exploit ODR and explicit specialization of class members. namespace foo { template <class P, class ROLE> struct association { static_assert(std::is_enum_v<ROLE>||std::is_integral_v<ROLE>); static const bool allowed(); }; template <class T> class bar final { public: bar() = default; ~bar() = default; }; void do_something() {} template <class I, class ROLE> void install(I &&i, ROLE r) { if (association<std::decay_t<I>, ROLE>::allowed()) do_something(); } template <class I> void install(I &&i) { if (association<std::decay_t<I>, void>::allowed()) do_something(); } } With the following sample use: // declare the indexing type enum myindex { min=0, max=3 }; int main() { foo::bar<int> foobar; foo::install(foobar, myindex::min); return 0; } There should be a linker error unless we also add // add a definiton to make the association with myindex OK template <> const bool foo::association<bar<int>, myindex>::allowed() { return true; } In the full code, the value of "allowed" doesn't matter, only the existence of a definition does. It's a pretty cryptic way of saying "this association is OK", but it works. At least, if you fully specialize association. But this is where the "sometimes" comes in: Some of the templates are supposed to work with any indexing type. It's a pain to make the library user write out specializations for these templates. But the following template <class T, class ROLE> const bool foo::association<foo::bar<T>, ROLE>::allowed () { return true; } is a compiler error, because it's not a full specialization. Is there a way to fully define association::allowed() for all combinations of bar specializations with any ROLE, but force the user to define it for other templates? If not, is there a better approach that accomplishes this goal? (Hopefull, something that can be used with static_assert because what I have now is charitably called 'clunky'). Remember, myindex cannot be rolled into the library. (I'm sticking to C++17 for the time being).
This case seems like a good place for template variables. One of their use is to make them a kind of a map - which in this case would greatly increase readability of the client code and move everything to compile-time. If you just want to break compilation the following should be fine: #include <iostream> #include <type_traits> // make_association is a variable template which works as a compile-time map // default value is false_type = no relation template <typename I,typename ROLE> constexpr std::false_type make_association; // isAssociated used as a compile-time "function" template <typename I, typename R> using isAssociated = decltype(make_association<std::decay_t<I>,std::decay_t<R>>); template <typename I, typename ROLE> void install( I &&i, ROLE r) { static_assert(isAssociated<I,ROLE>(), "make_association<I, ROLE> not registered"); static_assert(std::is_enum_v<ROLE> || std::is_integral_v<ROLE> ); std::cout<<"Entered install( I &&, ROLE r)"<<std::endl; } template <typename I> void install( I &&i) { static_assert(isAssociated<I,void>(), "make_association<I, void> not registered"); std::cout<<"Entered install( I &&)"<<std::endl; } enum WrongIndexT { ok = 1}; enum IndexT { min=0, max=3 }; class ObjT final {}; // a class for which any index works template <class T> class Any final {}; template <class T, class Index> constexpr std::true_type make_association<Any<T>, Index>; // here the relations are set using variable template specialization; template<> constexpr std::true_type make_association<ObjT, IndexT>; template<> constexpr std::true_type make_association<ObjT, void>; int main() { ObjT f1,f2,f3; install(f1, IndexT::min); install(f2); install(Any<int>{}, WrongIndexT::ok); // OK install(f1, WrongIndexT::ok); // compilation error return 0; }
73,463,592
73,463,643
what type of data does string.length() return in c++?
I am a beginner in C++. Today, I was trying to solve problem 139 on Leetcode, here is the pseudo-code: for (string& word: wordDict) { int i=0; int word_len = word.length(); cout << i - word.length() << endl; cout << i - word_len << endl; } And here is the result: 18446744073709551611 -5 18446744073709551613 -3 Why does the integer seem out of range if I don't declare the type of word.length() in front?
The type of the member function length is an unsigned integer type named like size_type. As the type is unsigned then the expression i - word.length() also has an unsigned value because the rank of the type size_type (that usually corresponds to the type size_t) is not less than the rank of the type int. You could write for example i - ( int )word.length() to use signed arithmetic.
73,463,784
73,463,888
Remove All Adjacent Duplicates In String in C++: Why is my iterator not entering into the for loop again
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ In this Leetcode question, I tried to do it without using the concept of a stack. But according to the answer, I get the loop is not getting completed, why is that the case here? class Solution { public: string removeDuplicates(string s) { for (int i = 0; i<s.length(); i++) { if(s[i] == s[i+1]){ s.erase(i,2); i=0; } } return s; } }; This is the error I am getting:
Your loop boundary, i < s.length(), is wrong since it'll let s[i + 1] access the string out of bounds*. You need to reset i when a match is found, which you do, but it's followed by i++ directly, so it will never find a match at s[0] == s[1] again. Fixed: string removeDuplicates(string s) { for (unsigned i = 0; i + 1 < s.length();) { // corrected loop bounds if (s[i] == s[i + 1]) { s.erase(i, 2); i = 0; } else ++i; // only add 1 if no match is found } return s; } * The out of bounds access will really access the terminating \0 (since C++11, undefined behavior before that), but it's unnecessary since you can't erase it anyway. A somewhat quicker version would be to not reset i to 0, but to continue searching at the current position. You may also use std::adjacent_find to simplify the algorithm: string removeDuplicates(string s) { for(auto it = s.begin(); (it = std::adjacent_find(it, s.end())) != s.end();) { it = s.erase(it, it + 2); if(it != s.begin()) --it; } return s; }
73,463,785
73,464,253
How to include libs into Qt project?
I'm trying to figure out how to use the winapi SetWindowSubclass On a non-Qt project under MSVC I can use the API by including: #include <commctrl.h> #pragma comment(lib, "Comctl32.lib") I have been trying for hours unsuccessfully to link this lib on my project. I have found these comctl32.lib on my machine: https://i.imgur.com/D5uOCVb.png I tried adding into .pro: LIBS += -comctl32 LIBS += -comctl32.lib => error: unrecognized command-line option '-comctl32' LIBS += comctl32 LIBS += comctl32.lib => error: cannot find comctl32: No such file or directory I copied the one from C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22000.0\um\arm64 and past it on a new folder under C:\Qt\Libs LIBS += C:\Qt\Libs => error: cannot find C:\Qt\Libs: Permission denied LIBS += -L"C:\Qt\Libs" => this didn't throw any of the errors from above, but now I have these compiler error: .pro QT += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets CONFIG += c++17 LIBS += -L"C:\Qt\Libs" #win32:QMAKE_FLAGS += -L"C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22000.0\um\arm64" #win32:LIBS += cm-comctl32.lib SOURCES += \ main.cpp \ mainwindow.cpp HEADERS += \ mainwindow.h FORMS += \ mainwindow.ui # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += target RESOURCES += \ rcdata.qrc .h #include <commctrl.h> #pragma comment(lib, "Comctl32.lib") // <- warning: Unkown pragma ignored .cpp #include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); SetWindowSubclass((HWND)ui->tabWidget->find(0), ButtonProc, 0, (DWORD_PTR)&ui); DWORD err = GetLastError(); } Using Qt Creator 8.0.1 Qt 6.3.1, compiler MinGW 64-bit
It should be LIBS += -lcomctl32 for your compiler instead of the several other options you tried. This related question has additional detail: Adding external library into Qt Creator project
73,464,159
73,464,285
VS debugger - Identify DLL function names from DLL exports (no PDB available)
I have a segfault in a mess of DLLs that I unfortunately cannot acquire .pdb files for. While I have a stack trace, this is unhelpful as I can't pin down exactly where things are going wrong. I am wondering if there's any way to use the DLL to associate sections of the code with specific exported functions, preferably automatically. For instance, it seems to me that I could GetProcAddress on all the exported functions listed in dumpbin /exports problematicDll.dll, and then manually compare the resulting function pointers to the location the code actually jumps to. This would identify (exported) functions in the stack trace. Does any tool like this already exist? Am I missing an important step of the DLL load process that would make this impossible? Thanks!
You can have VS resolve the exports, go into Tools -> Options, then Debugging -> General. Make sure the "Load dll exports (Native only)" item is checked. Note that this will only resolve functions that are actually exported. If the exported function calls some non-exported function in the DLL you won't be getting a name for that function. Also, there are some (rare) ways to generate code at run-time that this also won't resolve, but those shouldn't be exported, at most you would be getting such a function as a function pointer used as a callback.
73,464,269
73,464,387
How can I include a header file in, but the header file I include includes the file I want to include
I can't really describe my problem, so I'll show you here with code what I mean: boxcollider.h #include "sprite.h" class BoxCollider { public: BoxCollider(Sprite sprite); }; sprite.h #include "boxcollider.h" class Sprite { public: BoxCollider coll; }; INCLUDE issue. How can I solve this problem?
You have two issues. One is the circular references between the two classes. The other is just the circular includes. That one is easy. All your includes -- ALL of them -- should guard against multiple includes. You can do this two ways. #ifndef BOXCOLLIDER_H #define BOXCOLLIDER_H // All your stuff #endif // BOXCOLLIDER_H However, all modern C++ compilers I've used support this method: #pragma once As the first line in the file. So just put that line at the top of all your include files. That will resolve the circular includes. It doesn't fix the circular references. You're going to have to use a forward declaration and pass in a reference, pointer, or smart pointer instead of the raw object. class Sprite; class BoxCollider { public: BoxCollider(Sprite & sprite); }; BoxCollider.h should NOT include Sprint.h, but the .CPP file should.
73,465,091
73,471,084
Boost process child with custom environment causes deprecation warning/error
I would like to use Boost::Process::Child to create a process while also supplying an environment variable to that process. While it seems straightforward, I've also got the requirement of compiling with -Wall -Wextra -pedantic -Werror -Wl,--fatal-warnings (Basically, the slightest issue is treated as an error). I'm following the Boost tutorial (https://www.boost.org/doc/libs/1_80_0/doc/html/boost_process/tutorial.html#boost_process.tutorial.env) and the answer in a duplicate question here: Create child process with custom environment using boost for something similar to this: std::string command = "/usr/bin/something"; ipstream pipe_stream; auto env = boost::this_process::environment(); env["SOMETHING"] = "VALUE"; boost::process::child childProc(command, env, std_out > pipe_stream); This works until I add my compiler switches. Now I'm getting an error: /usr/lib/boost/boost/process/env.hpp:309:13: error: implicitly-declared 'boost::process::basic_environment<char>& boost::process::basic_environment<char>::operator=(const boost::process::basic_environment<char>&)' is deprecated [-Werror=deprecated-copy] 309 | env = e; | ~~~~^~~ And some additional notes: /usr/lib/boost/boost/process/detail/posix/environment.hpp:177:30: note: because 'boost::process::basic_environment<char>' has user-provided 'boost::process::detail::posix::basic_environment_impl<Char>& boost::process::detail::posix::basic_environment_impl<Char>::operator=(const boost::process::detail::posix::basic_environment_impl<Char>&) [with Char = char]' 177 | basic_environment_impl & operator=(const basic_environment_impl& rhs) | ^~~~~~~~ /usr/lib/boost/boost/process/env.hpp:309:13: note: synthesized method 'boost::process::basic_environment<char>& boost::process::basic_environment<char>::operator=(const boost::process::basic_environment<char>&)' first required here 309 | env = e; | ~~~~^~~ It seems the boost::process::child constructor uses a now-deprecated basic_environment copy constructor, but the documentation still shows this as the appropriate method. How do I construct a boost::process::child with an environment now without this warning/error?
Like the commenter, I'm unable to reproduce this on my system. So we really need to know more about what tools you use to compile, and what you're compiling (versions). That said, I think the issue can be skirted by making the Boost include a system include, e.g. with -isystem /path/to/boost or add_includes(SYSTEM /path/to/boost) and similar when using CMake.
73,465,491
73,465,921
How to pack all arrays of bytes of data members everything in a single vector?
I have a created a function serialize which takes the Data { a class containing 4 members int32,int64,float,double) as input and returns a encoded vector of bytes of all elements which I will further pass to deserialize function to get the original data back. std::vector<uint8_t> serialize(Data &D) { std::vector<uint8_t> seriliazed_data; std::vector<uint8_t> intwo = encode(D.Int32); // output [32 13 24 0] std::vector<uint8_t> insf = encode(D.Int64); // output [233 244 55 134 255 23 55] // float float ft = D.Float; // float value eg 4.55 float *a; // I will encode them in binary format char result[sizeof(float)]; memcpy(result, &ft, sizeof(ft)); // double double dt = D.Double; // double value eg 4.55 double *c; // I will encode them in binary format char resultdouble[sizeof(double)]; memcpy(resultdouble, &dt, sizeof(dt)); ///// ///// How to bind everything here ///// return seriliazed_data; } Data deserialize(std::vector<uint8_t> &Bytes) /// Vector returned from above function { Data D2; D2.Int64 = decode(Bytes, D2); // D2.Int32 = decode(Bytes, D2); // D2.float = decode(Bytes, D2); // D2.double = decode(Bytes, D2); /// Return original data ( All class members) return D2; } I don't have any idea, of how to move forward.. Q1. If I bind everything in a single vector, how would I dissect them while deserializing. there should be some kind of delimiter? Q2. Is there any better way of doing it.
If I bind everything in a single vector, how would I dissect them while deserializing. there should be some kind of delimiter? In a stream, you either know what type that comes next - or you'll have to have some sort of type indicator in the stream. "Here comes a vector of int with size ..." etc: vector int size elem1 elem2 ... elemX Depending on how many types you need to support, the type information could be 1 or more bytes. If the smallest "unknown" entities are your classes, then you need one indicator per class you aim to support. If you know exactly what should be in the stream, the type information for vector and int could be left out: size elem1 elem2 ... elemX Q2. Is there any better way of doing it. One simplification could be make serialize more generic so you could reuse it. If you have some std::vector<uint8_t> encode(conts T& x) overloads for the fundamental types (and perhaps container types) you'd like to support, you could make it something like this: template <class... Ts> std::vector<uint8_t> serialize(Ts&&... ts) { std::vector<uint8_t> serialized_data; [](auto& data, auto&&... vs) { (data.insert(data.end(), vs.begin(), vs.end()), ...); }(serialized_data, encode(ts)...); return serialized_data; } You could then write serialization for a class simply by calling serialize with all the member variables and you could make serialization of composit types pretty easy: struct Foo { int32_t x; // encode(int32_t) needed std::string y; // encode(const string&) needed std::vector<std::string> z; // encode(const vector<T>&) + encode(const string&) }; std::vector<uint8_t> encode(const Foo& f) { return serialize(f.x, f.y, f.z); } struct Bar { Foo f; // encode(const Foo&) needed std::string s; // encode(const string&) needed }; std::vector<uint8_t> encode(const Bar& b) { return serialize(b.f, b.s); } The above makes encoding of classes pretty straight forward. To add serialization, you could add an adapter which simply references the object to serialize, encodes it and writes the encoded data to an ostream: struct BarSerializer { Bar& b; friend std::ostream& operator<<(std::ostream& os, const BarSerializer& bs) { auto s = encode(bs.b); // encode(const Bar&) needed return os.write(reinterpret_cast<const char*>(s.data()), s.size()); } }; You'd make the deserialize function template and decode overloads in a similar manner.
73,465,892
73,477,095
How to execute a function with parameters just before exiting a code in C++?
I want to trigger a function with parameters just before exiting the program (exit by "return" in the main or by closing the console). My function will print the values of certain variables in a file. Using the function "atexit" not help me because the pointer to the function is without parameters. Thanks P.S. My major problem is when I interrupt the execution of my program by closing the console, I want to get tthe value of some variables at that moment : ostream out("myFile.txt"); int **S; int n; ... void fn(void) { out << "S = " << endl; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { out << S[i][j] << " " << endl; } out << endl; } } ... int main() { atexit(fn); // not working if i interrupt the execution ... // a big loop of code return 0; } I think it will be easy to understand mu issue with this example. Regards
Thanks to all of you, the answer proposed by @JeremyFriesner gives me the right thing to do, my code will be like : #include <iosrteam> #include <Windows.h> ... int **S; int n; ofstream out("MyFile.txt"); BOOL WINAPI ConsoleHandler(DWORD CEvent) { switch (CEvent) { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: case CTRL_CLOSE_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: out << "S = " << endl; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { out << S[i][j] << " " << endl; } out << endl; } } return TRUE; } ... int main() { if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler, TRUE) == FALSE) { cout << "The handler is not going to work." << endl; } ... // a big loop of code return 0; } This will allow me to save my variables to my file just before closing the console. The unique inconvenient is the time we have to save my data is only 5 seconds if we interrupt the console by clicking the "x" and 30 seconds otherwise. I think the 5 seconds will be sufficient for the small data but otherwise, it will be lost. Thanks a lot for everyone try to help me with this issue.
73,466,076
73,466,341
C++ Constrained Variadic Template Parameters
Currently using C++20, GCC 11.1.0. I'm quite new to templates and concepts in general, but I wanted to create a template function with 1 to n number of arguments, constrained by the requirement of being able to be addition assigned += to a std::string. I've been searching for several days now but as you can see I am really struggling here. Attempt 1: template<typename T> concept Stringable = requires (T t) { {std::string += t} -> std::same_as<std::string::operator+=>; }; template <typename Stringable ...Args> void foo(Args&&... args) { // Code... } EDIT: Attempt 2: template<typename T> concept Stringable = requires (std::string str, T t) { str += t; }; template <typename Stringable ...Args> void foo(Args&&... args) { // Code... }
Attempt2 is pretty close, except that the typename keyword needs to be removed since Stringable is not a type but a concept. The correct syntax would be #include <string> template<typename T> concept Stringable = requires (std::string str, T t) { str += t; }; template<Stringable... Args> void foo(Args&&... args) { // Code... }
73,466,485
73,466,840
Why are loads of symbols missing from OpenSSL libs, such as BIO_ctrl?
I'm mystified by why a large subset of symbols is apparently missing from OpenSSL libs I built on Mac. In a CMake-based project, I'm compiling a lib (Restbed) that links statically with OpenSSL (both libssl and libcrypto). The Restbed lib appears to build fine, but if I try to link an application with it, it fails with lots of errors like: Undefined symbols for architecture arm64: "_BIO_ctrl", referenced from: asio::ssl::detail::engine::map_error_code(std::__1::error_code&) const in librestbed.a(service_impl.cpp.o) asio::ssl::detail::engine::map_error_code(std::__1::error_code&) const in librestbed.a(socket_impl.cpp.o) "_BIO_ctrl_pending", referenced from: asio::ssl::detail::engine::perform(int (asio::ssl::detail::engine::*)(void*, unsigned long), void*, unsigned long, std::__1::error_code&, unsigned long*) in librestbed.a(service_impl.cpp.o) The architecture isn't the problem; everything is built on M1 Mac. To sum up, step 1 was build the static Restbed lib: librestbed.a libssl.a libcrypto.a All the output from that is here. Then I tried to compile an app, linking statically with Restbed: app librestbed.a Here's the build command for the app, which triggers the errors: /usr/bin/clang++ -g -arch arm64 -arch x86_64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/Series2Server.dir/main.cpp.o -o Series2Server -L/Users/me/data/series2server/restbed/library -Wl,-rpath,/Users/me/data/series2server/restbed/library -lrestbed -pthread libssl and libcrypto are built from source using the configure tool provided in the OpenSSL source tree. So I examined both libssl and libcrypto with nm -u, to see if the complained-about symbols were in there. Well, they aren't. Such symbols as BIO_ctrl are listed as undefined in both libssl and libcrypto. I don't know what this means. How are symbols known about by nm, and yet "undefined" in the file under inspection? More importantly, how do I fix this problem so the application will build?
When you build a static lib, it does not involving linking at all -- you just run a tool (ar or libtool or some such) that collects the compiled object files into a static library and does not link any of them. This means that when you link with a static library, you also need to link with any other libraries (static or dynamic) that it depends on.
73,466,665
73,466,839
How do I determine from the documentation what type of exception a function can throw?
I am new to C++ programming but have programmed in higher-level languages to find my way around most documentation. I'm learning about exception handling in C++, specifically with this example: vector<int> myNums; try { myNums.resize(myNums.max_size() + 1); } catch (const bad_alloc& err) { cout << err.what() << endl; } This code doesn't catch the exception because the exception thrown by the .resize() method isn't bad_alloc; it's a length_error. So, from this documentation, how do you get to that? Maybe I missed something obvious. https://cplusplus.com/reference/vector/vector/resize/ The only specific exception mentioned in there is bad_alloc. Can someone walk me through how you'd get to know that length_error is the right exception starting from that page?
This is not uncommon. The complexity of the language has increased so much over the years, accumulating multiple revisions to the C++ standard, that even the C++ standard itself can be at odds with itself, sometimes. Let's just see what the C++ standard itself says about two versions of the overloaded resize() vector method. I happen to have a copy of N4860 handy which is, basically, the C++20 version, and while looking up what the C++ standard itself says about resize()'s exceptions, I found that the two resize() overloads define their exception behavior as follows: constexpr void resize(size_type sz); // ... Remarks: If an exception is thrown other than by the move constructor of a non-Cpp17CopyInsertable T there are no effects. // ... constexpr void resize(size_type sz, const T& c); // ... Remarks: If an exception is thrown there are no effects. That's the only mention of exceptions in resize(). I found nothing on a more general in vector itself, nor in "Container Requirements", there was some discussion of exception guarantees but none pertaining to the specific details of vector's resize() or reserve(). This is an obvious oversight. It's fairly obvious that when it comes to exceptions that might be generated as a result of reallocations, both overloads should have the same exception behavior. The first overload's description is lifted straight from reserve() that just precedes it. It goes without saying that resize() uses reserve() to grow the vector's capacity, when needed, and inherits its exception guarantees/behavior. But the same thing must be true with the 2nd resize() overload. The only difference between them is that one default-constructs new values when the vector grows and the other one copy-constructs. But in terms of exception behavior during reallocation they must be identical. The total overall difference, related to exceptions, between the two overloads is due to any exception differences between the value's default constructor and/or its copy/move constructors. My question is, from looking at this documentation, how do you get to that? > Maybe I missed something obvious. No, you did not miss anything. The C++ standard itself has some gaps; not to mention 2nd-hand sources of documentation like the one you're looking at. You get where you want to go by studying everything about the class, template, or algorithm in question, understanding how it must work -- i.e. the resize()s inheriting certain parts of their behavior from reserve() -- and then drawing the inescapable inferences. TLDR: it is what it is.
73,466,716
73,467,143
Heap-buffer overflow when implementing two-pointer approch
I'm solving this brain teaser Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. The tests are generated such that there is exactly one solution. You may not use the same element twice. Your solution must use only constant extra space. Example 1: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. and my solution is giving this error: ================================================================= ==31==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000620 at pc 0x000000345e97 bp 0x7ffcd6847990 sp 0x7ffcd6847988 READ of size 4 at 0x602000000620 thread T0 #2 0x7f2c3b9790b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2) 0x602000000620 is located 0 bytes to the right of 16-byte region [0x602000000610,0x602000000620) I did some research and saw that this is usually caused by calling an index that's too far (i.e. outside the range of the data structure you're using) but since I'm using vectors I don't get why I have this error. It happened on the following test case: [5,25,75] 100. class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { // can have an i that points forward and a j that loops through everything until sum // is greater // checking recursively // if sum greater stop checking (as list is increasing) // can reset i each time?? // add 1 at the end vector<int> indices; int i = 0; int j = 0; // for loop on top? for (int i; i < numbers.size(); i++) int j = 0; while (numbers[i] + numbers[j] <= target) { if (numbers[i] + numbers[j] == target && i != j) { // some if determining if i or j is greater // to determine the order in which to push back indices.push_back(i+1); indices.push_back(j+1); return indices; } else { j++; } } return indices; } }; The other tests are passing but this one is failing. I am trying to use a two-pointer approach here.
There are several issues with this code, some simple syntactic mistakes, some algorithmic problems. First, as others have mentioned, i is uninitialized in your outer for loop. Luckily, that never comes into play because you have no braces around the loop body. Your code is equivilent to for (int i; i < numbers.size(); i++) { int j = 0; } while (numbers[i] + numbers[j] <= target) { // ... } This is presumably not what you intended, so you need to both initialize i and add {} around the loop body: for (int i = 0; i < numbers.size(); i++) { int j = 0; while (numbers[i] + numbers[j] <= target) { // ... } } Of course, you also don't need the redundant definitions of i and j outside the loops. Those variables get hidden by the ones defined within the loops, and are never used. Of course, this still doesn't address your out-of-range error. For that, you need to re-think your algorithm. Lets walk through it to find the issue. I'll just focus on the inner while loop. Assuming, from your test case that numbers = {5, 25, 75} and target = 100. First iteration: i = 0 and j = 0 numbers[i] + numbers[j] -> numbers[0] + numbers[0] -> -> 5 + 5 -> 10. That's less than 100, so the loop is entered if (10 == 100) is false, so the else branch is selected j++, so now i = 0 and j = 1 Second iteration: numbers[i] + numbers[j] -> numbers[0] + numbers[1] -> 5 + 25 -> 30. That's less than 100, so the loop continues if (30 == 100) is false, so the else branch is selected j++, so now i = 0 and j = 2 Third iteration: numbers[i] + numbers[j] -> numbers[0] + numbers[2] -> 5 + 75 -> 80. That's less than 100, so the loop continues if (80 == 100) is false, so the else branch is selected j++, so now i = 0 and j = 3 Third iteration: numbers[i] + numbers[j] -> numbers[0] + numbers[3] -> boom j is now out of range of the valid indices of numbers, so when you attempt to access numbers[j] the behavior of your program becomes undefined. In this case, it crashed; the best possible outcome.
73,467,607
73,479,402
LLVM: how to assign an array element?
I'm struggling to figure out how to assign an array element using the LLVM c++ API. consider this C code: int main() { int aa[68]; aa[56] = 7; return 0; } using clang -S -emit-llvm main.c I get the following IR (attributes and other things are skipped for simplicity): define dso_local i32 @main() #0 { %1 = alloca i32, align 4 %2 = alloca [68 x i32], align 16 store i32 0, i32* %1, align 4 %3 = getelementptr inbounds [68 x i32], [68 x i32]* %2, i64 0, i64 56 store i32 7, i32* %3, align 16 ret i32 0 } I already know how to create an inbounds GEP, but when storing a value (7) to the array the type is a pointer to i32. my language is very similar to C, that's why I'm using C as an example (so far it's just C but with a different syntax). generated IR for my language is: define i32 @main() { %0 = alloca [2 x i32], align 4 %1 = getelementptr [2 x i32], [2 x i32]* %0, i32 1 store i32 1, [2 x i32]* %1, align 4 ret i32 0 } how can I possibly turn [2 x i32]* into i32* when creating a store? this is how I create the store: llvm::AllocaInst *stored = symbol_table[arr_name]; llvm::Value *result = ir_builder->CreateGEP(stored->getAllocatedType(), stored, idx_vals); // idx_vals contains the index ir_builder->CreateStore(val, result); // here val is a value stored in a symbol table // and it's type is llvm::Value *
how can I possibly turn [2 x i32]* into i32* when creating a store? This is exactly what the "get element pointer" instruction does. You have a pointer to an object like a struct or an array, and you want a pointer to one element. %1 = getelementptr [2 x i32], [2 x i32]* %0, i32 1 This isn't quite what you want. Picture a C string in memory, you don't have a [*number* x i8]* you just have an i8*. If you had a pointer to [*number* x i8]* you'd be stepping into that array and getting a pointer to one of its elements, but with a C string you have a pointer to a single i8 element and you step over it, advancing your pointer by sizeof the pointee. What your %1 is doing is stepping over one whole [2 x i32] and pointing to another full [2 x i32] after it. You don't want to step over at all, so your first index should be i32 0. Then you want to step into it and select the second i32 in your 2 x i32? Use i32 1 as your second index. %1 = getelementptr [2 x i32], [2 x i32]* %0, i32, 0, i32 1 produces an i32*. See the LLVM GEP FAQ: https://www.llvm.org/docs/GetElementPtr.html