question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
73,602,012
73,602,094
Remove undefined behavior from overflow of signed integers in constant expressions?
EDIT In the actual example, it appears possible that negative overflow can happen, I've also added an example to demonstrate the error there I'm using C++20 and trying to convert a library which relies on signed integer overflow in Java and C# into C++ code. I'm also trying to generate the tables it uses at compile time, and allow those to be available at compile time. In my code I get errors in reference to code that looks like this (Minimal example to reproduce the error, the solution to this will solve my problem as well): #include <iostream> constexpr auto foo(){ std::int64_t a = 2; std::int64_t very_large_constant = 0x598CD327003817B5L; std::int64_t x = a * very_large_constant; return x; } int main(){ std::cout << foo() << std::endl; return 0; } https://godbolt.org/z/TvM45vd8d Negative overflow version #include <iostream> constexpr auto foo(){ std::int64_t a = -2; std::int64_t very_large_constant = 0x598CD327003817B5L; std::int64_t x = a * very_large_constant; return x; } int main(){ std::cout << foo() << std::endl; return 0; } https://godbolt.org/z/7zoE9r18E I get 12905529061151879018 is out side of range representable by long long and -12905529061151879018 respectively. I understand that undefined behavior here is not allowed, I also recognize that GCC and MSVC do not error here, and you can put a flag to make clang compile this anyway. But what am I supposed to do to actually solve this issue with out switching compilers or applying the flag to ignore invalid constexpr? Is there some way I can define the behavior I expect and want to happen here?
Signed integers have two's complement layout in any implementation that you could name. It's also guaranteed to use two' s complement layout since C++20. This means that you can perform your math on unsigned integers and get well-defined overflow behavior that matches what you want your signed integers to do. #include <iostream> #include <bit> constexpr auto foo(){ std::uint64_t a = 2; std::uint64_t very_large_constant = 0x598CD327003817B5L; std::uint64_t x = a * very_large_constant; return static_cast<std::int64_t>(x); }
73,602,071
73,602,299
C++: Function call precedence rules for calling functions on objects of derived classes?
I have a class Iterator, for which I have defined various operator overloads for equality testing (<, <=, >, >=, == and !=) as friend functions. Prototype example: friend bool operator<(const Iterator &A, const Iterator &B); class RevIterator inherits (virtually) from Iterator. Naturally, I have had to overload the operators <, <=, > and >= for this class (as friend functions again). Prototype example: friend bool operator<(const RevIterator &A, const RevIterator &B); I also have a class ConstIterator which inherits (virtually) from Iterator, for which I have not defined more operator overloads (they are meant to behave in the same way as for Iterator). Finally, I have a class ConstRevIterator which inherits from RevIterator and ConstIterator, for which I have not defined any operator overloads. Visual class hierarchy: class Iterator {}; class RevIterator : virtual public Iterator {}; class ConstIterator : virtual public Iterator {}; class ConstRevIterator : public RevIterator, public ConstIterator {}; My assumption was that for the operator <, for example, operating on two ConstRevIterators, the function available for one of the parent classes, RevIterator (2nd func. prototype above) would be called, instead of the function for the grandparent class, Iterator (1st func. prototype above). In summary, what are the rules for which function gets called on a reference to a 'grandchild' object, when there are functions available for its parent and grandparent classes?
Your assumption seems correct. You may find rules of overload resolution here https://en.cppreference.com/w/cpp/language/overload_resolution Here is the part concerning your question: If Mid is derived (directly or indirectly) from Base, and Derived is derived (directly or indirectly) from Mid a) Derived* to Mid* is better than Derived* to Base* b) Derived to Mid& or Mid&& is better than Derived to Base& or Base&& c) Base::* to Mid::* is better than Base::* to Derived::* d) Derived to Mid is better than Derived to Base e) Mid* to Base* is better than Derived* to Base* f) Mid to Base& or Base&& is better than Derived to Base& or Base&& g) Mid::* to Derived::* is better than Base::* to Derived::* h) Mid to Base is better than Derived to Base I also produced some code to verify it: https://godbolt.org/z/bc47dzxvY
73,602,090
73,602,192
What is the meaning of this expression
I am trying to push a integer that is stored in a string to a stack of type int I was trying to do the same by using stack.push(str[i]) which resulted in some weird values in the final outcome Github copilot suggeted to do it this way which was succesfull else { temp.push(exp[i]-'0'); } what is the meaning of -'0' here
The char '0' has ascii value 0x30 (48 decimal). The char '9' has ascii value 0x39 (57 decimal). If you do '9' - '0' = 57 - 48 = 9. So you are converting a digit from its ascii number '9' = 57 to its numeric value 9. This is often used when fast-converting a string of integers to its numeric value.
73,602,986
73,603,019
O(n/2) search in linked list
I'm supposed to make a search method for a linked list that has time complexity O(n/2). What would this look like? I heard that saying O(n/2) is the same as O(n). So is it just a search of all of the linked list's items? Or is there a specific sorting algorithm that would help me do this?
O(n/2) is indeed equivalent to O(n) so an O(n/2) search is just a linear search i.e. iterate over the list and test each item until you find the one you are looking for. If you are confused why O(n) and O(n/2) are equivalent, see my answer here.
73,603,396
73,608,660
Regex Replace gives different output according to compiler
DEMO #include <iostream> #include <regex> int main() { std::string bstr = "111111111111111111111111111111111111111110"; std::regex re(".{6}"); bstr = std::regex_replace(bstr, re, "|$00"); std::cout << "bstr: " << bstr << std::endl; return 0; } Why when I compile the same code using visual studio 2022 i get a different value stored on bstr after running the regex_replace function?
Short answer: Use $& as a reference to whole match. In this case the correct format string is: bstr = std::regex_replace(bstr, re, "|$&"); Long answer: Well, this is a rare case where MSVC is right and gcc and clang are (technically) buggy. C++ default regex flavour is based on ECMAScript standard. This standard defines $n and $nn as backreference to a capture group number n or nn, but neither of them allows 0 as valid group number. An invalid substitution should be left as is (i.e. treated like any other plain text). This is what MSVC is doing. It recognizes that $00 substitution is invalid per standard and treats it as plain text. gcc and clang on the other hand made it work like std::regex_match and treat group number 0 as the whole match. A reasonable assumption, but technically incorrect by standard. This can be confirmed also with regex101: |$00 is replaced with just that text, |$& is replaced with the match.
73,603,586
73,603,707
Question about the types `std::basic_string<char>::size_type` and `size_t` in the solution shown below
What is the difference between std::basic_string<char>::size_type and size_t? Some extra context: I have in mind something like the function in the code example appearing in the SO question linked below. There, an STL array is constructed for the purposes of parsing a string and saving information to said array. In the code example, default array values of std::string::npos are used, and if the npos values are never replaced during the life of the function, a -1 must be returned from the function. The underlying spirit of this question is to get at best practices for type usage in a context such as this. I posted a separate question that contains a code example containing the above constructs: Question about npos and -1 for the output of a C++ function
std::string is a typedef for std::basic_string<char> (so you do not need to keep unpacking this). std::string::size_type is a typedef for an unsigned type large enough to hold the length of any string. Usually this is a typedef for size_t although that is not a guarantee, so very robust code shouldn't rely on it. std::string::npos is the value -1 converted to std::string::size_type . So it is the largest possible value that can be held by std::string::size_type . Note that converting from std::string::size_type to int may be lossy since int is narrower than size_t generally, so you could not rely on (int)npos being -1.
73,603,794
73,679,667
QtApplication Error. Sound Effect is not a type. M300 error
I am facing a QQmlApplicationEngine failure while loading a component. The error is mentioned below: QQmlApplicationEngine failed to load component qrc:/KBButton.qml:54:5: SoundEffect is not a type The following section of KBButton.qml is failing: import QtQuick 2.0 import QtMultimedia 5.15 Rectangle { id: kbButton property double size: 100 x: centerX - width / 2 y: centerY - height / 2 SoundEffect { ~~~~~~~~~~~~~~~~~~~~~~Error occurs here. Unknown Component (M300) id: clickSound source: "resources/ClickSound.wav" } onClick: { isSelected = false; expManager.logKeyClicked(objectName) clickSound.play(); } } .pro file contains the following. Although I am importing QtMultimedia in qml files and not in C++ files, I still added the multimedia and multimediawidgets to qmake project file QT += qml quick widgets core quickcontrols2 multimedia multimediawidgets The code model could be reset using the Main Menu option available in QtCreator, as suggested by some online forums: Tools > QML/JS > Reset Code Model but this did not work. It didn't help either to run qmake again. What can be done to resolve this error?
As far as I know, QML should load the right version for you, so in this case it seems a good solution is to remove the version from your import: import QtMultimedia instead of import QtMultimedia 5.15 More info about the import statement: https://doc.qt.io/qt-6/qtqml-syntax-imports.html
73,603,798
73,603,911
What is the difference between "sum = addTwoNumbers" to just calling "addTwoNumbers"?
I'm a freshman in IT and we're currently discussing functions in C++. I just want to ask the difference between our prof's code and the other code that I tried. This is the sample code our prof showed us: #include<iostream> //header file using namespace std; int num1, num2, sum = 0; // global variable int addTwoNumbers(int a, int b) { sum = a + b; return sum; } int main() { cout << "Enter first number: "; cin >> num1; cout << "Enter second number: "; cin >> num2; sum = addTwoNumbers(num1, num2); cout << "\nThe sum is " << sum; } and as for the code I tried, I simply removed the "sum =" part. So, addTwoNumbers (num1, num2); cout << "\nThe sum is " << sum; and it still did the same thing. At least, from what I saw in the output. Is there any difference between the two behind the scenes or is there really nothing?
The 1st code is ... confusing. I hope your professor didn't show this code to introduce you to functions, but to rather quiz your already knowledge of functions and global variables. The confusing part are the global variables and how they are used inside the function. If we remove them and forget about them completely the code is better suited to teach you about functions. Let's see: #include <iostream> int addTwoNumbers(int a, int b) { int sum = a + b; return sum; // or simply: // return a + b; } int main() { int num1, num2; std::cout << "Enter first number: "; std::cin >> num1; std::cout << "Enter second number: "; std::cin >> num2; int sum = addTwoNumbers(num1, num2); std::cout << "\nThe sum is " << sum; } Now there are no hidden dependencies between main and addTwoNumbers (in the form of the global variables). This illustrates the procedure of passing data to function and getting data back from the function (parameters and return). Analyze this code and understand how it works. Play with it. Now this won't work: addTwoNumbers (num1, num2); cout << "\nThe sum is " << sum; Because the only way data escapes the function is via its return. Since you discard the return value (you don't assign the result of calling the function) you don't have the result of the sum. Now you could say you could do this instead: int sum = num1 + num2; cout << "\nThe sum is " << sum; and ask "what's the point of functions?" True for this particular small function there is no practical point of having it. You'll always write the num1 + num2 instead. However its simplicity makes it perfect as a teaching tool. You will soon see functions that get more complex and you will learn (either by being told or learning yourself the hard way) that writing code in very small chinks (functions) is better for both writing (breaking down the big problem in smaller problems) as well as for reading.
73,603,909
73,604,033
right associativity and order of execution of nested ternary operator in c++
I have the solution regarding execution order, but I cant understand how right associativity is linked to SCENARIO 2. a ? b: c ? d : e ? f : g ? h : i // scenario 1 : associativity understood, which is : (a?b:(c?d:(e?f:(g?h:i)))) and a ? b ? c : d : e // scenario 2 : NOT UNDERSTOOD From the first answer here, I am able to understand the first scenario but not the second.
The obvious (and generally best) advice about things like this is "just don't do it." Other than that, I find the easiest approach to be to think of them like Algol-style ifs. An Algol if was an expression, not a statement, so (much like a conditional, except readable) you could write something like this: a = if b then c else d; The transformation is really pretty simple. x ? is if (x) and : is else. Applying this to a nested conditional is actually pretty easy, and at least in my opinion, the result is much more readable. a ? b: c ? d : e ? f : g ? h : i Transforms to: if (a) { b; } else if (c) { d; } else if (e) { f; } else if (g) { h; } else { i; } The second is actually just about as easy, as long as you remember that x ? translates directly to if (x). Other than that, we follow the normal C rule that an else matches up with the most recent if that doesn't already have an else associated with it. a ? b ? c : d : e ...becomes: if (a) { if (b) { c; } else { d; } } else { e; };
73,604,042
73,609,086
Compiling Rust that calls C++ to WASM
I've found this How do I use a C library in a Rust library compiled to WebAssembly?, but this relies on wasm-merge, which has been discontinued. My problem is the following, I have some C++ code that I would like to call from Rust in order to have the option to compile the resulting package either to native code for use in mobile apps or to Webassembly for use in Node.js. At the moment, I have the following setup: libTest.cpp extern "C"{ int test_function(int i){ return i; } } lib.rs use wasm_bindgen::prelude::*; #[link(name = "Test")] extern "C"{ pub fn test_function(i: i32) -> i32 ; } #[wasm_bindgen] pub fn test_function_js(i : i32) -> i32{ let res = unsafe{test_function(i)}; res } build.rs fn main() { cc::Build::new() .cpp(true) .file("libTest.cpp") .compile("libTest.a"); } This compiles and works when compiling to native code using a simple cargo build, but does not work for building to wasm, for which I'm doing cargo build --target wasm32-unknown-unknown. There I get the two errors = note: rust-lld: error: /[path to my project]/target/wasm32-unknown-unknown/debug/build/rustCpp-cc5e129d4ee03598/out/libTest.a: archive has no index; run ranlib to add one rust-lld: error: unable to find library -lstdc++ Is this the right way to go about this and if yes, how do I resolve the above error? If not, how do I best go about calling C++ from Rust and compiling it to wasm?
(This is not really a full answer, but too long for a comment.) I can compile your example with cc::Build::new() .archiver("llvm-ar") // Takes care of "archive has no index" - emar might be an alternative .cpp_link_stdlib(None) // Takes care of "unable to find library -lstdc++" … // rest of your flags but I'm not sure whether the resulting binary is useful to you. Especially, it contains WASI imports when compiled in debug mode, and you'll probably get linker errors if you start using any interesting functions (e.g. sin). You could in theory give the C++ compiler a full stdlib to work with through .flag("--sysroot=/usr/share/wasi-sysroot/") (if you have wasi-sdk or wasi-libc++ installed), but I'm unsure how to best account for differences of where this folder is usually installed (maybe like this) I think you have to also pass this flag at link time, but I don't know how (it seems to work without, though) that would target wasi, and may not be useful for whatever bindgen-based environment you have in mind.
73,604,153
73,629,351
How to use an external DLL in a winrt component
I'm trying to use an external DLL in a winrt component. To be specific I built https://github.com/webview/webview and got the required DLLs but when trying to add a reference to these DLLs I get "The DLL is not a type or version current project can use". Now I know that Winrt components can use a winmd file as a reference but can I not use a regular DLL?
Just to Answer this question. I was trying to use a set of APIs in WinRT specific only to Win32 API. And that caused including the headers and lib to fail. Some of these APIs are the likes of SetDPIProcessAware. Otherwise you should follow this guide How to add additional libraries to Visual Studio project? to include libraries in your project.
73,604,422
73,604,975
Including a locally installed library in Arduino
How do I include a local file? This is my project structure (with multiple sketches): (project root) - some_config.json - SketchOne/ - SketchOne.ino - SketchTwo/ - SketchTwo.ino - lib/ - lib_1/ - some.h From SketchOne/SketchOne.ino, I want to include lib/lib_1/some.h. I've tried the following(s): #include "lib/lib_1/some.h" #include <lib/lib_1/some.h> #include "lib_1/some.h" #include <lib_1/some.h> Note: I use the CLI (arduino-cli)
In Arduino projects are called "sketches". The name of the main ino file of the sketch must match the name of the sketch folder. CLI builds one sketch at time. Sketches are in file system organized into a folder called "sketchbook". The sketchbook folder should containing a special folder named "libraries". Folders in the libraries folder are treated as libraries. There are two forms of library folder in the file system: old and new. See the sketch build process too.
73,604,455
73,604,596
Error when building FLTK: Configure could not find required X11 libraries
I am having trouble getting FLTK set up. I am currently using windows and trying to built it with msys2. Whenever I try to configure it with ./configure I get this error: configure: error: Configure could not find required X11 libraries, aborting. Here is the full stack trace: https://pastebin.com/raw/YeA72wYr I tried redownloading FLTK without success. What should I do? Thanks!
See this GitHub issue, where jputcu could workaround the issue by passing --build=mingw32 to the configure script. You can read the rest of the GitHub issue to learn more, or subscribe to it follow discussion. Feel free to participate there.
73,604,587
73,604,609
How to keep threads untangled when changing vector? c++
This program will crash cause the threads are tangled... One could be pushing while the other is trying to erase. How can I make this work? #include <thread> #include <vector> using namespace std; vector<int> v_test; void push() { v_test.push_back(0); } void erase() { if (v_test.size() > 0) { v_test.erase(v_test.begin()); } } int main() { thread w0(push); thread w1(erase); while (true) { Sleep(1000); } return 0; }
You need to synchronize the threads so they coordinate their access to the vector. For example, by using a std::mutex, eg: #include <thread> #include <mutex> #include <vector> using namespace std; vector<int> v_test; mutex m_sync; void push() { lock_guard<mutex> lock(m_sync); v_test.push_back(0); } void erase() { lock_guard<mutex> lock(m_sync); if (v_test.size() > 0) { v_test.erase(v_test.begin()); } } int main() { thread w0(push); thread w1(erase); while(true) {Sleep(1000);} return 0; }
73,605,178
73,605,219
C++ function pointer at declaration and argument
I am confused about using C++ function pointers. using fn_p1 = void(int); // function pointer using fn_p2 = void (*)(int); void functional(fn_p1 f) { f(1); } void callback(int value){ // do something } int main() { fn_p2 f = callback; //works fn_p1 f1 = static_cast<fn_p1>(f); //does not work fn_p1 f2 = callback; //does not work fn_p1 f2 = static_cast<fn_p1>(callback); //does not work functional(f); // works, the argument is form of void(*)(int) f(1); // works functional(*f); // works, the argument is dereferenced, void(int) (*f)(1); // works return 0; } I know there is no difference if you call a function pointer with f(1), (*f)(1), or (*****f)(1). I don't get how functional(f); works but fn_p1 f1 = static_cast<fn_p1>(f); and its variants can not since they define the function pointer as using fn_p1 = void(int);. Could anyone explain how the function pointer works or how the compiler deals with it?
The most useful error that the IDE should give you is on the line fn_p1 f2 = callback;: Illegal initializer (only variables can be initialized) [illegal_initializer] (This is the message I get from clangd.) That means literally that an entity of type void(int) (or more in general someReturnType(someArgTypes...)) is not a variable. Indeed, in C++ functions are not first class, which means that you can't pass them to function and don't get them in return from function; when you think you are successfully doing so, you're in reality passing or taking back function pointers. In other words there's no such a thing in C++ as "a function value". Functions are not values that you can assign to. When you write fn_p1 f2 = callback; // assuming using fn_p1 = void(int); you are truly trying to create a variable of type void(int). But such a thing doesn't exist, hence the error. The static_casts don't work for fundamentally the same reason. As regards void functional(fn_p1 f) { f(1); } function-to-(function)pointer decaying is happening. f is truly of type fn_p1*. You can easily verify it by writing an invalid statement in functional in order to trigger a compiler error telling you what the type of f is, like this void functional(fn_p1 f) { int foo = f; f(1); } Clangd answers this Cannot initialize a variable of type 'int' with an lvalue of type 'fn_p1 ' (aka 'void ()(int)') [init_conversion_failed] which indirectly tells you that f is of type fn_p1*, so you better write that instead of fn_p1 as the type of the parameter of functional, at least for clarity (similarly to how you should prefer writing T* instead of T[] as a parameter type in a function taking a c-style array of Ts). If you truly want to assign functions to variables, you should look at lambdas, structs+operator(), std::function, and the topic of function objects in general.
73,605,354
73,608,754
Call a derived class' (non-virtual) function in the base class' Destructor
Suppose we have the following class template: template<typename T> class Object { public: Object() = default; Object(const Object&) = delete; Object(Object&& other) noexcept { if (this != &other) { static_cast<T*>(this)->Release(); m_Id = std::exchange(other.m_Id, 0); } } auto operator=(const Object&) = delete; Object& operator=(Object&& other) noexcept { if (this != &other) { static_cast<T*>(this)->Release(); m_Id = std::exchange(other.m_Id, 0); } return *this; } ~Object() { static_cast<T*>(this)->Release(); m_Id = 0; } protected: std::uint32_t m_Id; }; (Please ignore the duplication in the move constructor and move assignment operator for the moment) This class is meant to act as a base class for OpenGL object wrappers. Following is an example use: class VertexBuffer : public Object<VertexBuffer> { public: VertexBuffer() { glGenBuffers(1, &m_Id); ... } void Release() { glDeleteBuffers(1, &m_Id); } }; The Object<T> class template is supposed to take care of the bookkeeping. The reason for doing this is that the pattern in the Object<T> class is repeated the exact same way for (almost) every OpenGL object wrapper that might be written. The only difference is the creation and deletion of the objects which is handled by the constructor and the Release() function in this example. Now the question is whether this (Object<T>::~Object() to be specific) taps into UB land? Undefined Behavior Sanitizer doesn't report any errors but I've never done this, so I though of asking people with more experience to make sure.
Short answer: Yes, this is undefined behaviour, don't do that. Long answer: The destruction of VertexBuffer invokes first ~VertexBuffer() and then invokes ~Object<VertexBuffer>() afterwards. When ~Object<VertexBuffer>() is invoked the VertexBuffer "part" of the object has already been destroyed, i.e. you are now doing an illegal downcast via static_cast (the remaining valid part of the object is a Object<VertexBuffer>, not a VertexBuffer). And undefined behaviour permits the compiler to do ANYTHING - it might even (appear to) work, only to suddenly stop working (or only work when you build in Debug mode, but not when in Release). So, for your own sake, please don't do that.
73,605,841
73,605,879
std::pair returned by std::transform resulting in segfault
I'm trying to transform a vector of strings to a vector of pairs of strings, and I was getting segfault. I've tried to narrow it down to a simple test case (below), and I'm sure it's likely to do with the memory allocation: #include <string> #include <vector> #include <utility> std::pair<std::string, std::string> newP( const std::string& foo) { return std::make_pair(std::string("Foo"), std::string("Bar")); } int main() { std::vector<std::string> vec; std::vector<std::pair<std::string, std::string>> pairs; vec.push_back("Hello, "); vec.push_back("World!"); std::transform(vec.cbegin(), vec.cend(), pairs.begin(), newP); } I get following segfault on FreeBSD 13.1: Program received signal SIGSEGV, Segmentation fault. Address not mapped to object. 0x0000000000205fd5 in std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::__is_long (this=0x0) at /usr/include/c++/v1/string:1456 1456 {return bool(__r_.first().__s.__size_ & __short_mask);} (gdb) bt #0 0x0000000000205fd5 in std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::__is_long (this=0x0) at /usr/include/c++/v1/string:1456 #1 0x0000000000205f0d in std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::__move_assign (this=0x0, __str="Foo") at /usr/include/c++/v1/string:2463 #2 0x0000000000205ee1 in std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::operator= (this=0x0, __str="Foo") at /usr/include/c++/v1/string:2485 #3 0x0000000000205ded in std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::operator= ( this=0x0, __p=...) at /usr/include/c++/v1/__utility/pair.h:277 #4 0x0000000000203fe5 in std::__1::transform<std::__1::__wrap_iter<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const*>, std::__1::__wrap_iter<std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >*>, std::__1::pair<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > (*)(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)> (__first=..., __last=..., __result=..., __op=0x203c20 <newP(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)>) at /usr/include/c++/v1/__algorithm/transform.h:29 #5 0x0000000000203d96 in main () at pair.cc:19 Could someone please explain what I'm doing wrong ? And if possible, what would be the best way to fix this. I'm fairly out of touch with modern C++. Thanks!
The vector pairs is empty, and pairs.begin() will return the pairs.end() iterator which can't be dereferenced. Set the size of pairs to the same size as vec before calling transform: pairs.resize(vec.size()); std::transform(vec.cbegin(), vec.cend(), pairs.begin(), newP); An alternative that has been mentioned is to preallocate memory and then use std::back_inserter to append to the vector: pairs.reserve(vec.size()); std::transform(vec.cbegin(), vec.cend(), std::back_inserter(pairs), newP); While the reserve call isn't strictly needed, it will avoid extra re-allocations and copying that might otherwise happen when adding new elements to the vector.
73,606,411
73,607,379
I'm writing a c++ mandelbrot generator but I need to work with HSV
I'm starting with a black cv::Mat image but I would like to add HSV to it. How do I achieve this?? int RE_START = -2; int RE_END = 1; int IM_START = -1; int IM_END = 1; int MAX_ITER = 80; int mandelbrot(std::complex<double> c){ std::complex<double> z{0,0}; int n = 0; while (abs(z) <= 2 && n < MAX_ITER){ z = z*z + c; n += 1; } return n; } int m; int main() { //! [mandelbrot-transformation] Mat mandelbrotImg(width, height,CV_8UC3, cv::Scalar(0, 0, 0)); Mat mandelHSV(width, height,COLOR_BGR2HSV); float wid = (float)width; float hei = (float)height; int count = 0; for (int x=0; x < width; x++){ for (int y=0; y<height; y++){ std::complex<double> c( RE_START + (x / wid) * (RE_END - RE_START), IM_START + (y / hei) * (IM_END - IM_START)); m = mandelbrot(c); double hue = (255 * m / (float)MAX_ITER); double saturation = 255.0; double value; if (m < MAX_ITER) { value = 255; }else { value = 0; } mandelbrotImg.at<cv::Vec3b>(x,y) = ((uchar)hue, (uchar)saturation, (uchar)value); count++; } } cv::cvtColor(mandelbrotImg, mandelbrotImg, COLOR_BGR2HSV); imwrite("../img/mandle.png", mandelbrotImg); } }; This is what I have so far! I dont know if I need to convert it or assign the HSV value at the pixel location. I've added floating point division I've added norm(z) into mandelbrot The image output is now: Expected output:
There were numerous issues in you original code, and there are still quite a few in your current one. To name some: cv::Mat constructor expects first the height, then the width. cv::Mat::at method expects first the y coordinate, then the x. The final color conversion should be COLOR_HSV2BGR not COLOR_BGR2HSV. mandelbrot should better accept the parameter by const& to avoid copy (an efficiency issue). Instead of checking abs(z) <= 2, it's better to use norm(z) <= 4 since it avoids calculating the sqrt (an efficiency issue). Since your main calculations are in doubles, I swapped all the floats to doubles. There's no need to initialize the cv::Mat to a zero value upon construction, because later on we fill all the pixel values anyway. See fixed version: #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <complex> static const int RE_START = -2; static const int RE_END = 1; static const int IM_START = -1; static const int IM_END = 1; static const int MAX_ITER = 80; int mandelbrot(std::complex<double> const & c) { std::complex<double> z{ 0,0 }; int n = 0; while (std::norm(z) <= 4 && n < MAX_ITER) { z = z*z + c; n += 1; } return n; } int main() { int width = 960; int height = 640; cv::Mat mandelbrotImg(height, width, CV_8UC3); double wid = (double)width; double hei = (double)height; double reWidth = RE_END - RE_START; double imWidth = IM_END - IM_START; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { std::complex<double> c(RE_START + (x / wid) * reWidth, IM_START + (y / hei) * imWidth); int m = mandelbrot(c); double hue = (255 * m / (float)MAX_ITER); double saturation = 255.0; double value = (m < MAX_ITER) ? 255.0 : 0; mandelbrotImg.at<cv::Vec3b>(y, x) = cv::Vec3b((uchar)hue, (uchar)saturation, (uchar)value); } } cv::cvtColor(mandelbrotImg, mandelbrotImg, cv::COLOR_HSV2BGR); cv::imwrite("../img/mandle.png", mandelbrotImg); } Output:
73,606,569
73,606,662
How do I change Clang's default include path on Windows
I failed to find system interal header files (like <iostream>). I can pass arguments to compile every time, but is there a way to change the default includes? C:\WINDOWS\system32>clang++ -v -c -xc++ nul clang version 16.0.0 (https://github.com/llvm/llvm-project.git e529c0a2a03fb4eb0ddffafe0ddc7a02059f74cc) Target: x86_64-pc-windows-msvc Thread model: posix InstalledDir: D:\languages\LLVM\bin (in-process) "D:\\languages\\LLVM\\bin\\clang++.exe" -cc1 -triple x86_64-pc-windows-msvc19.31.31107 -emit-obj -mrelax-all -mincremental-linker-compatible --mrelax-relocations -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name nul -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -mllvm -treat-scalable-fixed-error-as-warning -v "-fcoverage-compilation-dir=C:\\WINDOWS\\system32" -resource-dir "D:\\languages\\LLVM\\lib\\clang\\16.0.0" -internal-isystem "D:\\languages\\LLVM\\lib\\clang\\16.0.0\\include" -internal-isystem "D:\\program tools\\Microsoft\\VC\\Tools\\MSVC\\14.25.28610\\include" -internal-isystem "C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.19041.0\\ucrt\\" -internal-isystem "C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.19041.0\\um" -internal-isystem "C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.19041.0\\shared" -fdeprecated-macro "-fdebug-compilation-dir=C:\\WINDOWS\\system32" -ferror-limit 19 -fmessage-length=120 -fno-use-cxa-atexit -fms-extensions -fms-compatibility -fms-compatibility-version=19.31.31107 -std=c++14 -fdelayed-template-parsing -fcxx-exceptions -fexceptions -fcolor-diagnostics -faddrsig -o nul.o -x c++ nul clang -cc1 version 16.0.0 based upon LLVM 16.0.0git default target x86_64-pc-windows-msvc ignoring nonexistent directory "D:\program tools\Microsoft\VC\Tools\MSVC\14.25.28610\include" ignoring nonexistent directory "C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\ucrt\" ignoring nonexistent directory "C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um" ignoring nonexistent directory "C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\shared" #include "..." search starts here: #include <...> search starts here: D:\languages\LLVM\lib\clang\16.0.0\include End of search list. just want to change these default nonexistent directory (I built clang from source)
The trick I use with GCC, which should also work with Clang, is using the environment variables C_INCLUDE_PATH/CPLUS_INCLUDE_PATH for compiler include paths and LIBRARY_PATH for linker library paths.
73,606,971
73,607,129
What the meaning of mark a lambda capturing this as mutable in C++?
I found following code in a raft implementation. [this](ptr<resp_msg>& resp, const ptr<rpc_exception>& e) mutable { this->handle_peer_resp(resp, e); } When we capture this in a lambda expression, we have already be allowed to modify the value of member or call member function (as shown following). #include <functional> #include <iostream> class A { public: int a; A() { a = 0; } std::function<void(int)> func = [this](const int & b) mutable { a = 10; this->print(b); }; void callFunc() { func(1); } void print(const int & b) { std::cout << a << " " << b << std::endl; } }; int main() { A a; a.callFunc(); return 0; } Why do they use mutable in this lambda function ?
In this std::function<void(int)> func = [this](const int & b) mutable { a = 10; this->print(b); }; there is nothing mutating the lambda and removing mutable would be the reasonable thing to do. I therefore made a pull request in the Cornerstone repo to remove mutable from the lambdas that don't mutate, which has been approved, so now the confusing mutables aren't there anymore.
73,607,289
73,654,370
How to configure Visual Studio Code so that it selects an already opened file in a different split view instead of opening it again in the same view?
I often use split view in Visual Studio Code, e.g., showing a C++ header file in the left view and the associated source file in the right view. What I often do is use the command Go to Definition (default key binding F12) in the header file (which is open in the left view). And then Visual Studio Code goes on to open the definition in the left view, so that the associated source file is now open in both, the left and the right view. What I would like Visual Studio Code to do instead is to select the definition in the right view, where the source file is already opened. How to configure Visual Studio Code to do that? I would like Visual Studio Code to act in the same manner as Visual Studio does, which shows exactly the behavior I would like to see, namely selecting the already opened source file and jumping to the definition there, instead of opening the same file twice in different views.
Visual Studio Code provides the following option which enables the desired behavior: Reveal If Open Controls whether an editor is revealed in any of the visible groups if opened. If disabled, an editor will prefer to open in the currently active editor group. If enabled, an already opened editor will be revealed instead of opened again in the currently active editor group. Note that there are some cases where this setting is ignored, e.g. when forcing an editor to open in a specific group or to the side of the currently active group. It seems to be off by default.
73,607,462
73,607,780
Itoa stopping strcat from properly appending
I am trying to append a series of char arrays in Arduino C++. I have a char array "outputString", and a series of other char arrays that I with to append with via strcat. I also have a checkSum generator that generates the checksum and I used Itoa to convert the checksum value from an int into a base16 character array for appending. This is what it looks like: char cmdtype[6] = "AAAAA"; //The 5-letter command bool canPrint = true; int checkSumGenerator(char message[]) { int checkSum = 0; for (int i = 0; i < 21; ++i) //Remove the Checksum character, as well as the Null Character { checkSum ^= message[i]; } Serial.println(checkSum); Serial.println("Printed checksum."); return checkSum; } void setup() { // put your setup code here, to run once: Serial.begin(9600); // usb port serial } void loop() { //Collect data. if (Serial.available() > 0 && canPrint == true) { char outputString[] = "TOSBC_"; Serial.println(outputString); strcat (outputString, cmdtype); Serial.println(outputString); strcat (outputString, "_"); Serial.println(outputString); strcat (outputString, "00001212"); strcat (outputString, "_"); Serial.println("Line w/ "00001212" should be below"); Serial.println(outputString); int outputCheckSum = checkSumGenerator(outputString); char outputCheckSumHex[3]; itoa (outputCheckSum, outputCheckSumHex, 16); //Commenting this line seems to remove the "00001212" thing. Serial.println(outputCheckSum); //Serial.println(outputCheckSumHex); Serial.println(outputString); canPrint = false; //Only want it to print once. } } Under this code, the output is the following: 10:40:23.740 -> TOSBC_ 10:40:23.740 -> TOSBC_AAAAA 10:40:23.740 -> TOSBC_AAAAA_ 10:40:23.740 -> Line w/ cmdparam should be below 10:40:23.740 -> TOSBC_AAAAA_00001212_ 10:40:23.740 -> 87 10:40:23.740 -> Printed checksum. 10:40:23.740 -> 87 10:40:23.740 -> TOSBC_A57 //What I'm expecting is "TOSBC_AAAAA_00001212_57" I am not entirely sure why that is the case. I don't know how itoa could possibly affect strcat from working properly, but this is something else I tried, and doing so allowed "00001212" to be printed. int outputCheckSum = checkSumGenerator(outputString); char outputCheckSumHex[3]; //itoa (outputCheckSum, outputCheckSumHex, 16); //Commenting this line seems to remove the "00001212" problem. The output is: 10:43:29.178 -> TOSBC_ 10:43:29.178 -> TOSBC_AAAAA 10:43:29.178 -> TOSBC_AAAAA_ 10:43:29.178 -> Line w/ '00001212' should be below 10:43:29.178 -> TOSBC_AAAAA_00001212_ 10:43:29.178 -> 87 10:43:29.178 -> Printed checksum. 10:43:29.178 -> 87 10:43:29.178 -> TOSBC_AAAAA_00001212_ Directly providing a value for outputCheckSum, like so, is also something I tried. It did not fix the problem. int outputCheckSum = 87; char outputCheckSumHex[3]; itoa (outputCheckSum, outputCheckSumHex, 16); Please let me know if more information is required to solve this issue.
The char outputString[] = "TOSBC_"; declaration gives the array just enough space to hold the initializer string; that is, the size of the array will be determined from the number of elements in the string literal – which will 7 (the 6 visible characters plus a nul terminator). Thus, attempting any strcat() on that will overflow the array's bounds and, as such, will be undefined behaviour (UB). The fact that problems don't appear immediately (i.e. after the first few calls to strcat) is just one of the many possible manifestations of the UB. What appears to be happening, in your case, is that the compiler has assigned the memory for the outputCheckSumHex array right after that for outputString, and your call to ltoa is thus overwriting what has (by unlucky chance) already been written there by the earlier – and invalid – calls to strcat. The fix is trivial: just declare the outputString array with an explicitly specified size, and one that will make it large enough to accommodate all possible appended strings: if (Serial.available() > 0 && canPrint == true) { char outputString[100] = "TOSBC_"; // Specify a big enough size here! Serial.println(outputString); //...
73,608,580
73,608,938
Quick sort Hoare's partition not working when choosing last element as pivot
I'm learning about quick sort and have been having trouble for days with this problem. I implemented Hoare partition algorithm according to the algorithm on wikipedia: https://en.wikipedia.org/wiki/Quicksort#Hoare_partition_scheme // Sorts a (portion of an) array, divides it into partitions, then sorts those algorithm quicksort(A, lo, hi) is if lo >= 0 && hi >= 0 && lo < hi then p := partition(A, lo, hi) quicksort(A, lo, p) // Note: the pivot is now included quicksort(A, p + 1, hi) // Divides array into two partitions algorithm partition(A, lo, hi) is // Pivot value pivot := A[ floor((hi + lo) / 2) ] // The value in the middle of the array // Left index i := lo - 1 // Right index j := hi + 1 loop forever // Move the left index to the right at least once and while the element at // the left index is less than the pivot do i := i + 1 while A[i] < pivot // Move the right index to the left at least once and while the element at // the right index is greater than the pivot do j := j - 1 while A[j] > pivot // If the indices crossed, return if i ≥ j then return j // Swap the elements at the left and right indices swap A[i] with A[j] Here is my c++ code: #include <iostream> int hoare_partition(int A[], int low, int high){ int pivot = A[high]; int i = low-1; int j = high+1; while (true){ do i++; while (A[i] < pivot); do j--; while (A[j] > pivot); if (i >= j) return j; std::swap(A[i], A[j]); } } void quick_sort(int A[], int low, int high){ if (low < high){ int pivot = hoare_partition(A, low, high); quick_sort(A, low, pivot); quick_sort(A, pivot+1, high); } } int main(){ int n; std::cin >> n; int A[n]; for (int i = 0; i < n; i++) std::cin >> A[i]; quick_sort(A, 0, n-1); for (int i = 0; i < n; i++) std::cout << A[i] << " "; return 0; } The problem comes when I want to select the last element as pivot so I have set int pivot = A[high] and when I enter test case 5 4 3 2 1 my code is not working. After testing many times I found if I set pivot = A[from low to high-1] everything works fine, it only gives error when I set pivot = A[high]. Can anyone help me understand why things are not working in this case? And how to select last element as pivot with hoare's partition? Thank you very much.
TL;DR The implementation you use may not choose the final element as a pivot. Explanation You need to carefully read the whole description of the algorithm. Specially, note the following quote from the section you linked: The division returned is after the final position of the second pointer, so the case to avoid is where the pivot is the final element of the range and all others are smaller than it. Therefore the pivot choice must avoid the final element (in Hoare's description it could be any element in the range); this is done here by rounding down the middle position, using the floor function. This illustrates that the argument for correctness of an implementation of the Hoare partition scheme can be subtle, and it is easy to get it wrong. Simple demo of this case is {4,3,2,5}, which comes in your data in the second recursion step: https://godbolt.org/z/hsca8EEG8.
73,608,886
73,609,839
Where to find BGI file?
I am trying to plot circle using graphics.h library but all the tutorials and examples I have seen had "C:\TurboC\BGI" in the initgraph() function. As long I understand, the mentioned path leads to the graphics driver, but in my my PC I was unable to find any BGI file. I am using mingw-w64 environment on visual studio code. Is there any different command or add-on I should install to access graphics programming in c++? It would be a lot of help, if anyone can suggest any alternative way to do graphics programming in c++.
Go to https://github.com/ananay/turboc OR download Turbo C++ software then use the installation location (which is C:/ in above example) /TurboC/BGI BGI files come with Turbo C++
73,609,126
73,610,015
Is there any C++ counterpart for Borland C++ Builder 5's dir.h header?
I need to adapt a file written in Borland C++ Builder 5 to be usable in MS Visual Studio 2022. One of the files heavily utilizes the dir.h library, which, as far as I can tell, is a C library exclusive to Builder. The source files are available, however they have a lot of dependencies and, as I've mentioned, are written in C. I have searched the Internet for a substitute, unfortunately to no avail. Does a similar library exist for C++? Or do I have to re-write the file (which is pretty big) using e.g. std::filesystem?
The functions in dir.h are mapping quite direct to Win32 API calls of fileapi.h. You could use this header for a quick port. For a modernization, it might be the best idea to re-write the code using std::filesystem. There is hardly any sensible C++ library with such a C-like API. Well, there are the modernized Embarcadero API-calls in System.SysUtils.hpp, but they are still no modern C++, and they are only available in their ecosystem.
73,609,369
73,609,684
How can I save Checkbox selection in qt c++?
I am trying to develop an application with QT C++. I added a checkBox. How can I make my checkBox be in the last selection when I close my app and open it again. For example, if the checkbox was selected before the application was closed, I want it to be selected when the application runs again. If it wasn't selected before closing, it should come back unselected when it runs again. How can I do that?
Read the value of the checkbox when your app shuts down. Save the value somewhere, like; QSettings, a custom file, windows registry, etc. When your application starts, read the stored value and set the checkbox state to match.
73,612,148
73,612,182
Did I just change const value in C++ using refrence?
Code: #include <iostream> int main() { int a = 137; const int &b = a; std::cout << a << " " << b << std::endl; // prints 137 137 a++; std::cout << a << " " << b << std::endl; // prints 138 138 } The value of variable b becomes 138 after a++ statement, although it's declared as const Shouldn't this be not allowed? how to make sure this won't happen? or at least get a warning for doing that. I am using GNU GCC Compiler
Shouldn't this be not allowed? It's fine. Your code only prevents the b reference from changing the value, but the original variable a doesn't have such a restriction, so it can be freely changed.
73,612,230
73,612,864
Cross-compiling c++ with sdl on linux
I'm on Arch Linux, and I have a C++ SDL2 program, contained in single main.cpp file, and I compile it for Linux with such command: g++ main.cpp -lSDL2 -lSDL2_image Now I wanna compile it for windows. Any advice on what should I do?
I suggest my own tool, quasi-msys2, which lets you reuse the precompiled SDL2 for MinGW provided by MSYS2 (and more). Install Clang, LLD, make, wget, tar, zstd, gpg. git clone https://github.com/HolyBlackCat/quasi-msys2 cd quasi-msys2/ make install _gcc _SDL2 _SDL2_image env/shell.sh win-clang++ main.cpp `pkg-config --cflags --libs sdl2 SDL2_image` This should produce a.exe, which you can test using wine a.exe (or just ./a.exe, after running env/shell.sh). How to do this manually: For completeness, SDL2 itself distributes precompiled binaries for MinGW, meaning the manual setup is not hard. Any tutorial for MinGW should work. Install MinGW from your package manager. Download and unpack SDL2-devel-??-mingw.zip and SDL2_image-devel-??-mingw.zip. Specify the paths to the directories with .a files using -L... and to .h files using -I.... Add -lmingw32 -lmingw32 -mwindows -lSDL2main -lSDL2 -lSDL2_image to the linker flags. Follow this troubleshooting guide if you get stuck.
73,612,303
73,612,370
How to clear a `priority_queue` that uses user-defined compare?
How to clear a priority_queue that uses user-defined compare? From std::priority_queue documentation, I reduced the use of priority_queue to the case I need (= queue with user-defined compare) >> cat test.cpp #include <functional> #include <queue> #include <vector> #include <iostream> #include <utility> auto queue_cmp = [](std::pair<int, double> const& lhs, std::pair<int, double> const& rhs) { return lhs.second > rhs.second; // Custom order. }; typedef std::priority_queue<std::pair<int, double>, std::vector<std::pair<int, double>>, decltype(queue_cmp)> custom_queue; template<typename T> void print_queue(T q) { // NB: pass by value so the print uses a copy int s = 0; while(!q.empty()) { std::pair<int, double> elem = q.top(); std::cout << s << ": " << elem.first << ", " << elem.second << std::endl; q.pop(); s++; } std::cout << '\n'; } int main() { custom_queue q(queue_cmp); for (int n = 10; n < 20; n++) { double val = static_cast <double>(rand())/(static_cast<double>(RAND_MAX)); q.push(std::pair<int, double>(n, val)); } print_queue(q); //q = custom_queue(queue_cmp); } This runs OK >> g++ -o test test.cpp >> ./test 0: 15, 0.197551 1: 18, 0.277775 2: 16, 0.335223 3: 11, 0.394383 4: 19, 0.55397 5: 17, 0.76823 6: 12, 0.783099 7: 13, 0.79844 8: 10, 0.840188 9: 14, 0.911647 Now I need to reset q so, following priority queue clear method, I uncomment the last line in test.cpp... And get this compilation error as if I get this correctly, copy constructors are deleted on lamdba: >> g++ -o test test.cpp test.cpp: In function ‘int main()’: test.cpp:34:31: error: use of deleted function ‘std::priority_queue<std::pair<int, double>, std::vector<std::pair<int, double> >, <lambda(const std::pair<int, double>&, const std::pair<int, double>&)> >& std::priority_queue<std::pair<int, double>, std::vector<std::pair<int, double> >, <lambda(const std::pair<int, double>&, const std::pair<int, double>&)> >::operator=(std::priority_queue<std::pair<int, double>, std::vector<std::pair<int, double> >, <lambda(const std::pair<int, double>&, const std::pair<int, double>&)> >&&)’ 34 | q = custom_queue(queue_cmp); | ^ In file included from /usr/include/c++/12/queue:64, from test.cpp:2: /usr/include/c++/12/bits/stl_queue.h:498:11: note: ‘std::priority_queue<std::pair<int, double>, std::vector<std::pair<int, double> >, <lambda(const std::pair<int, double>&, const std::pair<int, double>&)> >& std::priority_queue<std::pair<int, double>, std::vector<std::pair<int, double> >, <lambda(const std::pair<int, double>&, const std::pair<int, double>&)> >::operator=(std::priority_queue<std::pair<int, double>, std::vector<std::pair<int, double> >, <lambda(const std::pair<int, double>&, const std::pair<int, double>&)> >&&)’ is implicitly deleted because the default definition would be ill-formed: 498 | class priority_queue | ^~~~~~~~~~~~~~ /usr/include/c++/12/bits/stl_queue.h:498:11: error: use of deleted function ‘<lambda(const std::pair<int, double>&, const std::pair<int, double>&)>&<lambda(const std::pair<int, double>&, const std::pair<int, double>&)>::operator=(const<lambda(const std::pair<int, double>&, const std::pair<int, double>&)>&)’ test.cpp:7:19: note: a lambda closure type has a deleted copy assignment operator 7 | auto queue_cmp = [](std::pair<int, double> const& lhs, | ^ Is there a way to reset q in this case? EDIT bool queue_cmp(std::pair<int, double> const& lhs, std::pair<int, double> const& rhs) { return lhs.second > rhs.second; // Custom order. }; Doesn't help
Not in C++17. C++20 gives capture-less lambdas a default constructor. But in earlier language versions, the constructor is deleted. Really, you should not be using a lambda. Just use a named struct.
73,613,276
73,613,327
Why is friend function showing me error that member x and y are private?
Somebody please help me as I can't understand why the compiler is throwing me an error that members x and y are inaccessible even though I have given the friend function declaration? #include<iostream> using namespace std; #include<math.h> class die; class point{ int x , y; public: friend int die :: dist(point, point); point(int a,int b){ x=a; y=b; } void display(){ cout<<"the point are ("<<x<<" , "<<y<<")"<<endl; } }; class die{ public: int dist(point p1 , point p2 ){ int final; final= sqrt((pow((p1.x-p2.x),2))+pow((p1.y-p2.y),2)); return final; } }; int main(){ point d(3,4); d.display(); point e(3,4); e.display(); die sum; sum.dist(d,e); return 0; }
You cannot use incomplete names in nested specifiers use . I.e., here: friend int die::dist(point, point). You cannot refer to a name that hasn't been declared. It's not enough to know that die exists. You also need to know that die::dist exists. In your original snippet, simple class die; does not say anything about die::dist. By the time point is befriending die::dist, there needs to be information about dist. Just reverse the forward declaration and implement dist() after point: class point; class die { public: int dist(point p1, point p2); // just a declaration }; class point { int x, y; public: friend int die::dist(point, point); point(int a, int b) { x = a; y = b; } void display() { cout << "the point are (" << x << " , " << y << ")" << endl; } }; int die::dist(point p1, point p2) { // implementation possible since we know about internals of point int final; final = sqrt((pow((p1.x - p2.x), 2)) + pow((p1.y - p2.y), 2)); return final; } Additionally, I see no reason for dist to be a member function of die. It can either be static, or simply be a free function.
73,613,371
73,613,470
Conditionally initialize an array
I want an array to have two different values, based on a condition. I can initialize the array inside the condition with the values i want. if (myCondition == 0) { byte my_message[8] = {0x00, 0xAB, 0xEE, 0xFF, 0x00, 0x01, 0x0A, 0x0B}; } else if (myCondition == 1) { byte my_message[8] = {0x11, 0xA1, 0xBC, 0x71, 0x00, 0x02, 0x94, 0x10}; } The problem with the previous approach is that the array has local scope, and it cannot be "seen" by the code beneath. If I try to declare the array outside the condition with: byte my_message[8]; then, inside the condition, I cannot use the previous way of initializing the whole array all at once. There is no pattern in the data so I can use a for loop- inside the condition- in order to give value to each element of the array easily. Is there a way of giving values to the array, besides the cumbersome: if (myCondition == 0) { my_message[0] = {0x00}; my_message[1] = {0xAB}; my_message[2] = {0xEE}; .... }
If my_message isn't changed, you could use a pointer instead of an array. const byte my_messages[2][8] = { { 0x00, 0xAB, 0xEE, 0xFF, 0x00, 0x01, 0x0A, 0x0B }, { 0x11, 0xA1, 0xBC, 0x71, 0x00, 0x02, 0x94, 0x10 }, }; const byte *my_message = my_messages[ myCondition ]; If you need to be able to change my_array, I'd use the following: const byte my_messages[2][8] = { { 0x00, 0xAB, 0xEE, 0xFF, 0x00, 0x01, 0x0A, 0x0B }, { 0x11, 0xA1, 0xBC, 0x71, 0x00, 0x02, 0x94, 0x10 }, }; byte my_message[8]; memcpy( my_message, my_messages[ myCondition ], sizeof( my_message ) ); You could memcpy from an anonymous array, but it's overly complicated and involves code repetition: byte my_message[8]; if ( myCondition ) { memcpy( my_message, ( byte[] ){ 0x11, 0xA1, 0xBC, 0x71, 0x00, 0x02, 0x94, 0x10 }, sizeof( my_message) ); } else { memcpy( my_message, ( byte[] ){ 0x00, 0xAB, 0xEE, 0xFF, 0x00, 0x01, 0x0A, 0x0B }, sizeof( my_message) ); }
73,613,566
73,613,593
Changing a Macros in another C++ file
I have a C++ file that uses functions defined in another C++ file. Let's say I am working with main.cpp and func.cpp. func.cpp #define SIZE 32 bitset<SIZE> functionA(int a) { Code; } and I have main.cpp main.cpp #include "func.cpp" int main(void) { int a; cin >> a; bitset<64> out; out = functionA(a); /// This is the functionality I want. } I don't want to directly change the value of SIZE in func.cpp. I want a way to somehow change the macros definition of SIZE to 64 from main.cpp. After this, I can call functionA and expect it to return a bitset of size 64.
You cannot change the definition of SIZE to be used with bitset<SIZE> without changing func.cpp. It is not possible. Do not use a macro. Make functionA a function template: template <size_t SIZE = 32> bitset<SIZE> functionA(int a) { Code; } Then in main call it with the SIZE you want: int main(void) { int a; cin >> a; bitset<64> out = functionA<64>(a); /// This is the functionality I want. } Because 32 is the default for SIZE, whenever you call functionA(x) the returned value is a bitset<32>. Do not include source files. Source files should not be included. Instead you should compile the source files and then link them. Include a header with the function declaration.
73,613,579
73,614,247
Error while trying to compile an c++ sdl2 program with mingw
Basically, when I'm trying to compile my program for windows on linux, I get such an error: /usr/lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld: ../libs/SDL2-2.24.0/x86_64-w64-mingw32/lib//libSDL2main.a(SDL_windows_main.o): in function `main_getcmdline': /Users/valve/release/SDL/SDL2-2.24.0-source/foo-x64/../src/main/windows/SDL_windows_main.c:82: undefined reference to `SDL_main' collect2: error: ld returned 1 exit status My main function starts like this: int main(int argv, char* args[]) My compiling script looks like this: #!/bin/bash x86_64-w64-mingw32-c++ -I../libs/SDL2-2.24.0/x86_64-w64-mingw32/include/ -L../libs/SDL2-2.24.0/x86_64-w64-mingw32/lib/ -I../libs/SDL2_image-2.6.2/x86_64-w64-mingw32/include/ -L../libs/SDL2_image-2.6.2/x86_64-w64-mingw32/lib/ -lmingw32 -lSDL2main -lSDL2 -lSDL2_image -mwindows And this is my file structure: ☃️ ├── my-project <where I run my script> │   └── main.cpp ├── my-script.sh └── libs ├── SDL2-2.24.0 └── SDL2_image-2.6.2 Any clues on why can't I compile it?
Oh, okay I was just dumb, didn't pass name of main.cpp to the compiler.
73,614,069
73,614,733
parameter isn't destroyed when argument throws exception?
Consider the following toy code: class X {}; class Y { public: Y() { cout << "Y ctor\n"; } ~Y() { cout << "Y dtor\n"; } }; int gun() { throw X{}; return 42; } void fun(Y yy, int i) {} int main() { Y a; cout << "--------\n"; try { fun(a, gun()); } catch (const X&) { cout << "catched\n"; } cout << "--------\n"; } The outputs of this are as follows: Y ctor -------- catched -------- Y dtor May I ask why the destructor of the parameter yy (copy initialized by a) is not called? Same outputs are produced when I switch the order of the arguments (i.e. using void fun(int i, Y yy) {} and fun(gun(), a);), so I don't think it is because of the undefined order of evaluation of function arguments. Update: see demo
There are no sequencing rules between the argument expressions in a function call and/or the initialization of function parameters until C++17. Since C++17 there are some rules which however still do not establish any ordering between the individual arguments. As a consequence only the indeterminate sequencing rules for function calls apply and the compiler is free to choose to either call gun() first and construct Y yy afterwards or the other way around. Due to the indeterminate sequencing rules the compiler is however not allowed to interleave these calls. So, if the compiler chooses the former order of evaluation, Y yy's constructor is never called before the exception is thrown and hence its destructor also won't (and shouldn't) be called. If the compiler decides to do it the other way around, then Y yy will have been constructed when the exception is thrown and its destructor will then also be called. You can verify this by adding output in the copy constructor as well. You will see that either the copy constructor is never called and yy does not have a destructor called or both will be called. You cannot control which of the two scenarios happens. The choice is unspecified, meaning that the compiler could also just choose it randomly at runtime. Reordering the arguments will not help. In practice there will be some rules in the compiler to decide the order at compile-time, probably in an order that is beneficial to optimization. It may be inconsistent between multiple equivalent calls as well.
73,614,093
73,614,196
Conversion from initializer_list<const char*> to initializer_list<string> in vector constructor
std::vector‘s initializer list constructor has the form vector( std::initializer_list<T> init, const Allocator& alloc = Allocator() ); What makes an initialization like std::vector<string> vec{ “foo”, “bar” }; possible? Why does the constructor accept an std::initializer_list<const char*>, even though the std::vectors‘s T is std::string? Where and how does the conversion from std::initializer_list<const char*>to std::initializer_list<string> happen?
I think you should refer to this section of the C++ 17 Standard (11.6.4 List-initialization) 5 An object of type std::initializer_list is constructed from an initializer list as if the implementation generated and materialized (7.4) a prvalue of type “array of N const E”, where N is the number of elements in the initializer list. Each element of that array is copy-initialized with the corresponding element of the initializer list, and the std::initializer_list object is constructed to refer to that array. [ Note: A constructor or conversion function selected for the copy shall be accessible (Clause 14) in the context of the initializer list. — end note ] If a narrowing conversion is required to initialize any of the elements, the program is ill-formed. [ Example: struct X { X(std::initializer_list<double> v); }; X x{ 1,2,3 }; The initialization will be implemented in a way roughly equivalent to this: const double __a[3] = {double{1}, double{2}, double{3}}; X x(std::initializer_list<double>(__a, __a+3)); assuming that the implementation can construct an initializer_list object with a pair of pointers. — end example ] Pay attention to that there is the conversion constructor for the class std::basic_string basic_string(const charT* s, const Allocator& a = Allocator()); So in this declaration std::vector<string> vec{ “foo”, “bar” }; at first an object of the type std::initializer_list<std::string> is constructed from the initializer list and then is used as an initializer for the vector of the type std::vector<std::string>. If instead you will write std::initializer_list<const char *> lst = { "foo", "bar" }; std::vector<std::string> vec( lst ); then the compiler will issue an error because there is no implicit conversion from the type std::initializer_list<const char *> to the type std::initializer_list<std::string>. That is the compiler determines whether it can build std::initializer_list from a braced initializer list to call the initializer-list constructor.
73,614,571
73,621,964
how to split log messages into file and screen in wxwidgets
When I read the WxWidgets documentation, I get the impression that the developers wrote it just for themselves, just to remember what they did 20 years ago. Regardless, I figured out how to send log messages to a file: wxLog::SetActiveTarget(new wxLogStderr(fopen(logPath + "/wxApp.log", "w + "))); and also I figured out how to change the format of the log messages: wxLog::GetActiveTarget()->SetFormatter(new MyLogger); But I didn't understand anything else. So I want to ask my question here. I want to make a log for my application. Moreover, I want: all log messages to be written to a file at the same time some of these messages are displayed on the screen using wxTextCtrl. So I want to filter the log messages that are displayed on the screen, depending on the logging level: for example, I want to display in wxTextCtrl only log messages with "wxLOG_Info" and "wxLOG_Error" levels. How can this be done in Windows and Linux in C++? It's best to show a code example.
I may be missing something but this seems very simple? For example, this could be the simplest possible log target which logs some messages into a wxTextCtrl and all of them into a wxFFile. #include <wx/wx.h> #include <wx/ffile.h> class MyLogTarget : public wxLog { public: // textCtrl must have longer lifetime than MyLogTarget MyLogTarget(wxTextCtrl* textCtrl, const wxString& fileName) : m_textCtrl(textCtrl), m_file(fileName, "a") {} protected: void DoLogTextAtLevel(wxLogLevel level, const wxString& msg) override { // preserve debug logging if ( level == wxLOG_Debug || level == wxLOG_Trace ) wxLog::DoLogTextAtLevel(level, msg); if ( level == wxLOG_Info || level == wxLOG_Error ) m_textCtrl->AppendText(msg + "\n"); if ( m_file.IsOpened() ) m_file.Write(msg + "\n"); } private: wxTextCtrl* m_textCtrl; wxFFile m_file; }; class MyFrame : public wxFrame { public: MyFrame(wxWindow* parent = nullptr) : wxFrame(parent, wxID_ANY, "Test") { wxTextCtrl* logCtrl = new wxTextCtrl(this, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH2); wxLog::SetActiveTarget(new MyLogTarget(logCtrl, "log.txt")); wxLogDebug("Debug test"); wxLogMessage("Message test"); wxLogInfo("Info test"); wxLogError("Error test"); } ~MyFrame() { delete wxLog::SetActiveTarget(nullptr); } }; class MyApp : public wxApp { public: bool OnInit() override { (new MyFrame())->Show(); return true; } }; wxIMPLEMENT_APP(MyApp); Please notice that this would have to be extended to be usable in a real application, for example, handle the file encoding / flushing / cleaning / error handling (without getting into the endless logging loop), use the full path for the file (e.g., obtained with wxStandardPaths), use a log chain to preserve (some of?) the default wxWidgets logging... If you want to use separate log targets for logging into a text control and a file, it is still very simple except that you have to chain the log targets, as explained in the docs.
73,614,980
73,615,142
Why does reinterperet cast work on pointers and static doesn't
I'm learning about type casting and finding it pretty tough to understand it. So from what I've learned. You cannot static cast pointers of one type to another. I don't know exactly why. Because you can static cast an int to a char which has there own address in memory so its super confusing me as to why you cannot do the same with pointers. So with reinterpret cast. You can convert a pointer type to another pointer type. I think? So a few questions i have are. You can convert non pointer variables with a static cast. And You can cast pointers types to different pointer types using reinterpret? Below are some examples of stuff I'm struggling on. <int *>something // what is the * inside of the <int> meaning? // i know what the previous *<int> means to deference. // So if i have this does this mean I'm casting something into a char pointer // and storing the cast inside of ptr? char* ptr = static_cast<char *>something //With reinterpret cast i can cast from another type like this int x = 9; int* ptr = {&x}; char* nowchar = reinterpret_cast<char *>&x // the above is fine? //But i cannot do the same with static int x = 8; int* ptr = {&x}; char* nowchar = static_cast<char*>&x; Can you explain why i cannot use static on a pointer, and why reinterpret_cast works
Taking this one question at a time: <int *>something // what is the * inside of the <int> meaning? When you are casting, what you put in the angle brackets is the type, int* (or int *) is a pointer to an integer. This is often confusing for those new to C++ because you also use the * operator to dereference a pointer, but in this context it denotes that the type is a pointer to an int and not an int. // So if i have this does this mean I'm casting something into a char pointer // and storing the cast inside of ptr? char* ptr = static_cast<char *>something Yes, the only case I'm aware of where this will work is if you are casting from / to a void* or if you are casting from a base class to a derived class, e.g.: class Something{}; class SomethingElse : public Something{}; ... Something* something = new Something(); SomethingElse* ptr = static_cast<SomethingElse *>(something); In this case, you are correct that you are casting the pointer to the instance of Something into a pointer for the derived class SomethingElse. //With reinterpret cast i can cast from another type like this int x = 9; int* ptr = {&x}; char* nowchar = reinterpret_cast<char *>(&x); // the above is fine? //But i cannot do the same with static int x = 8; int* ptr = {&x}; char* nowchar = static_cast<char*>(&x); In C++, static_cast is only used for a few (mostly) well-defined conversions. There is no well-defined conversion from a pointer to an int to a pointer to a char. Considering that neither the size (number of bits) of char nor int are specified, this makes sense. What does the compiler do if you are trying to cast a 16-bit int to an 8-bit char? In this case, what you need to do is reinterpret the int pointer to a char pointer; hence why you need to use a reinterpret_cast instead. Specifically, this will tell the compiler that it is allowed to reinterpret the underlying bit pattern of the data however it sees fit.
73,615,389
73,615,430
Implement a virtual function for two derived classes, that is the same except for one variable Type
I have an abstract class Node that can either be a Leaf or a NonLeaf. I have written a large function SplitNode. The problem is, this function is basically the same for a Leaf as for a NonLeaf. The only difference being that it operates on the entries vector for Leafs, as opposed to the children vector, for NonLeafs. The code is otherwise identical in both cases. For example in one case I do entries[i]->r to access some Rectangle property, and in the other case I do children[i]->r. So the main difference beyond the 2 variable names, is the type of the actual vector. How am I supposed to implement this, without copying and pasting the same function, implemented slightly differently for Leaf and NonLeaf? Edit: I also want the SplitNode function to be able to be called recursively. class Leaf; class Node { public: Node(); virtual Leaf& ChooseLeaf(const Rectangle& entry_r) = 0; // this makes the Node class Abstract Rectangle r; unique_ptr<Node> parent; }; class Leaf : public Node { public: Leaf(); Leaf& ChooseLeaf(const Rectangle& entry_r) override; vector<unique_ptr<IndexEntry>> entries; }; class NonLeaf : public Node { public: NonLeaf(); Leaf& ChooseLeaf(const Rectangle& entry_r) override; vector<unique_ptr<Node>> children; }; Dummy illustration of the SplitNode() function: void SplitNode() { // in the Leaf case: if (this.entries.size() > rtree.M) { ... } // in the NonLeaf case: if (children.size() > rtree.M) { ... } // in the Leaf case: entries[0]->r.DoSomething(); // in the NonLeaf case: children[0]->r.DoSomething(); // Recursion parent.SplitNode(); ... |
This is a textbook case for a template function. Presuming that the common logic freestanding logic whose only dependency is the vector itself: template<typename T> void doSplitNode(T &entries_or_children) { for (auto &entry_or_child:entries_or_children) { auto &the_r=entry_or_child->the_r; // Here's your entries[i]->r, or children[i]->r } } // ... class Leaf : public Node { public: // ... void SplitNode() { doSplitNode(entries); } }; class NonLeaf : public Node { // ... void SplitNode() { doSplitNode(children); } }; Additional work will be needed of the shared logic has additional dependencies. There's no universal solution here, everything depends on the details. Perhaps the template itself can be moved into a class, with both NonLeaf and Leaf multiply-inheriting from it, and then implementing the additional dependencies as virtual/abstract methods.
73,615,507
73,615,651
How to transfer a mutex containing object from one function to another?
#include <mutex> class ConcurrentQueue { // This class contains a queue and contains functions push to the queue and pop from the queue done in a thread safe manner. std::mutex m; }; class Producer { // This class contains several methods which take some ConcurrentQueue objects and then schedule tasks onto it. public: void func(ConcurrentQueue a) {} }; class Consumer { // This class contains several methods which take the same ConcurrentQueue objects and then remove the tasks and complete them one by one. public: void func(ConcurrentQueue a) {} }; int main() { // Here I want to generate the necessary ConcurrentQueue objects and then start threads for producer and consumer methods where I supply it with the required queue objects. ConcurrentQueue a; Producer b; // :( Unfortunately I cannot pass in any of my ConcurrentQueue objects to the methods as apparantly I cannot copy transfer a mutex. b.func(a); // This line gives compiler error saying the copy constructor is deleted. return 0; } The above code explains the whole situation through comments. How do I design it better so that I am able to achieve this?
If you don't want your ConcurrentQueue class to be copyable, then don't pass it by value; use pass-by-reference (i.e. arguments of types const ConcurrentQueue & or ConcurrentQueue &) instead. OTOH if you actually want your ConcurrentQueue class to be copyable (and you should carefully consider whether or not allowing the copying of a ConcurrentQueue object would be helpful or harmful to your goals), you can simply add a copy-constructor to your ConcurrentQueue class that copies the other member-variables but doesn't try to copy the std::mutex: class ConcurrentQueue { // This class contains a queue and contains functions push to the queue and pop from the queue done in a thread safe manner. std::mutex m; std::queue<int> q; public: ConcurrentQueue() { // default constructor } ConcurrentQueue(const ConcurrentQueue & rhs) { // serialize access to rhs.q so we can read its // contents safely while copying them into this->q const std::lock_guard<std::mutex> lock(const_cast<std::mutex &>(rhs.m)); q = rhs.q; } }; Note that I needed to add a default-constructor as well, since once you add any kind of constructor to the class, the compiler will no longer automatically create a default-constructor for you anymore. If you're using C++11 or later, you could declare the default-constructor via ConcurrentQueue() = default; instead.
73,615,686
73,618,555
Does an implementation that returns fundamental types by value using registers do "temporary materialization"?
(c++20; Working Draft N4868) [stmt.return]/2 says that the return statement initializes the glvalue result or prvalue result object by copy initialization the return statement initializes the glvalue result or prvalue result object of the (explicit or implicit) function call by copy-initialization (9.4) from the operand. For class types, the return statement "invokes" the selected constructor and copy-initialize the variable obj, the result object of the invocation, because the copy-elision (an implementation is the caller to pass the address of the dest, so that the called function initialize the dest by constructor call) class MyClass { int x; }; MyClass func() { return MyClass(); //initializes the result object of the function call } int main() { MyClass obj {func()}; //obj is the result object of func(). } [dcl.init.general]/16.6.1 suggests: If the initializer expression is a prvalue and the cv-unqualified version of the source type is the same class as the class of the destination, the initializer expression is used to initialize the destination object For fundamental types like int, double, etc., the common implementation is the return statement to copy the operand (return expression) to the registers (gcc 12.1 -std=c++20) int func() { return 2; } int main() { int myInt {func()}; } func(): push rbp mov rbp, rsp mov eax, 2 pop rbp ret main: push rbp mov rbp, rsp sub rsp, 16 call func() mov DWORD PTR [rbp-4], eax mov eax, 0 leave ret In [class.temporary]/1.2, the standard says that is it possible to materialize temporaries if the type is "trivially copyable": 1 Temporary objects are created [...] —(1.2) when needed by the implementation to pass or return an object of trivially copyable type (see below), [...] Question: Does implementation like that for fundamental types (int, double, etc.) uses the [class.temporary]/1.2 as source? If yes, then does the function call materialize an temporary (using registers) and the return statement initialize that temporary by copy-initialization? Related Initialization in return statements of functions that return by-value
Does an implementation that returns fundamental types by value using registers do "temporary materialization"? Yes. Does implementation like that for fundamental types (int, double, etc.) uses the [class.temporary]/1.2 as source? [class.temporary]/(1.2) is a non-normative reference to [class.temporary]/3, and an implementation can not use it for non-class types, which is the subject of CWG2434: 2434. Mandatory copy elision vs non-class objects In the following example, int f() { X x; return 4; } int a = f(); a must be directly initialized in the return statement of f() because the exception permitting temporaries for function arguments and return types in [class.temporary] paragraph 3 applies only to certain class types. This requirement is observable, since the destructor of X in the example could inspect the value of a. The permissions in this paragraph should also apply to all non-class types.
73,616,803
73,617,300
Clang partial class template specialization error
I've the following simple c++20 test: #include <type_traits> /////////////////////////////////////// constraints template <typename Type> concept isConst = ::std::is_const_v<Type>; template <typename Type> concept isNotConst = !isConst<Type>; /////////////////////////////////////// class decleration template <typename T> class TestRef; template <isNotConst T> struct TestRef<T> { explicit TestRef(T& value) noexcept; }; template <isConst T> struct TestRef<T> { explicit TestRef(T& value) noexcept; }; /////////////////////////////////////// class implementation template <isNotConst T> TestRef<T>::TestRef(T& value) noexcept {} template <isConst T> TestRef<T>::TestRef(T& value) noexcept {} /////////////////////////////////////// main int main() { int a{ 1 }; TestRef<int> ref1{ a }; TestRef<const int> ref2{ a }; return 0; } This exemple compiles fine with g++ 12.2.0. However, using clang++ 14.0.6, it does not. Here is the error: error: incomplete type 'TestRef' named in nested name specifier I failed to identify the reason why it does and how to work around it. What I understood is that it does not choose the specialized structure. It uses the basic one that is not defined. If I do define it, I get the error: error: type constraint differs in template redeclaration What can I do to fix the issue?
If there's no reason that you must use concepts, you can use a pre-C++20 way to implement it. template <typename T, typename = void> class TestRef; template <typename T> struct TestRef<T, std::enable_if_t<std::is_const_v<T>>> { explicit TestRef(T& value) noexcept; }; template <typename T> struct TestRef<T, std::enable_if_t<!std::is_const_v<T>>> { explicit TestRef(T& value) noexcept; }; /////////////////////////////////////// class implementation template <typename T> TestRef<T, std::enable_if_t<std::is_const_v<T>>>::TestRef(T& value) noexcept {} template <typename T> TestRef<T, std::enable_if_t<!std::is_const_v<T>>>::TestRef(T& value) noexcept {} Demo I'm showing you a general way. In your case, you don't have another specialization for the non-const version. You can fill them in the primary template.
73,617,065
73,628,720
Overloading conversion ctor and conversion operator in `To to = from;` and `To to = {from};`
In brief When I learned about C++ initialization these days, I found To to = from; behaves differently from To to = {from};, where from is of another type From: If conversion constructor To::To(From &) and conversion operator From::operator To() are provided, both of them will be considered for To to = from;, which will cause a compile error. However, only the conversion constructor will be considered for To to = {from};, which will work fine. What the hack here? To be detailed Code to reproduce this case on GCC 10.3 with C++20 applied: class From; class To { public: To() = default; To(From &) {std::cout << "conversion constructor\n";} }; class From { public: operator To() {std::cout << "conversion operator\n"; return {};} }; int main(int argc, char **argv) { From from; // To to1 = from; To to2 = {from}; return 0; } Uncomment the line and we'll get the error: case.cpp: In function ‘int main(int, char**)’: case.cpp:17:14: error: conversion from ‘From’ to ‘To’ is ambiguous 17 | To to1 = from; | ^~~~ From what I can tell, To to = from; is copy initialization. And this page says "the conversion functions and constructors are both considered by overload resolution in copy-initialization", which is pretty much about the error. What about To to = {from}; then? It is listed as an old way of copy initialization. But it's up untill C++11 and is probably not the case. Is it list initialization? Can someone give an explanation of how it deals with conversion constructor and conversion operator? Additional discussion I also experimented with C++11 in-class initialization, with a few more lines of code: class InClsInitialization { private: From from; // To to1 = from; To to2 = {from}; }; The result seems to be the same (i.e., uncomment the line and we'll get the same error), though I don't find which category of initialization it belongs to.
To to = from; is copy-initialization. It falls under [dcl.init.general]/16.6.3, according to which ... user-defined conversions that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated ... and the best one is chosen through overload resolution ([over.match]). ... Both converting constructors of To and conversion functions of From are considered. (Since this is copy-initialization, explicit functions will be ignored.) To to = {from}; is copy-list-initialization. Copy-list-initialization is a type of copy-initialization, but has different rules. Since To is not an aggregate, it falls under [dcl.init.list]/3.7, according to which ... constructors are considered. The applicable constructors are enumerated and the best one is chosen through overload resolution ([over.match], [over.match.list]). ... Thus, conversion functions are not considered. (Explicit constructors are considered, but the program is ill-formed if one of them is chosen by overload resolution.)
73,617,081
73,617,792
Will the compiler ever use the move constructor to move a named variable that is about to go out of scope?
consider function void foo() and class myclass class myclass { /* some data members, including pointers, and a move constructor */ }; void foo() { myclass myvar = myclass(...); // foo() allocates space on the stack for sdlv // then passes address in %rdi to constructor /* myvar is used a few times */ myclass myvar_copy = myvar; // myvar used for the last time return; } myvar is an lvalue, but when it is used for the final time, it might as well be a reference to a rvalue (&&). A C++ compiler will detect a typical && (like x * y) by recognizing that (x * y) is a temporary object. Will a C++ compiler (say gcc) intelligently know to use a move constructor in the example above too?
myclass myvar_copy = myvar; is copy initialization where myvar is an lvalue. The copy constructor has a parameter of type const myclass& and the move constructor has a parameter of type myclass&&. Now, since the argument that we're passing is myvar which is an lvalue only the copy constructor can be used since the move constructor parameter is myclass&& which cannot be bound to an lvalue.
73,617,170
73,618,663
Why SFINAE has different behavior with gcc <11 vs >12?
I saw this example of using SFINAE to check if a type is streamable here. However, I noticed that it is not portable, i.e. returns different results for templated types with different compilers. I'd be glad for any tips to understand the problem here. The code below returns true, false with any version of clang++ and GCC 12 or higher, but true, true with earlier versions of GCC. You can try it online here. #include <iostream> #include <type_traits> #include <vector> template <typename T, typename dummy = void> struct is_printable : std::false_type {}; template <typename T> struct is_printable< T, typename std::enable_if_t<std::is_same_v< std::remove_reference_t<decltype(std::cout << std::declval<T>())>, std::ostream>>> : std::true_type {}; template <typename T> inline constexpr bool is_printable_v = is_printable<T>::value; struct C {}; std::ostream& operator<<(std::ostream& os, const C& c) { os << "C"; return os; } template <typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { for (const auto& el : v) { os << el; } return os; } int main(int argc, const char* argv[]) { std::cout << std::boolalpha; std::cout << is_printable_v<C> << std::endl; std::cout << is_printable_v<std::vector<int>> << std::endl; return 0; }
operator<<(std::ostream& os, const std::vector<T>& v) won't be found by ADL (for std::vector<int>, it would for std::vector<C>) (and so need to be declared before usage to be usable). That is why correct answer is true, false. previous version of gcc misbehave on this. Note: It is discouraged to overload operator for types which you don't own. std might in the future add that overload, and you will have ODR (One definition rule) violation. Same if another library does the same wrong thing than you.
73,617,302
73,618,031
created a linked list to insert an array in it, but it's not giving desired output
I had created a program to create a linked list and insert an array in it. But it's not giving the desired output, may be the problem is in display function #include <iostream> using namespace std; //node class node { public: int data; node *next; } *head = nullptr; //function to insert array in linkedlist void create(int A[], int n) { node *head = new node; node *temp; node *last; head->data = A[0]; head->next = nullptr; last = head; for (int i = 1; i < n; i++) { //temp is an temporary variable which creates each time and last remebers its position temp = new node; temp->data = A[i]; cout << temp->data << endl; temp->next = nullptr; last->next = temp; last = temp; } } //function to display linked list which can access head because it is global void display() { node *p = head; while (p != nullptr) { cout << p->data << endl; p = p->next; } } int main() { int A[] = {1, 6, 9, 4, 5, 6}; node *head; create(A, 6); display(); return 0; } Maybe I understand something wrong like to add display function in class. But I had never seen a class pointer having functions. This is my first linked list program. If you could share some good info about it please do, thank you
The problem is that you have multiple variables named head being used for different purposes. You have a global variable head, which your display() function uses, but your create() function does not populate. create() populates a local variable named head instead, which shadows the global variable. display() never sees the created list. And main() has its own local variable named head, which is not being used for anything at all. Get rid of the global variable. Make create() return the list it creates. And then make main() pass that list to display(). Try something like this: #include <iostream> using namespace std; //node class node { public: int data; node *next; }; //function to insert array in linkedlist node* create(int A[], int n) { node *head = nullptr; node **p = &head; for (int i = 0; i < n; i++) { *p = new node{ A[i], nullptr }; p = &((*p)->next); } return head; } //function to display linked list void display(const node *head) { node *p = head; while (p != nullptr) { cout << p->data << endl; p = p->next; } } //function to destroy linked list void destroy(node *head) { node *p = head; while (p != nullptr) { node *next = p->next; delete p; p = next; } } int main() { int A[] = {1, 6, 9, 4, 5, 6}; node *head = create(A, 6); display(head); destroy(head); return 0; }
73,617,971
73,618,114
Type error in C++ when instantiating a priority_queue of int pairs with a custom comparator (to implement a min heap)
Currently working through a leetcode problem for which I need a min Heap of pairs. I am trying to use a priority_queue with int pairs and a custom compare type. Attempts of implementation of the same have failed with the following error: In file included from prog_joined.cpp:1: In file included from ./precompiled/headers.h:55: In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/queue:64: /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_queue.h:467:7: error: static_assert failed due to requirement 'is_same<int, std::pair<int, int>>::value' "value_type must be the same as the underlying container" static_assert(is_same<_Tp, typename _Sequence::value_type>::value, ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Line 9: Char 67: note: in instantiation of template class 'std::priority_queue<int, std::vector<std::pair<int, int>, std::allocator<std::pair<int, int>>>, std::greater>' requested here priority_queue<int, vector<pair<int, int>>, greater> pq; Here's the code with which I'm trying to implement the heap: #include <queue> #include <utility> using namespace std; //... priority_queue<int, pair<int, int>, greater<int>> pq;
As you can see in the std::priority_queue documentation: The 1st template argument is the data type (should be pair<int,int> in your case). The 2nd template argument should be the underlying container type used for the queue. The 3rd should be the compare type. For example if you want a priority_queue of int pairs that use std::vector as a container, you need: std::priority_queue<std::pair<int, int>, // data type std::vector<std::pair<int,int>>, // container type std::greater<std::pair<int,int>>> pq; // compare type Note: as you can see here the std::pair implementation for comparison operators which are used by std::greater is: Compares lhs and rhs lexicographically by operator<, that is, compares the first elements and only if they are equivalent, compares the second elements. If this is not what you need you can implement your own compare type for std::pair<int,int>. A side note: it is better to avoid using namespace std. See here: Why is "using namespace std;" considered bad practice?.
73,618,656
73,618,809
What is the usage of std::multimap?
I've just started learning STL containers, and I cannot understand why std::multimap exists. With std::map, we can access values by user-defined keys, but with std::multimap we cannot do that as the latter does not even have an overloaded operator[] and the same key can be mapped to several different values. To me, this looks like std::multimap is essentialy just something like std::multiset<std::pair<K, V>> with the Compare function operating on the K and we lose the main feature of a map which is the ability to access elements by key (as I see it). I've found this post, but still couldn't comprehend the usecases given here. Could someone please give me several examples when we would use std::multimap?
First note that std::map::operator[] is a little quirky. It is not the way to access elements in the map. Instead std::map::operator[] potentially inserts an element into the map and then returns a reference to either the element that was already present before or to the newly inserted. This may seem like splitting hairs, but the difference matters. The way to access a mapped_value given a key in a std::map is std::map::find. std::multimap has a find as well. No big difference with respect to that. std::map::at has not counterpart in std::multimap because std::map::at returns a reference to the mapped_value for the given key, but in the multimap there can be more than one mapped_value for the same key, so it isnt obvious what a std::multimap::at should return if it existed. Finding and accessing elements can be done with find for both maps. A std::multimap<K,V> can be compared to a std::map<K,std::vector<V>> but with the interface you'd expect when you want to map more than a single value to the same key. For example std::multimap iterators lets you iterate all key-value pairs in the multimap in one go. With the map of vectors you'd have to use the maps iterators and the vectors iterators. Using the map of vectors with standard algorithms is rather cumbersome. Further, std::multimap::count returns the number of elements for a given key. With the map of vectors you would have to first find the vector for given key and call its size. This list is not complete, but I hope the difference gets clear. One example for a multimap could be inhabitants of houses. In the same house lives more than one person. If you want to map street number to person you could use a multimap. More generally, if you have a collection / container of elements and you want to divide them into distinct groups, you can use a multimap. A common use of std::map (or std::unordered_map) is to count frequencies, eg: std::map<int,int> freq; for (const auto& x : some_container) { ++freq[ x % 3 ]; } This counts how many elements of some_container are divisible by 3, without remainder, with remainder 1, or with remainder 2. If you want to know the elements rather than only count them you can use a std::multimap.
73,618,718
73,618,781
What to pass in a class constructor with multiple inheritance?
I just started learning C++ and QT, sorry if this is a weird question. I inherit a class from two classes, each of which has a constructor. How can I correctly pass parameters to these two constructors? I have first class - WirelessSensor class WirelessSensor : public BoxSensor { public: explicit WirelessSensor(const unsigned int id, const QString &type, const QString &address, QObject *parent = nullptr); }; And second class - SwitchSensor class SwitchSensor : public BinarySensor { public: explicit SwitchSensor(const unsigned int id, const QString &type, const bool &inverted, QObject *parent = nullptr); }; This is my inherited class - WirelessSwitchSensor.h class WirelessSwitchSensor : public WirelessSensor, public SwitchSensor { public: explicit WirelessSwitchSensor(const unsigned int id, const QString &type, const QString &address, QObject *parent = nullptr); }; But in the WirelessSwitchSensor.cpp file it highlights the error:[https://i.stack.imgur.com/HQswI.png] In constructor 'WirelessSwitchSensor::WirelessSwitchSensor(unsigned int, const QString&, const QString&, QObject*)': ..\Test\Sensor\wirelessswitchsensor.cpp:4:47: error: no matching function for call to 'SwitchSensor::SwitchSensor()' : WirelessSensor(id, type, address, parent) WirelessSwitchSensor.cpp WirelessSwitchSensor::WirelessSwitchSensor(const unsigned int id, const QString &type, const QString &address, QObject *parent) : WirelessSensor(id, type, address, parent) { } What is the correct way to write a constructor for my inherited class?
It's really simple - you need to call it directly by chaining the initializations in the derived class: struct A { A(int a) { AA=a; } int AA; }; struct B { B(std::string b) { BB=b;} std::string BB; }; struct C : public A, public B { C(int a, std::string b) :A(a), B(b) { } }; Try it yourself :)
73,619,255
73,619,635
Negative number input help-how-to
// ConsoleApplication6.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <limits> int getInput() { while (true) { std::cout << "Indtast fire point-tal mellem 0 og 100: "; int number = 0; int number2 = 0; int number3 = 0; int number4 = 0; std::cin >> number; std::cin >> number2; std::cin >> number3; std::cin >> number4; int sum; sum = (number + number2 + number3 + number4) / 4; std::cout << "\n"; if (std::cin.eof()) { std::cout << "Fejl, prøv igen!\n"; std::cin.clear(); continue; } if (std::cin.bad() || std::cin.fail()) { std::cout << "Ugyldigt input (fejl i input af tal).\n"; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); continue; } if (sum < 0 || sum > 100) { std::cout << "Ugyldigt input, det skal være mellem 0 og 100!.\n"; continue; } return sum; } // unreachable return 0; } int main() { int sum = getInput(); std::cout << "Gennemsnittet af antal point: "; std::cout << sum << std::endl; if (sum >= 90) { puts("Karakter: \n"); puts("12"); } else if (sum >= 80) { puts("Karakter: \n"); puts("10"); } else if (sum >= 70) { puts("Karakter: \n"); puts("7"); } else if (sum >= 60) { puts("Karakter: \n"); puts("4"); } else if (sum >= 50) { puts("Karakter: \n"); puts("02"); } else { puts("Karakter: \n"); puts("00"); } } Currently, my code processes negative inputs the same way as positive inputs. But I would like to implement an "if" that filters negative numbers and come back with an error and maybe also restart the loop. How would I do that? getInput() retrieves 4 numeric inputs, with an error if letters are submitted as input and if the input isn't between 0-100 then it does the same.
you could make a inputPositive function that reads the input and sets a boolean to true if the input number was negative: void inputPositive(int& number, bool& negative) { std::cin >> number; if (number < 0) { negative = true; } } then you can call these functions for the 4 numbers. If negative flag is set we say continue; to return the start of the while(true): while (true) { std::cout << "Indtast fire point-tal mellem 0 og 100: "; bool negative = false; int number = 0; int number2 = 0; int number3 = 0; int number4 = 0; inputPositive(number, negative); inputPositive(number2, negative); inputPositive(number3, negative); inputPositive(number4, negative); if (negative) { std::cout << "Invalid. Input only positive numbers\n\n"; continue; } //... } output: Indtast fire point-tal mellem 0 og 100: 10 20 30 -40 Invalid. Input only positive numbers Indtast fire point-tal mellem 0 og 100: 10 20 30 40 Gennemsnittet af antal point: 25 you should use std::array for your function. It will shorten your code length, and allows to use features like std::accumulate which calculates the sum: bool negative = false; std::array<int, 4> numbers; for (auto& i : numbers) { inputPositive(i, negative); } auto sum = std::accumulate(numbers.begin(), numbers.end(), 0) / numbers.size();
73,619,383
73,726,717
Why does pybind fail for functions without arguments?
I have an overloaded constructor in C++ (default + other). My automatically generated pybind code looks like this: py::class_<MyClass>(m, "MyClass") .def( py::init<>(), py::kw_only() ) .def( py::init< std::valarray<std::string> >(), py::kw_only(), py::arg("my_var") ) When I delete the first constructor everything works fine. But for the first one I get this error: error: static assertion failed: py::kw_only requires the use of argument annotations static_assert(has_arg_annotations || !has_kw_only_args, "py::kw_only requires the use of argument annotations" Does anyone know why this error is coming up and how to fix it? Edit: I am using a custom pybind generator.
Thanks @463035818_is_not_a_number for pointing me in the right direction. I was confused cause I mixed up kw_only with **kwargs. kw_only means, that only named arguments are allowed when calling a function which doesn't make sense without arguments. My custom pybind generator added kw_only to all functions and the build failed because of that. As a solution I added an if-condition to check whether there are function arguments and only added kw_only if there are any: if (args.size() > 0) { out << "\n"; out << ">()," << "\n" << "py::kw_only()";} else { out << ">()"; } The generated pybind code looks like this: py::class_<MyClass>(m, "MyClass") .def( py::init<>() ) .def( py::init< std::valarray<std::string> >(), py::kw_only(), py::arg("my_var") )
73,619,448
73,623,327
Removing copy ctor of 3rd party class
I have a class that stores a large std::map. My understanding is that the idiomatic way to do this is: class Foo { public: Foo(/* Note: passed by value */ std::map<Bar, Baz> large_map) : large_map_(std::move(large_map)) {} private: std::map<Bar, Baz> large_map_; }; int main() { std::map<Bar, Baz> large_map; // Work hard to initialize large_map. Foo foo = Foo(std::move(large_map)); } This transfers the ownership of large_map from main, to the constructor arg and then to Foo's member. The problem with this is that the code is hard to use properly and I discovered that someone somewhere created a Foo and forgot to move the map into the ctor: void deep_dark_hidden_code() { std::map<Bar, Baz> large_map; // Work hard to initialize large_map. Foo foo = Foo(large_map); // Whoops! The author of this code forgot to std::move } I am looking for a way to write Foo which protects against such mistakes. My first thought was to use unique_ptr class Foo { public: Foo(std::unique_ptr<std::map<Bar, Baz>> large_map_ptr) : large_map_(std::move(*large_map_ptr)) {} private: std::map<Bar, Baz> large_map_; }; int main() { std::unique_ptr<std::map<Bar, Baz>> large_map_ptr = new std::map<Bar, Baz>; // Work hard to initialize large_map_ptr. Foo foo = Foo(std::move(large_map_ptr)); } This code is essentially using unique_ptr as a hack to erase the copy constructor of std::map. My question is whether there is a more explicit way to do this. Some magic template make_uncopyable like: class Foo { public: Foo(make_uncopyable<std::map<Bar, Baz>> large_map) : large_map_(std::move(large_map)) {} private: std::map<Bar, Baz> large_map_; }; The desired effect is to leave the code in my main intact but prevent the code in deep_dark_hidden_code from compiling.
The title appears to be a slight misnomer here (or is at least at odds with the contents with your question): (At least in the example given), you do not want to remove the copy constructor i.e. Foo::Foo(const Foo& other), but rather prevent invokation of Foo's constructor with a non-movable argument. As Mestkon pointed out (all credit to them - if they want to post it as an answer, just give me a yell and I'll remove mine), you could change Foo's constructor to require a std::map<Bar, Baz>&& large_map i.e. Foo(std::map<Bar, Baz>&& large_map) : large_map_(std::move(large_map)) {} A test at Godbolt confirms that the compiler will refuse to accept the Foo foo = Foo(large_map); in the deep_dark_hidden_code()., demanding the argument to be movable (as desired). This this might still run the risk of others "fixing" their code by simply slapping a std::move() around their large_map... and then attempting to continue using it after constructing Foo with it. If you want really want to prevent the invokation of the copy constructor (here std::map), things become rather difficult, as you cannot change the the definition std::map to erase its copy constructor. I don't feel I have a good answer to this.
73,619,926
73,742,332
Random error in exe_common.inl in Debug build
I am using VS 2022 Community Edition (v17.3.3) to build wxWidgets application (v3.2.0) using C++ (v14.3 - Features from Latest C++). The windows SDK is using the latest installed (10.0.22621). The project is also using C++ modules. The Debug build succeeds but when I run the project's exe file at random it throws the exception (Access violation reading 0xFFFFFF (ucrtbased.dll)) in exe_common.inl at the following line: __scrt_current_native_startup_state = __scrt_native_startup_state::initialized; After a few more compilations (by just making minor changes to trigger a compilation) it succeeds and the exe runs correctly. I wonder if there is any settings that might be causing this random error. Btw, I am using Win11 but same thing happens on Win10 as well. Thanks in advance. EDIT 1: The project is using boost libraries and at startup boost/json (boost/json is used in other parts of the project as well). Debugger shows that after the following line the above error happens: static allocator_arg_t allocator_arg = BOOST_CONTAINER_DOC1ST(unspecified, *std_allocator_arg_holder<>::dummy);
There were a few things needed attention: Discontinued use of wxSQLite (the library was not maintained for over a decade), The main frame was a singleton data structure, not anymore, and not deriving from wxMDIFrame anymore. All unnecessary (a chain of them) #include removed. Inclusion of <boost/json.hpp> in a few files were removed and now using #include <boost/json/src.hpp> only in one .cpp file. However, the project still uses inclusion of <boost/json/value.hpp> in multiple .h files. All uninitialized pointer variables and others were initialized. #1 and #4 were especially pointed by the debugger. It has now been more than a few days and haven't had the problem since then.
73,619,994
73,620,044
How to initialize a struct with two std::array members?
I can initialize a struct with a single std::array element using a variadic template constructor: #include <array> #include <initializer_list> #include <memory> struct Foo { using data_type = int; using foo_type = std::array<data_type,2>; using init_type = std::initializer_list<data_type>; template <typename... T> Foo(T... array) : array_{array...} {} foo_type array_; }; int main() { Foo foo {1,2}; // this works std::unique_ptr<Foo> foo2 = std::make_unique<Foo>(3,4); // this also works! return 0; } This works fine! But how can I do the initialization if I have more than a single array member in Foo ? I tried the following which does not work: #include <array> #include <initializer_list> #include <memory> struct Foo { using data_type = int; using foo_type = std::array<data_type,2>; using init_type = std::initializer_list<data_type>; template <typename T> Foo(T array1, T array2) : array1_{init_array(array1)}, array2_{init_array(array2)} {} template <typename... T> constexpr auto init_array(T... array) { return array...; } foo_type array1_, array2_; }; int main() { Foo foo {{1,2},{3,4}}; return 0; } This gives an error: test.cpp: In member function ‘constexpr auto Foo::init_array(T ...)’: test.cpp:12:16: error: parameter packs not expanded with ‘...’: 12 | return array...; | ^~~~~
Just specify the parameters as arrays themselves: struct Foo { using data_type = int; using foo_type = std::array<data_type,2>; using init_type = std::initializer_list<data_type>; Foo(const foo_type &arr, const foo_type &arr2): array1_{ arr }, array2_{ arr2 } {} foo_type array1_, array2_; };
73,620,242
73,620,608
Do I need a transaction for multiple queries in one string?
https://github.com/SRombauts/SQLiteCpp SQLite::Database db("example.db3"); while(...) { db.exec("INSERT INTO xxx VALUES(...)"); } It's sample code for SQLite to insert data. If there's no transaction, each db.exec is slow, almost takes 1 second. So, you need a transaction : db.exe("BEGIN"); while(...) { db.exec("INSERT INTO xxx VALUES(...)"); } db.exe("END"); But if I make all queries into one string: db.exec("INSERT INTO xxx VALUES(...);\ INSERT INTO xxx VALUES(...);\ INSERT INTO xxx VALUES(...);\ ... "); Do I still need a transaction?
If you want to insert 'everything' or 'nothing', then, YES. You still need a transaction. SQLite::Database::exec() internally calls sqlite3_exec() and semicolon separated SQL statement will not be executed atomically without a transaction.
73,620,656
73,620,713
Passing image to function as a char array in C++ and display with SFML
I'm aware there are similar posts already but I just couldn't find anything that solved my problem. I have my image stored as a char array of hex numbers and I am trying to pass this to a function that loads that data from memory in order to read the data and display the image. When I write the array name directly into the code, the image displays as I need it to, but I want to be able to use different images without writing a function for each one. I'm no expert with pointers and addresses so maybe this is where my mistake is but I've tried so many things and just can't figure it out. I'm working with the SFML graphics library so that's where some of the commands are from. My image data array (in spritePNG.h): #pragma once const unsigned char spritePNG[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x64, 0x08, 0x06, 0x00, 0x00, 0x00, 0x70, 0xe2, 0x95, 0x54, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x05, 0xc8, 0x69, 0x54, 0x58, 0x74, 0x58, 0x4d, 0x4c, 0x3a, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x64, 0x6f, 0x62, 0x65, 0x2e, 0x78, 0x6d, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, .... }; Header file for necessary function (IconSprite.h): #pragma once #include <SFML/Graphics.hpp> #include <iostream> #include <string> using namespace std; using namespace sf; class IconSprite { private: Texture texture; Sprite sprite; public: IconSprite(){} ~IconSprite(){} Sprite loadSpriteResource(const unsigned char image[], float scale); Sprite getSprite(); }; My function to load it from memory (in IconSprite.cpp): #include "IconSprite.h" #include "spritePNG.h" Sprite IconSprite::loadSpriteResource(const unsigned char image[], float scale) { // load sprite resource image into texture //if (!texture.loadFromMemory(spritePNG, sizeof(spritePNG))) /* when line above is used, it runs fine but then function is only useful for displaying that one image */ if (!texture.loadFromMemory(image, sizeof(image))) { cout << "Cannot locate sprite image file" << endl; } // set texture settings texture.setSmooth(true); sprite.setTexture(texture); // set scale and origin sprite.setScale(scale, scale); sprite.setOrigin(sprite.getLocalBounds().width / 2, sprite.getLocalBounds().height / 2); return sprite; } My main.cpp which calls the function: int main() { RenderWindow window(VideoMode(1280, 720), "Asteroids"); window.setFramerateLimit(60); Vector2f windowSize = (Vector2f)window.getSize(); IconSprite iconSprite; Sprite splashSprite = iconSprite.loadSpriteResource(splashPNG, 0.6f); Sprite sprite = iconSprite.loadSpriteResource(spritePNG, 0.6f); sprite.setPosition(windowSize.x / 2, windowSize.y / 2); splashSprite.setPosition(windowSize.x / 2, 100); ... I haven't included the full main() function as this is the only section of it that is relevant and I don't want to make this question longer than it already is. splashPNG is another image that is stored in the same way as spritePNG. Currently the images don't load at all and it gives me the following error: Failed to load image from memory. Reason: Corrupt PNG Each time I check if it is truly corrupt or not by writing the array name directly into the code and it displays perfectly which tells me it's not actually corrupt. This has been really bugging me so any help at all is really appreciated!
You can't pass arrays like that to function. What you're passing is only a pointer to the first element of the array. And the sizeof of a pointer is the size of the pointer itself, not what it actually points to. All of this means that for the loadSpriteResource function the argument is really const unsigned char* image and that sizeof(image) will not give you the expected result. Either use another container (std::array for example) or pass the size as an argument to the function. Optionally you could use templates to pass a reference to the array with its exact size, but I still recommend using std::array.
73,620,711
73,620,956
Create a tuple of successive elements of a vector divided by each other
I have a member variable of a class, offsets, which is a vector with at leastN+1 elements. I would like to create a member function which will return a tuple with N entries with values of successive elements of the vector divided by each other. An example is shown below for a specific instance of this function when N=3. std::tuple<3> get_shape() { return std::make_tuple(offsets[N]/offsets[N-1], offsets[N-1]/offsets[N-2], offsets[N-2]/offsets[N-3]); } Is there a way that this sequence can be generalized to implement the function std::tuple<N> get_shape()?
You can implement this with std::index_sequence. template<size_t N> struct foo { std::array<double, N + 1> offsets; auto get_tuple() const { auto make_tuple = [this]<typename I, I... idx>(std::index_sequence<idx...>) { return std::make_tuple((offsets[N - idx] / offsets[N - idx - 1])...); }; return make_tuple(std::make_index_sequence<N>()); } }; std::make_index_sequence<N> turns into std::index_sequence<0, 1, 2, ... N - 1>. This can be applied on a templated lambda since c++20. Where we can access 0, 1, 2, ... N - 1 via the variadic I... idx. Now saying ... inside std::make_tuple will unpack all the idx numbers into N arguments int main() { foo<3> f = { 2, -4, 7, 1 }; auto tuple = f.get_tuple(); static_assert(std::is_same_v<decltype(tuple), std::tuple<double, double, double>>); std::apply([](auto&&... rest) { ((std::cout << rest << " "), ...); }, tuple); } output: 0.142857 -1.75 -2
73,621,975
73,622,641
Does taking a reference to an object via two different base classes violate strict aliasing rule?
I have three pure virtual classes, let's call them ServiceA, ServiceB and ServiceC. The concrete implementation provides all three services using multiple inheritance: class Concrete : public ServiceA, public ServiceB, public ServiceC { //... }; It is possible that the services could also be provided by separate concrete classes (single inheritance), so to make use of the services, I'm thinking to write a class like so: class Consumer { public: Consumer(const ServiceA& svcA, const ServiceB& svcB); }; If instantiate my class as shown below, will that be a violation of the strict aliasing rule? Concrete multiService; Consumer consumer(multiService, multiService);
If instantiate my class as shown below, will that be a violation of the strict aliasing rule? Strict aliasing rule doesn't break because svcA and svcB do not refer to the same address in the memory. When you refer to base classes, you actually refer to subobjects of the complete class Consumer, where each has its own offset (which might be more than zero), and thus different addresses even for the same instance of Consumer.
73,623,523
73,625,748
Why is my program continuing on the setw value which I have set for the previous cout statements? And this is happening in a pattern too?
This is my code: #include <iostream> #include <string> #include <iomanip> using namespace std; int main() { int n1 = 1, n2 = 2; cout << setw(5) << n1 << endl; cout << setw(6) << n1 << " " << n2 << endl; cout << setw(7) << n1 << " " << n2 << endl; cout << setw(8) << n1 << " " << n2 << endl; cout << setw(9) << n1 << " " << n2 << endl; cout << setw(8) << n1 << " " << n2 << endl; cout << setw(7) << n1 << " " << n2 << endl; cout << setw(6) << n1 << " " << n2 << endl; cout << setw(5) << n1 << endl; return 0; } This is my output: However, my intended output is: what's wrong in my code?
You just put the numbers in wrong order, try this: int main() { int n1 = 1, n2 = 2; cout << setw(9) << n1 << endl; cout << setw(8) << n1 << " " << n2 << endl; cout << setw(7) << n1 << " " << n2 << endl; cout << setw(6) << n1 << " " << n2 << endl; cout << setw(5) << n1 << " " << n2 << endl; cout << setw(6) << n1 << " " << n2 << endl; cout << setw(7) << n1 << " " << n2 << endl; cout << setw(8) << n1 << " " << n2 << endl; cout << setw(9) << n1 << endl; return 0; }
73,624,093
73,624,425
Stack Smashing detected while implementing mergeSort in C++14
I am implementing standart MergeSort algorithm. I am getting a runtime error 'Stack Smashing Detected'. What is the root cause of such error and how to prevent my code from this error? I saw that the control is coming to merge function , but somewhere it is getting messed up. #include<iostream> using namespace std; //this particular function will merge 2 sorted array void merge(int arr[], int res[], int low, int mid, int high) { int i=low,j=mid+1,k=high; while(i<=mid && j<=high) //make sure that i remains within the end if left subarray and j remains within the end of right subarray { if(arr[i]<=arr[j]) res[k++]=arr[i++]; else res[k++]=arr[j++]; } while(i<=mid) // In case there are some elements left in left subarray, just copy it into result res[k++]=arr[i++]; while(j<=high) //// In case there are some elements left in right subarray, just copy it into result res[k++]=arr[j++]; //copy the result into original array for( i=low;i<=high;i++) arr[i]=res[i]; } void mergeSort(int arr[], int res[], int low, int high) { //Don't forget to put the base case in recursion if(high == low) return; int mid = low + (high-low)/2; mergeSort(arr,res,low,mid); mergeSort(arr,res,mid+1,high); merge(arr,res,low,mid,high); cout<<"end of recursion"<<endl; } int main() { int arr[] = {8,4,3,12,25,6,13,10}; // initialise resultant array (temporary) int res[]= {8,4,3,12,25,6,13,10}; for(int i=0 ;i<8 ; i++) cout<<arr[i]<<" "; cout<<endl; mergeSort(arr,res,0,7); for(int i=0 ;i<8 ; i++) cout<<arr[i]<<" "; cout<<endl; }
The problem is in your merge routine. If you look at the case where low and mid are 6 and high is 7, which will happen towards the end of the recursion, the loop while (i <= mid) res[k++] = arr[i++]; will end up executing with k being out-of-bounds. I think you meant for k to be initialized to low because it is supposed to be in sync with i.
73,624,398
73,625,445
Call to implicitly deleted default constructor when instantiating unordered_map<const char, std::string>
I'm trying to instantiate an std::unordered_map<const char, std::string>: std::unordered_map<const char, std::string> cities = { {'A', "Amsterdam"}, {'B', "Berlin"}, {'C', "Canberra"} }; This fails with error: call to implicitly-deleted default constructor of 'std::unordered_map<const char, std::basic_string<char>>::hasher'. It looks like std::hash can't hash const char, but I can't find anything which would confirm it. Why doesn't it work?
As stated in documentation for std::hash it is implemented through template specialization: Each specialization of this template is either enabled ("untainted") or disabled ("poisoned"). The enabled specializations of the hash template defines a function object that implements a hash function. Instances of this function object satisfy Hash. In particular, they define an operator() const that... And in section "Standard specializations for basic types" only types like char, int etc are listed, not their const variants. As template specialization for non-const and const versions are different those specializations do not work for const types. So you either need to provide your own specialization for const char or just use std::uinordered_map<char,std::string> which should be used anyway.
73,624,769
73,625,020
C++ template function recursive
I have a function that calculate determinant of a matrix. My matrix class is like this: template <int Col, int Row, typename T> class Matrix; I have implemented 3 specific function for Mat<1, 1, T>, Mat<2, 2, T>, Mat<3, 3, T>: template <typename T> float Determinant(const Matrix<1, 1, T>& mat); template <typename T> float Determinant(const Matrix<2, 2, T>& mat); template <typename T> float Determinant(const Matrix<3, 3, T>& mat); And now i want to have a function that calculate determinant of matrices those have dimension higher than 3x3. I have tried to implement it like this: template <int Dim, typename T> float Determinant(const Matrix<Dim, Dim, T>& mat) { float result = 0; for (int i = 0; i < Dim; ++i) { // This function return a minor matrix of `mat` Matrix<Dim - 1, Dim - 1, T> minor = mat.GetMinorMatrix(i, 0); result += (i & 1 ? -1 : 1) * mat(i, 0) * Determinant(minor); } } // I try to use that function Matrix<1, 1, float> mat { 1.0f }; Determinant(mat); // Error occurred here But somehow my compiler keeps crashing while i try to build that code. And my IDE reports this error: In template: recursive template instantiation exceeded maximum depth of 1024. That error will be disappeared when i delete the function template <int Dim, typename T> float Determinant(const Matrix<Dim, Dim, T>& mat). Why does that error happen, and how can i fix it?
Imagine you instantiate Determinant with Dim = 0. Your compiler will try to instantiate Determinant<-1>, which will then again instantiate Determinant<-2>, and so on. At some point you will reach the maximum 1024. A minimal reproducible example could look like: template <int I> void foo() { foo<I - 1>(); } int main() { foo<5>(); } You can fix this is in different ways. The more modern approach would check for the final recursive call: template <int I> void foo() { if constexpr (I > 0) { foo<I - 1>(); } else { // however you want to deal with I = 0 } } Or by using template pattern matching: template <int I> void foo() { foo<I - 1>(); } template <> void foo<0>() { // however you want to deal with I = 0 }
73,624,899
73,624,945
C++ error C2280. Why struct is non-copyable
I have a struct inside header file in C project. struct tgMethod { const char *name; const enum tgAccessModifier access; const enum tgMethodKind kind; tgTypeRef return_type; const tgParams params; const tgMethod *overrides; const void *userptr; const tgObject *(*methodptr)(tgObject *, size_t, tgObject *, void *); }; In C++ project which links this C project I have this struct which using as EntryAllocator<tgMethod> but compiler gives error: error C2280: "tgMethod &tgMethod::operator =(const tgMethod &)": attempting to reference a deleted function template<typename T> struct EntryAllocator { public: EntryAllocator() : EntryAllocator(1 << 7) { } explicit EntryAllocator(size_t max_size) : _start(0), _count(0), _capacity(max_size), _data((T*)calloc(max_size, sizeof(T))) { } ~EntryAllocator() { free(_data); } void Begin() { _start += _count; // move '_start' to the end of filled data _count = 0; } void Append(T elem) { _data[_count++] = elem; if (_start + _count > _capacity) { _capacity <<= 1; // *= 2 but faster _data = (T*) realloc(_data, _capacity * sizeof(T)); } } void End(T **out_data, size_t &count) { *out_data = &_data[_start]; count = _count; } void Trim() { _capacity = _start + _count; _data = (T*) realloc(_data, _capacity * sizeof(T)); } [[nodiscard]] size_t GetCapacity() const { return _capacity; } [[nodiscard]] size_t GetCount() const { return _count; } [[nodiscard]] size_t GetLength() const { return _count + _start; } [[nodiscard]] T* GetRawData() const { return _data; } private: size_t _start; size_t _count; size_t _capacity; T* _data; }; Why tgMethod is non-copyable? What I need to change to fix this error and save the logic of program?
Why tgMethod is non-copyable? tgMethod can be copied, via copy construction, but it is not assignable. Your class tgMethod has several const members. const enum tgAccessModifier access; const enum tgMethodKind kind; const tgParams params; const members can not change, therefore a constructed tgMethod object can not entirely change. Since tgMethod::operator =(const tgMethod &) would change the object, it can not be default-implemented, and the compiler chooses to delete this function. What I need to change to fix this error You can make the members non-const. Or you can manually implement your own tgMethod::operator =(const tgMethod &) that somehow achieves your "assignment" without modifying the const members.
73,625,050
73,626,597
What is the most efficient way to compare two QStringList in QT?
I have two String Lists and I already have a function that compares two lists to find out which elements of list 2 do not exist in list 1. This block of code works, but maybe it is not the best way to achieve it, there are any other way to get the same result without performing so many iterations with nested loops? QStringList list1 = {"12420", "23445", "8990", "09890", "32184", "31111"}; QStringList list2 = {"8991", "09890", "32184", "34213"}; QStringList list3; for (int i = 0; i < list2.size(); ++i) { bool exists = false; for (int j = 0; j < list1.size(); ++j) { if(list2[i] == list1[j]){ exists = true; break; } } if(!exists) list3.append(list2[i]); } qDebug() << list3; output: ("8991", "34213") Perhaps this small example does not seem like a problem since the lists are very small. But there might be a case where both lists contain a lot of data. I need to compare these two lists because within my app, every time a button is clicked, it fetches an existing dataset, then runs a function that generates a new data (including existing ones, such as a data refresh), so I need to get only those that are new and didn't exist before. It might sound like strange behavior, but this is how the app works and I'm just trying to implement a new feature, so I can't change this behavior.
If you switch to QSet<QString>, your code snippet boils down to: auto diff = set2 - set1; If the input and output data structures must be QStringLists, you can still do the intermediate computation with QSets and still come out ahead: auto diff = (QSet::fromList(list2) - QSet::fromList(list1)).toList();
73,625,801
73,625,902
Undefined reference to info()
So basically I was given an assignment to write a program that uses three arrays, one to store the given names and the other two to output whether an Employ will be an Attendee at a conference. The employee is allowed to attend both sessions. (We are not allowed to use pointers, referencing or structs) This is what I have written so far but I get the error: undefined reference to `info(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >*, int, int)' Any tips on how to fix it? #include <iostream> #include <iomanip> #include <string> #include <cctype> #include <stdio.h> using namespace std; //Function initialization bool info(string Names[10], int num, int pos); void display(string Names[10], bool sesA[10], bool sesB[10]); void totalAttendees(bool tempA[10], bool tempB[10]); //Main program int main() { //Variable declaration string arrNames[10] = {"Cindy Hess", "David Thornton", "Amanda Bryan", "Claudia Newton", "Heather Snyder", "Amy Rodriguez", "Kerry Ellis", "Yolanda Mccullough", "Summer Price", "Sandra Carter"}; bool SessionA[10], SessionB[10]; char choice, ses; int att, ctr, session; ctr = 0; //Input loops for SessionA & SessionB for (int i = 0; i < 10; i++) { SessionA[i] = info(arrNames, ctr, i); } ctr++; for (int i = 0; i < 10; i++) { SessionB[i] = info(arrNames, ctr, i); } //While loop for editing SessionA & SessionB cout << "Would you like to edit a session?(Y-yes / N-no): "; cin >> choice; while (toupper(choice) == 'Y') { cout << "Which Attendee would you like to edit: "; cin >> att; cout << "Which Session would you like to edit(A / B): "; cin >> ses; cout << "Update session(1-accept / 2-decline): "; cin >> session; if (toupper(ses) == 'A') { if (session == 1) { SessionA[att] = true; } else if (session == 2) { SessionA[att] = false; } } else if (toupper(ses) == 'B') { if (session == 1) { SessionB[att] = true; } else if (session == 2) { SessionB[att] = false; } } cout << "Would you like to edit a session?(Y-yes / N-no): "; cin >> choice; } totalAttendees(SessionA, SessionB); return 0; } //Info Function bool info (string Names, int num, int pos) { string s; bool choice; if (num == 0) { s = "SESSION A"; } else if (num == 1) { s = "SESSION B"; } cout << (pos + 1) << ". " << Names[pos] << "are they going to attend " << s << "(1-accept / 2-decline): "; cin >> num; if (num == 1) { choice = true; } else if (num == 2) { choice = false; } return choice; } //Display Function void display (string Names[10], bool sesA[10], bool sesB[10]) { cout << "# " << "Attendee\t\t" << "Session A\t" << "Session B" << endl; for (int i = 0; i < 10; i++) { printf("%n. %2s %10b %5b\n", i + 1, Names[i], sesA[i], sesB[i]); } } //Total attendees function void totalAttendees (bool sesA[10], bool sesB[10]) { int total = 0; for (int i = 0; i < 10; i++) { if (sesA[i] == true && sesB[i] == true) { total++; } else if (sesA[i] == true) { total++; } else if (sesB[i] == true) { total++; } } cout << "The total Attendees: " << total; }
You are just missing this - [10] in your function definition. //Info Function bool info(string Names[10], int num, int pos) { ... }
73,626,013
73,626,584
std::variant does not seem to work with shared_ptr in C++
With the code below, I'm getting: In static member function ‘static std::shared_ptr<std::variant<MyClass<InputClass1>, MyClass<InputClass2> > > MyCreatorClass::create()’: main.cpp:34:57: error: could not convert ‘std::make_shared(_Args&& ...) [with _Tp = MyClass; _Args = {}]()’ from ‘shared_ptr>’ to ‘shared_ptr, MyClass >>’ Code: #include <iostream> #include <variant> #include <memory> using namespace std; struct InputClass1{ static std::string MyName(){ return "InputClass1"; } }; struct InputClass2{ static std::string MyName(){ return "InputClass2"; } }; template<class InputClass> class MyClass{ public: MyClass(){ std::cout<<InputClass::MyName(); } }; class MyCreatorClass{ using VariantType = std::variant<MyClass<InputClass1>, MyClass<InputClass2>>; public: static std::shared_ptr<VariantType> create(){ return std::make_shared<MyClass<InputClass2>>(); } // Am I using the variant the right way here? }; int main() { cout<<"Hello World"; MyCreatorClass::create(); return 0; }
static std::shared_ptr<VariantType> create() this is a function that returns a shared pointer to a variant over MyClass<InputClass1>, MyClass<InputClass2>. { return std::make_shared<MyClass<InputClass2>>(); } this is a function body that returns a shared pointer to a MyClass<InputClass2>. These two types are unrelated. A pointer to a X cannot be converted to a pointer to a variant which includes an X. Your code basically requests this to happen. It is possible you want a variant over shared pointers instead of a shared pointer of a variant. It is possible you want to make a shared pointer to a variant, and initialize it with a specific alternative. Both of these are allowed. What you are doing is not. In pseudo code, you have a sp[var[A|B]] and are initializing it with a sp[A]. You need to either use the type var[sp[A]|sp[B]] or you need to initialize it with a sp[var[A]] to be structurally compatible. ... Finally, I see some bad signs. The default use of shared_ptr is a bad sign, especially if you don't understand how C++ pointer types well enough to see the problem here. Shared lifetime management and ownership of mutable objects seems like it makes problem simpler, but really it hides problems until your system is more complex, and then makes it very difficult to track down why you have a problem.
73,626,367
73,626,770
use std::accumulate to add an array to only a vector slice
I have following code std::vector<float> d; d.resize(800); std::array<float, 8> adder; int ind_slice = 5; // we want to add the array adder to v[40],v[41] ... v[47] const auto it_begin = d.begin() + ind_slice *8; const auto it_end = d.begin() + ind_slice *8 + ind_slice; int index = 0; std::accumulate(it_begin, it_end) [&] ( float* ind) { return ind = ind + (adder[index++])}; I am wondering if this is a safe way to do the accumulation, since I am captuing a reference from the outside and mutating it. So the function does have side effects. Is there a better way to use the accumulate to achieve my objective
At least if I understand your intent correctly, the algorithm to use here would almost certainly be std::transform, not std::accumulate. accumulate is intended for taking some collection, and simply adding them up, roughly equivalent to sum() in a spreadsheet (for one example). transform allows you (among other things) to combine two collections, about the way you seem to want to. #include <vector> #include <array> #include <algorithm> #include <iterator> #include <iostream> int main() { std::vector<float> d; d.resize(800); std::array<float, 8> adder { 1, 2, 3, 4, 5, 6, 7, 8}; size_t start = 40; const auto it_begin = d.begin() + start; const auto it_end = d.begin() + start + adder.size(); // do the addition: std:transform(it_begin, it_end, adder.begin(), it_begin, [](float a, float b) { return a + b; }); // show the modified part of the array. std::copy(it_begin, it_end, std::ostream_iterator<float>(std::cout, "\n")); } I've taken the liberty of simplifying a bit of the other code as well, but not in ways that are likely to matter much here. Since you only need an iterator to the beginning of the second collection, you can simplify the code a bit further if you want, by using adder as the first collection, and the slice of d as the second: #include <vector> #include <array> #include <algorithm> #include <iterator> #include <iostream> int main() { std::vector<float> d; d.resize(800); std::array<float, 8> adder { 1, 2, 3, 4, 5, 6, 7, 8}; size_t start = 40; const auto it_begin = d.begin() + start; std:transform(adder.begin(), adder.end(), it_begin, it_begin, [](float a, float b) { return a + b; }); std::copy(it_begin, it_begin+adder.size(), std::ostream_iterator<float>(std::cout, "\n")); } As it stands right now, we still use an iterator to the end of the affected portion of d when we print things out, but that was added just to make it clear that we'd actually done something, not to fulfill any real requirement.
73,626,694
73,626,842
Getting first 5 even numbers element from vector after reverse const iteration
I have this code below that generates 15 random integers and uses them to initialize my vector, intVec. What I'm trying to do here is to iterate through the vector in reverse order and only print out the first 5 even numbers encountered while iterating. I tried using the erase method to just print the first 5 elements but it keeps throwing me an exception error that says: can't decrement vector iterator before begin One of the requirements is that I have to use the const_reverse_iterator. Is there any simpler way to accomplish this? int main() { default_random_engine randObj; vector<int> intVec; for (int i = 0; i < 15; i++) { intVec.push_back(randObj()); } vector<int>::const_reverse_iterator iter; for (iter = intVec.rbegin(); iter < intVec.rend(); ++iter) { if (*iter % 2 == 0) { intVec.erase(intVec.begin()+5, intVec.end()); cout << *iter << endl; } } };
The requirement of having to use the const_reverse_iterator (note the "const") should be telling you that modifying the vector is not allowed. And nor is it even necessary: just use that iterator and run through the vector, printing out the elements that are even and, when doing so, incrementing a "counter" variable. When (or, technically, "if") that counter reaches 5, you can break out of the loop. Note also that the const_reverse_iterator functions are crbegin() and crend(). Like this, for example: #include<iostream> #include <vector> #include <random> int main() { std::default_random_engine randObj; std::vector<unsigned> intVec; for (int i = 0; i < 15; i++) { intVec.push_back(randObj()); } int count = 0; std::vector<unsigned>::const_reverse_iterator iter; for (iter = intVec.crbegin(); iter != intVec.crend(); ++iter) { if (*iter % 2 == 0) { std::cout << *iter << "\n"; if (++count == 5) break; } } return 0; }
73,627,187
73,627,458
Can I specify the radius of each corner of a rounded rectangle?
In Direct2D, rounded rectangle geometry can be created this way: D2D1_ROUNDED_RECT rq = {0}; rq.rect.left = 0; rq.rect.top = 0; rq.rect.right = 100; rq.rect.bottom = 100; rq.radiusX = 5; rq.radiusY = 5; factory->CreateRoundedRectangleGeometry(rq, &geometry); Where radiusX and radiusY are confusing me, because I can't understand how two values can independently describe 4 (4 rectangle corners radiuses). Can I set each corner's radius separately like that, or do I need to do it manually using CreatePathGeometry() instead?
According to the documentation, radiusX and radiusY are the radii for the quarter ellipse that are drawn in every corner. You are not specifying the radius for every corner but for all of them at once. When radiusX is larger than radiusY, it's essentially a rounded rectangle that looks "squished". If the radii are larger or equal to the half size of the rectangle, it'll be drawn like a regular ellipse that you would draw with D2D1_ELLIPSE.
73,627,348
73,627,384
Why is the text of the file displayed twice
I have been working on a project which needs to read the text from a .txt file. But I get the text displayed in the console twice. Here is the CreateFiles.cpp #include "CreateFiles.h" void createF() { std::fstream fs{ "C:\\Users\\bahge\\source\\repos\\Education\\Education\\myfile.txt" }; std::string s; while (fs) { std::getline(fs, s); std::cout << s << std::endl; } } And the CreateFiles.h #pragma once #ifndef CREATE_FILES #define CREATE_FILES #include <iostream> #include <fstream> #include <string> void createF(); #endif // !CREATE_FILES Here is the file's content StackOverflow And the output from the console StackOverflow StackOverflow C:\Users\bahge\source\repos\Education\x64\Debug\Education.exe (process 39072) exited with code 0. Press any key to close this window . . .
You are encountering a variation of Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?. You are ignoring the stream's state after getline() returns. Your file has only 1 line in it, so s is not valid (and in your case, is unchanged) after the 2nd read fails, but you are not handling that condition correctly, so you are printing s when you should not be. You need to change your loop from this: while (fs) { std::getline(fs, s); std::cout << s << std::endl; } To this instead: while (std::getline(fs, s)) { std::cout << s << std::endl; }
73,627,351
73,627,809
Find unique element in sorted array using c++
I am trying to find unique element from the array these is question Input : arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5} Output : arr[] = {1, 2, 3, 4, 5} They give me correct output but why they give 0 at the end in output: these is my output: {1,2,3,4,5,0} Code: #include<iostream> using namespace std; int main(){ int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}; int n=sizeof(arr)/sizeof(arr[0]); int c=0; for(int j=0;j<=n;j++){ if(arr[j]!=arr[j+1]){ cout<<arr[j]; } } }
Except for std::cout, you code is much more C than ++. std::unique of the C++ Standard Library does exactly what you want. There is no need to re-implement this. Next there is the erase-remove idiom to delete the superfluous elements. For the output, you can use std::for_each() or at least a range-based for loop. And also, you don't want using namespace std; A more modern solution looks like this: #include <iostream> #include <algorithm> #include <vector> int main(){ std::vector<int> arr {1, 2, 2, 3, 4, 4, 4, 5, 5}; auto last = std::unique(arr.begin(), arr.end()); arr.erase(last, arr.end()); std::for_each(arr.begin(), arr.end(), [](int n){std::cout << n << std::endl;} ); } Try it on Godbolt.
73,628,029
73,628,529
Java shared library generated from C++ code
I'm trying to run C++ code in java using the java wrapper to generate such code, I've successfully generated all the code and implemented it in my code, but when I try to compile, I get an architecture error Can't load this .dll (machine code=0x7) on a AMD 64-bit platform I'm running java 1.8.0_022, the PC I'm running the code in is a Intel 64 bit platform and I've tried to run the code in a 64 bit AMD computer and get the same error any help to run C++ code in java? Either to run it like this with a shared library or any other method
The typical solution to run C++ code in Java is with Java Native Interfaces (JNI) https://docs.oracle.com/javase/8/docs/technotes/guides/jni/ You might also want to check SWIG that makes the C++/JNI integration much easier. https://www.swig.org/Doc1.3/Java.html As user @KCWong added in the comments, there's also JNA (github.com/java-native-access/jna). Easier to use but runs much slower than JNI. JavaCCP (github.com/bytedeco/javacpp) is another alternative, it is said to be about as fast as JNI.
73,628,084
73,628,271
Why am i getting seg. fault?
I'm starting with pointers, and I can't see the reason why I'm getting a segfault with this code. I guess I'm accessing the array the wrong way, so how should I access it? const int MAXIMO_LIBROS_INICIAL = 20; typedef struct { string titulo; char genero; int puntaje; } libro_t; int main(){ libro_t** libros = new libro_t*[MAXIMO_LIBROS_INICIAL]; int tope_libros = 0; libros[tope_libros]->titulo = "hola"; return 0; }
You are creating an array of pointers that don't point anywhere. You are getting a segfault from trying to access invalid memory. You need to create the individual objects that the pointers will point at, eg: const int MAXIMO_LIBROS_INICIAL = 20; struct libro_t { string titulo; char genero; int puntaje; }; int main(){ libro_t** libros = new libro_t*[MAXIMO_LIBROS_INICIAL]; for (int i = 0; i < MAXIMO_LIBROS_INICIAL; ++i) { libros[i] = new libro_t; } int tope_libros = 0; libros[tope_libros]->titulo = "hola"; ... for (int i = 0; i < MAXIMO_LIBROS_INICIAL; ++i) { delete libros[i]; } delete[] libros; return 0; } Though, you really have 1 level of indirection too many, and should drop one level of *, eg: const int MAXIMO_LIBROS_INICIAL = 20; struct libro_t { string titulo; char genero; int puntaje; }; int main(){ libro_t* libros = new libro_t[MAXIMO_LIBROS_INICIAL]; int tope_libros = 0; libros[tope_libros].titulo = "hola"; ... delete[] libro_t; return 0; } That being said, consider using std::vector or std::array instead, let them manage the memory for you, eg: #include <vector> // or: <array> const int MAXIMO_LIBROS_INICIAL = 20; struct libro_t { string titulo; char genero; int puntaje; }; int main(){ std::vector<libro_t> libros(MAXIMO_LIBROS_INICIAL); // or: std::array<libro_t, MAXIMO_LIBROS_INICIAL> libros; int tope_libros = 0; libros[tope_libros].titulo = "hola"; ... return 0; }
73,628,107
73,629,611
RegexReplace different output according to compiler
LIVE #include <iostream> #include <regex> int main() { std::string text = R"(11111111111111111111 11111111111111111111 11111111111111111111 11111111111110000000 11111111111000000000 11111111100011111100 11111111100111100000)"; std::regex re("^1+\n"); std::string str = std::regex_replace(text, re, ""); std::cout << str; return 0; } Why does the exact same code when compiled under visual studio, trims all lines containing 11111111111111111111? I would like to it behave the same as on the link above, replacing just the first occurrence. Do i need any kind of 'special' flag into the regex?
I modified my answer. It might be a compiler difference. You can refer to the flags and similar thread. std::regex_constants::match_flag_type fonly = std::regex_constants::format_first_only; std::regex re("^1+\n"); std::string str = std::regex_replace(text, re, "", fonly);
73,628,314
73,628,451
reinterpret_cast a slice of byte array?
If there is a buffer that is supposed to pack 3 integer values, and you want to increment the one in the middle, the following code works as expected: #include <iostream> #include <cstring> int main() { char buffer[] = {'\0','\0','\0','\0','A','\0','\0','\0','\0','\0','\0','\0'}; int tmp; memcpy(&tmp, buffer + 4, 4); // unpack buffer[5:8] to tmp std::cout<<buffer[4]; // prints A tmp++; memcpy(buffer + 4, &tmp, 4); // pack tmp value back to buffer[5:8] std::cout<<buffer[4]; // prints B return 0; } To me this looks like too many operations are taking place for a simple action of merely modifying some data in a buffer array, i.e. pushing a new variable to the stack, copying the specific region from the buffer to that var, incrementing it, then copying it back to the buffer. I was wondering whether it's possible to cast the 5:8 range from the byte array to an int* variable and increment it, for example: int *tmp = reinterpret_cast < int *>(buffer[5:8]); (*tmp)++; It's more efficient this way, no need for the 2 memcpy calls.
The latter approach is technically undefined, though it's likely to work on any sane implementation. Your syntax is slightly off, but something like this will probably work: int* tmp = reinterpret_cast<int*>(buffer + 4); (*tmp)++; The problem is that it runs afoul of C++'s strict aliasing rules. Essentially, you're allowed to treat any object as an array of char, but you're not allowed to treat an array of char as anything else. Thus to be fully compliant you need to take the approach you did in the first snippet: treat an int as an array of char (which is allowed) and copy the bytes from the array into it, manipulate it as desired, and then copy back. I would note that if you're concerned with runtime efficiency, you probably shouldn't be. Compilers are very good at optimizing these sorts of things, and will likely end up just manipulating the bytes in place. For instance, clang with -O2 compiles your first snippet (with std::cout replaced with printf to avoid stream I/O overhead) down to: mov edi, 65 call putchar mov edi, 66 call putchar Demo Remember, when writing C++ you are describing the behavior of the program you want the compiler to write, not writing the instructions the machine will execute.
73,628,384
73,630,947
WinUI 3 C++/WinRT loading string resources
I have a basic WinUI3 C++/WinRT app, containing a resw file with a simple entry named "APPNAME". I wish to put that string in the title of my Xaml form. My MainWindow.xaml.cpp has this snippet of code in it. MainWindow::MainWindow() { InitializeComponent(); auto resourceLoader{ Windows::ApplicationModel::Resources::ResourceLoader::GetForViewIndependentUse()}; hstring title = resourceLoader.GetString(L"APPNAME"); this->Title(title); } The issue seems to be that "Windows::ApplicationModel::Resources" isn't correct. So the question becomes how to access that resw string entry in C++/WinRT? Many thanks, Jason
With WinUI 3, most namespaces usually start with Microsoft, instead of Windows (which was more for UWP). It's actually difficult to get to the WinUI3-only documentation, here is some: Manage resources with MRT Core The WinUI 3 resource entry point is now the Microsoft.Windows.ApplicationModel.Resources.ResourceManager class. So, for a "MyString" string resource in a "Resources.resw" file You can now do this: Microsoft::Windows::ApplicationModel::Resources::ResourceManager rm{}; auto str = rm.MainResourceMap().GetValue(L"Resources/MyString").ValueAsString(); Note that you need to #include <winrt/Microsoft.Windows.ApplicationModel.Resources.h> after Xaml includes to compile.
73,628,848
73,628,883
Is the std::views namespace not available in Xcode's C++?
I have Xcode 14 beta, and I tried to compile this join example from cppreference.com. #include <iostream> #include <ranges> #include <string_view> #include <vector> int main() { using namespace std::literals; const auto bits = { "https:"sv, "//"sv, "cppreference"sv, "."sv, "com"sv }; for (char const c : bits | std::views::join) std::cout << c; // Error 1 std::cout << '\n'; const std::vector<std::vector<int>> v{ {1,2}, {3,4,5}, {6}, {7,8,9} }; auto jv = std::ranges::join_view(v); // Error 2 for (int const e : jv) std::cout << e << ' '; std::cout << '\n'; } I get errors: 1. No member named 'views' in namespace 'std' 2. No member named 'join_view' in namespace 'std::ranges' That reference site says these things are available "since C++20". I have my language build setting at the maximum: C++2b. The clang --version reports: Apple clang version 14.0.0 (clang-1400.0.29.102). Is there a way to make this work with Xcode's C++ compiler?
AppleClang does not support C++ views. See the red boxes in the 4th column on C++ compiler support.
73,628,882
73,629,633
How do I create a GstValueArray in C++?
I am trying to create a GstValueArray in C++ to update a pad property in some GStreamer code, but am unable to figure out from the documentation how to do so. My problem is that I have a GStreamer element that has sink pads with a property "dimensions", which is a "GstValueArray of GValues of type gint". See output from gst-inspect-1.0, some parts omitted for brevity: ... Pad Templates: SINK template: 'sink_%u' Availability: On request Capabilities: ... Type: GstVideoComposerSinkPad Pad Properties: dimensions : The destination rectangle width and height, if left as '0' they will be the same as input dimensions ('<WIDTH, HEIGHT>') flags: readable, writable, changeable in NULL, READY, PAUSED or PLAYING state, 0x4000 0000 GstValueArray of GValues of type "gint" I'd like to be able to update the dimensions property from my code. Currently, I am trying this: const auto pad = gst_element_get_static_pad(videomixer, sink_name.c_str()); ... // Create a GValue for width GValue width = G_VALUE_INIT; g_value_init(&width, G_TYPE_INT); g_value_set_int(&width, cameraUpdate["width"]); // Create a GValue for height GValue height = G_VALUE_INIT; g_value_init(&height, G_TYPE_INT); g_value_set_int(&height, cameraUpdate["height"]); // Create the GstValueArray GValue new_dimensions = G_VALUE_INIT; g_value_init(&new_dimensions, GST_TYPE_ARRAY); gst_value_array_append_value(&new_dimensions, &width); gst_value_array_append_value(&new_dimensions, &height); // Update the pad property "dimensions" with this array g_object_set(pad, "dimensions", new_dimensions, nullptr); But this has a runtime error of: GLib-ERROR **: 17:21:07.582: ../../../../glib/gmem.c:135: failed to allocate 62846110096 bytes. I am unsure also where I accidentally requested 62 GB of memory. Thank you!
g_object_set is a convenience function that, among other things, parses internally the GType of the property and automatically creates the underlying GValue for you. If you are creating the GValue yourself you need to use g_object_set_property instead. Replace your g_object_set with: g_object_set_property (G_OBJECT(pad), “dimensions”, &new_dimensions) By the way, remember to call g_value_unset on every GValue to clean up everything.
73,629,766
73,629,931
Good sound apis for linux?
I am learning game development and came across this playlist(Handmade Hero) about making a game from absolute scratch, like using only Os provided apis. The series focuses on windows, I also want to develope the same thing for linux. What should be the sound api that I should use? In the series he was using DirectSound, what would be the similar kind of api for linux?
ALSA (Advanced Linux Sound Architecture) part of the linux kernel (sound drivers) user space library (alsa-lib) There are also so called sound servers available on linux, like PulseAudio or pipewire. Frameworks for game development SDL OpenAL
73,630,606
73,632,379
Is it unsafe to take the address of a variable inside a loop where it is defined?
I came across a comment in cppcheck source code here, stating that it is unsafe to move the definition of i in the example into the inner loop. Why is that? void CheckOther::variableScopeError(const Token *tok, const std::string &varname) { reportError(tok, Severity::style, "variableScope", "$symbol:" + varname + "\n" "The scope of the variable '$symbol' can be reduced.\n" "The scope of the variable '$symbol' can be reduced. Warning: Be careful " "when fixing this message, especially when there are inner loops. Here is an " "example where cppcheck will write that the scope for 'i' can be reduced:\n" "void f(int x)\n" "{\n" " int i = 0;\n" " if (x) {\n" " // it's safe to move 'int i = 0;' here\n" " for (int n = 0; n < 10; ++n) {\n" " // it is possible but not safe to move 'int i = 0;' here\n" " do_something(&i);\n" " }\n" " }\n" "}\n" "When you see this message it is always safe to reduce the variable scope 1 level.", CWE398, Certainty::normal); }
The question is focused on the second comment in this hypothetical code: void f(int x) int i = 0; if (x) { // it's safe to move 'int i = 0;' here for (int n = 0; n < 10; ++n) { int i=0; // it is possible but not safe to move 'int i = 0;' here do_something(&i); } } } There is no general issue taking the address of a variable declared in a loop so long as that address (so taken) is not dereferenced after the loop. Here's a code fragment similar to the question with variable moved inside the loop as per that comment. int *p=nullptr; for(int n=0;n<10;++n){ int i=0; //Where the code in question says it's possible but not safe! p=&i; //can use value of p here. } //address of i assigned to p now invalid. This is the same general notion of variable scope that means pointers to local variables can't be used after the function that defined them returns(*). In this case in anything but the iteration the address was taken. int *q=nullptr; for(int n=0;n<10;++n){ int i=0; if(n==0){ q=&i; }else{ //cannot use q here. //That would using the address from the first iteration in a later iteration. } } So it's not clear what the original author's concern is. What is clear in the code as presented is i will be 0 when do_something(&i) is called every time and in the code as shown nothing is done with any value do_something() assigns to the variable through its pointer. Sometimes it is necessary to provide an address to a general purpose function that the specific caller doesn't then need to use. But the code provided isn't sufficient to explain the comment. (*) For the same reasons that the implementation may have released or reused the memory for other purposes as it leaves the relevant scope.
73,630,748
73,631,229
Mapping enums to types
I have two unrelated types: Object and Unrelated implementing the same basic interface Interface (for storing in the same container). I have an enum class that basically maps these types to enums enum class TypeEnum { TYPE_OBJECT, TYPE_UNRELATED, }; I have a reading method, that basically down-casts from the Interface to an implementation class template<typename DATA> const DATA& Read(const Container<Interface>& container, TypeEnum type); Is it possible to automate the code, such that (this is a pseudo code) switch(type_enum) { case TYPE_OBJECT: return Read<Object>(container, type_enum); case TYPE_UNRELATED: return Read<Unrelated>(container, type_enum); } can be made into a one liner? NB. I have a bunch of enum values around 50 and a number of places i want to use this idiom. In my want-to-have way, I would prefer something aka template<TypeName> struct TypePicker; template<> struct TypePicker<TYPE_OBJECT> { typedef Object underlying_type; }; template<> struct TypePicker<TYPE_UNRELATED> { typedef Unrelated underlying_type; }; and then return Read<TypePicker<type_enum>::underlying_type>(container, type_enum); However, type_enum is only known at run-time.
I turn the reference into a copy to fit std::variant, // using std::type_identity for C++20 or later template <typename T> struct type_identity { using type = T; }; using VType = std::variant<type_identity<Object>, type_identity<Unrelated>>; using RType = std::variant<Object, Unrelated>; static const std::map<TypeEnum, VType> dispatcher = { {TypeEnum::TYPE_OBJECT, type_identity<Object>{}}, {TypeEnum::TYPE_UNRELATED, type_identity<Unrelated>{}} }; auto foo(TypeEnum type_enum) { Container<Interface> container; return std::visit([&](auto v) -> RType { return Read<typename decltype(v)::type>(container, type_enum); }, dispatcher.at(type_enum)); } Demo
73,630,821
73,631,324
Best practice for very large if-else-statement using LLVMs RTTI system
I am currently writing a piece of software that relies on another library, which makes heavy use of LLVMs RTTI system. I cannot change the API of said library and it forces me to implement very large if-else-statements over several types and their sub-types. Usually I would have used at a switch-statement instead, but that is obviously not possible using LLVM's dyn_cast<>(). Below is an example of what I am currently doing, however, this turned out to be a real bottleneck. Are there any better ways of achieving the same, but with less overhead? Thanks a ton! if (const SomeClass *casted = dyn_cast<SomeClass>(something)) { ... } else if (const anotherClass *casted = dyn_cast<AnotherClass>(something)) { ... } ... else { ... }
You can switch(something->getType()->getTypeId()) sometimes, but some dyn_cast<>() calls will probably be unavoidable, e.g. for struct types you define.
73,631,293
73,647,440
How to encrypt a string using OpenSSL C library and a public key file?
What is the recommended way of encrypting a short std::string into another std::string using the openssl C library (not the command-line tool of the same name) using a public keyfile, and knowing the algorithm? (in this case the string is no larger than ~100 bytes, keyfile is in .pem format, algorithm can be any asymmetric one like RSA/ECDSA/etc). I am looking to write a function with an interface like so: bool EncryptString(const std::string& InStr, const std::string& InPublicKey, std::string& OutString). Looking through documentation it seems like EVP_PKEY_encrypt is the function to use, which requires an EVP_PKEY_CTX *ctx variable. My assumption is, this variable should be initialized with EVP_PKEY_CTX_new, which in turn requires an EVP_PKEY *pkey and an ENGINE *e. Those I don't know how to initialize, and searching through the documentation leaves me very confused. Maybe these functions are not the easiest approach, I am not familiar with this library at all and have no cryptography knowledge. I simply care about a black-box way of converting a string to an encrypted string. Thank you
As it turned out in the comments, RSA is an acceptable option for you. When implementing RSA with OpenSSL, the following steps are required for encryption: Loading the public key Creating and initializing the context Specifying the padding Encryption The implementation below for encryption with RSA and OpenSSL runs successfully on my machine and shows how the functions are called (without exception handling for simplicity): #include <openssl/pem.h> #include <string> ... bool EncryptString(const std::string& InStr /*plaintext*/, const std::string& InPublicKey /*path to public key pem file*/, std::string& OutString /*ciphertext*/) { // Load key FILE* f = fopen(InPublicKey.c_str(), "r"); EVP_PKEY* pkey = PEM_read_PUBKEY(f, NULL, NULL, NULL); fclose(f); // Create/initialize context EVP_PKEY_CTX* ctx; ctx = EVP_PKEY_CTX_new(pkey, NULL); EVP_PKEY_encrypt_init(ctx); // Specify padding: default is PKCS#1 v1.5 // EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING); // for OAEP with SHA1 for both digests // Encryption size_t ciphertextLen; EVP_PKEY_encrypt(ctx, NULL, &ciphertextLen, (const unsigned char*)InStr.c_str(), InStr.size()); unsigned char* ciphertext = (unsigned char*)OPENSSL_malloc(ciphertextLen); EVP_PKEY_encrypt(ctx, ciphertext, &ciphertextLen, (const unsigned char*)InStr.c_str(), InStr.size()); OutString.assign((char*)ciphertext, ciphertextLen); // Release memory EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(ctx); OPENSSL_free(ciphertext); return true; // add exception/error handling } With the ciphertext it must be considered that it is a byte sequence that does not represent real text (it may contain 0x00 values, for example). If the ciphertext is to be represented as real text, an additional binary-to-text encoding such as Base64 encoding must be performed. The code requires a PEM encoded public key in X.509/SPKI format. If the public key has the PKCS#1 format, it can be imported using PEM_read_RSAPublicKey() and EVP_PKEY_set1_RSA().
73,631,465
73,631,672
How to take a pointer address as command line argument in C++
I have a C++ code which will take a pointer address as an argument. The code arguments are: ./main 0x7fad529d5000 Now when reading the arguments, this value will be read as a string. How do I convert the string "0x7fad529d5000" into an address?
Read a hexadecimal from stdin: uintptr_t x; std::cin >> std::hex >> x; Read a hexadecimal from string: uintptr_t x; // assuming you used argc / argv and checked argc > 1 std::istringstream sstr( argv[1] ); sstr >> std::hex >> x; An alternative would be x = std::stoll( argv[1] ); but there is a cast involved there that I do not quite like (assuming the width of uintptr_t). Converting it to a pointer: void * p = reinterpret_cast<void *>(x); Handle that pointer value with care, because it is unlikely to be valid. (reinterpret_cast is something that should scream "danger!" at you.)
73,631,608
73,634,291
How to toggle a QCustomPlot graph's visibility by clicking on the legend
I have a QCustomPlot with multiple graph items on it. I wish to toggle their visibility by clicking on the relevant item in the legend. QObject::connect( plot, &QCustomPlot::legendClick, [](QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) { // how to get to the relevant graph from the item variable? } ); Thank you.
I suggest you try this QObject::connect( plot, &QCustomPlot::legendClick, [](QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) { for (int i=0; i<customPlot->graphCount(); ++i) { QCPGraph *graph = customPlot->graph(i); QCPPlottableLegendItem *itemLegend = customPlot->legend->itemWithPlottable(graph); QCPPlottableLegendItem *plItem = qobject_cast<QCPPlottableLegendItem*>(item); if (itemLegend == plItem ) { //graph the one you need } } };
73,631,617
73,631,870
pcre2: include a static library in c++ CMake project
need to include pcre2 static library in my CMake project. I've built last version of pcre2 from official sources and got libpcre2-32.a (I need 32-bit char width libray) Put it in my project folder, with its header pcre2.h Have added this library to CMakeLists.txt: ... include_directories(SupportFiles/OSLinux/pcre2) ... add_library(libpcre2 STATIC IMPORTED GLOBAL) find_library(libpcre2_path NAMES libpcre2-32.a HINTS ${CMAKE_SOURCE_DIR}/SupportFiles/OSLinux/pcre2/ REQUIRED NO_CMAKE_SYSTEM_PATH) message(">>>>>> libpcre2_path = ${libpcre2_path}") set_property(TARGET libpcre2 PROPERTY IMPORTED_LOCATION ${libpcre2_path}) target_link_libraries(appservicehttpmodule PRIVATE libpcre2) ... Library was found in my project and no CMake errors are. Have added simple pcre2 code in my project #define PCRE2_CODE_UNIT_WIDTH 32 #include "pcre2.h" ... pcre2_code *pcode = pcre2_compile(...) get an error : /usr/bin/ld: CMakeFiles/UnitTest.dir/test.cpp.o: in function `moduleTest_pcre2Presence_Test::TestBody()': /home/.../GoogleTest/test.cpp:248: undefined reference to `pcre2_compile_32' What is wrong? Why this lib is not linked? Thanks in advance.
(I don't have enough reputation to leave comments :( ) The linker error seems to be from a separate executable (a unit test). Does it have libpcre2 added as a dependency (using target_link_libraries())?
73,631,820
73,632,272
How do I normalize a filepath in C++ using std::filesystem::path?
I am trying to convert a path string to a normalized (neat) format where any number of directory separators "\\" or "/" is converted to one default directory separator: R"(C:\\temp\\Recordings/test)" -> R"(C:\temp\Recordings\test)" Code: #include <string> #include <vector> #include <iostream> #include <filesystem> std::string normalizePath(const std::string& messyPath) { std::filesystem::path path(messyPath); std::string npath = path.make_preferred().string(); return npath; } int main() { std::vector<std::string> messyPaths = { R"(C:\\temp\\Recordings/test)", R"(C://temp\\Recordings////test)" }; std::string desiredPath = R"(C:\temp\Recordings\test)"; for (auto messyPath : messyPaths) { std::string normalizedPath = normalizePath(messyPath); if (normalizedPath != desiredPath) { std::cout << "normalizedPath: " << normalizedPath << " != " << desiredPath << std::endl; } } std::cout << "Press any key to continue.\n"; int k; std::cin >> k; } Output on Windows VS2019 x64: normalizedPath: C:\\temp\\Recordings\test != C:\temp\Recordings\test normalizedPath: C:\\temp\\Recordings\\\\test != C:\temp\Recordings\test Reading the std::filepath documentation: A path can be normalized by following this algorithm: 1. If the path is empty, stop (normal form of an empty path is an empty path) 2. Replace each directory-separator (which may consist of multiple slashes) with a single path::preferred_separator. ... Great, but which library function does this? I do not want to code this myself.
As answered by bolov: std::string normalizePath(const std::string& messyPath) { std::filesystem::path path(messyPath); std::filesystem::path canonicalPath = std::filesystem::weakly_canonical(path); std::string npath = canonicalPath.make_preferred().string(); return npath; } weakly_canonical does not throw an exception if path does not exist. canonical does.
73,632,135
73,633,675
How do I assign an arbitrary value to a unique_ptr?
Is there a way to assign an arbitrary value to a unique_ptr? Let's say I have some unique_ptr of an object. For testing purposes, I want to have this unique_ptr to be != nullptr, and/or pObj.get() != 0 without having to construct the object. std::unique_ptr<someObj> pObj; assert(!pObj); // OK, but not what I want // pObj = std::make_unique<someObj>(); // assert(pObj); // Assign a "fake" object at an arbitrary memory location have have the assertion to be true. pObj = 1; assert(pObj);
Summarize the answers given in the comments of the question. The new code has to look like this: std::unique_ptr<someObj> pObj; assert(!pObj); // Assign a "fake" object at an arbitrary memory location pObj.reset((someObj *)1); assert(pObj); // release before unique_ptr is destructed! // Else we would get an Segmentation Fault // when the "fake" objects destructor is called by the unique_ptr. pObj.release();
73,632,216
73,633,287
Improve the performance of a method used to convert an std::string into an std::wstring?
I have the following method used to convert an std::string object into an std::wstring one: #include <string> #include <type_traits> #include <locale> #include <codecvt> template <class CharT> inline std::basic_string<CharT> StringConverter( std::string input_str ) { if constexpr( std::is_same_v <CharT, char> ) return input_str; else if constexpr( std::is_same_v <CharT, wchar_t> ) { static std::wstring_convert <std::codecvt_utf8_utf16 <wchar_t>> converter; return converter.from_bytes( input_str ); } return StringConverter<CharT>( "" ); } This is used only to convert simple strings like: #include <string> #include <iostream> using namespace std::literals::string_literals; int main() { std::cout << StringConverter<wchar_t>( "Hello"s ); // returns L"Hello" std::cout << StringConverter<char>( "Hello"s ); // returns "Hello" } and works well. However it seems a bit too much expensive in terms of performance: in the first case it needs 64 ns to convert the string, while in the second case 11.9. Do you know if there is a better way to write it or if it can be improved in C++17? Thanks.
You can clearly avoid copy/move in case you don't do any conversion (std::string -> std::string) and just pass and return by reference: template <class CharT> std::conditional_t<std::is_same_v<CharT, char>, const std::basic_string<CharT>&, std::basic_string<CharT>> StringConverter(const std::string& input_str) { if constexpr( std::is_same_v <CharT, char> ) { return input_str; } else if constexpr( std::is_same_v <CharT, wchar_t> ) { static std::wstring_convert <std::codecvt_utf8_utf16 <wchar_t>> converter; return converter.from_bytes( input_str ); } else { return StringConverter<CharT>( "" ); } }
73,632,337
73,646,023
Performance improvements of a method which check if a string is an ANSI escape sequence?
Let's suppose I have a class with a private method is_escape which check if an input string is and ANSI escape sequence. This method is then used in another public method, into an if/else condition: #include <string> enum class ANSI { first, generic }; template <class T_str> class foo { private: template <typename T> static constexpr bool is_escape( const T& str, ANSI&& flag ) { /* implementation */ } public: template <class T> void public_method( T str ) // T can be also an int, double etc... { if ( is_escape( str ) ) { /* do something */ } } }; The implementation of the is_escape method is the following: #include <string> #include <type_traits> template <typename T> static constexpr bool is_escape( const T& str, ANSI&& flag ) { if constexpr( std::is_convertible_v <T, std::basic_string_view<T_str>> && ! std::is_same_v<T, std::nullptr_t> ) { switch( flag ) { case( ANSI::first ): { return ( ! std::basic_string_view<T_str>( str ).rfind( "\033"s, 0 ) ) && ( std::basic_string_view<T_str>( str ).length() < 7 ); } case( ANSI::generic ): { return ( std::basic_string_view<T_str>( str ).find( "\033"s ) != std::basic_string_view<T_str>::npos ); } } } return false; } Is there a better way to write the method in order to improve its performances (in C++17)? Thanks.
At the end, I improved the performances of the function with this signature: template <typename T> static constexpr bool is_escape( const T& str, const ANSI& flag ) { if constexpr( std::is_convertible_v <T, std::basic_string_view<T_str>> && ! std::is_same_v<T, std::nullptr_t> ) { switch( flag ) { case( ANSI::first ): { return ( std::basic_string_view<T_str>( str ).length() < 7 ) && ( str[0] == '\033' ); } case( ANSI::generic ): { return ( std::basic_string_view<T_str>( str ).find( '\033' ) != std::basic_string_view<T_str>::npos ); } } } return false; }
73,632,611
73,637,922
Nested Requirements for Tree Data Structure with heterogeneous Nodes
Objective: I want to implement a tree data structure with non-identical nodes to manage my data. In general, the tree consists of 2 different type of nodes, namely, "Nodes" and "LeafNodes". Those nodes which have no children are considered to be "LeafNodes", which will be used to store data. Within the tree all nodes are tagged with metadata. The tree must be created at compile-time. How: My current implementation uses type template parameters to tag all nodes with metadata. The concept "Header" is used to specify the requirements of a header-type. If the node isn't a specialization of "LeafNode", "Nodes/LeafNodes" specializations are passed to specify the children of that node. The concept "Nodelike" is used to indicate how a specialization of "Node/LeafNode" has to look like. Error: I get a template constraint failure when specifying my tree type using Tree = Node < Header0<0>, LeafNode<Header1<0,20,5>>, LeafNode<Header1<1,20,'f'>>, LeafNode<Header1<2,20,4.4>> >; Unfortunately, I can't interpret the compiler error so that I have no hint how to resolve the error. I am using the compiler "x86-64 gcc 12" with the following flags "-std=c++20 -O3". Here is the not working online code: Code Implementation: using namespace std; template<class T> concept LeafHeader = requires (){ {T::ID} -> convertible_to<uint8_t>; {T::size} -> convertible_to<size_t>; T::dValue; }; template<class T> concept NodeHeader = requires (){ {T::ID} -> convertible_to<uint8_t>; }; template<class T> concept Header = NodeHeader<T> || LeafHeader<T>; template<class T> concept NodeLike = requires(T){ is_object_v<T>; requires T::Header; }; template<LeafHeader H> struct LeafNode final{ // Resource Header static constexpr H header{}; // Instances using type = typename H::type; }; template<NodeHeader H, NodeLike... N> struct Node{ static constexpr H header{}; tuple<N...> childs; }; template<uint8_t I, std::size_t S, auto V> struct Header1{ static constexpr uint8_t ID = I; static constexpr size_t size = S; using type = decltype(V); static constexpr type dValue = V; }; template<uint8_t I> struct Header0{ static constexpr uint8_t ID = I; }; using Tree = Node < Header0<0>, LeafNode<Header1<0,20,5>>, LeafNode<Header1<1,20,'f'>>, LeafNode<Header1<2,20,4.4>> >; int main(){ Tree t; }
There are two problems with the definition of the NodeLike: template<class T> concept NodeLike = requires(T) { is_object_v<T>; requires T::Header; }; First, the requires-clause only checks the validity of the expression, so is_object_v<T> is useless here because it is always valid, you should use the nested requires, but it is more appropriate just to move it outside the requires-clause. Second, requires T::Header is not satisfied in your case, because class Node does not have a static variable named Header (but header, I suspect it's a typo), and since you're using the nested-requires, T::Header will be evaluated, which is never satisfied because the variable cannot be converted to bool. You can just use T::header to check if T has a static variable named header, so this should work: template<class T> concept NodeLike = is_object_v<T> && requires { T::header; };
73,632,664
73,637,026
Generated parser code with antlr4.11.1 contains error
I create a compiler with antlr and llvm in c++. I've created the two .g4 files and in my CMakeLists.txt I call the antlr jar to generate the lexer and the parser. Then I compile all my files with the same CMakeLists file and I got these errors : Filc/src/generated/FilParser.cpp:803:16: error: invalid use of member function ‘antlrcppfil::FilParser::ExceptionContext* antlrcppfil::FilParser::ExprContext::exception()’ (did you forget the ‘()’ ?) 803 | _localctx->exception = std::current_exception(); | ~~~~~~~~~~~^~~~~~~~~ | () Filc/src/generated/FilParser.cpp:804:43: error: invalid use of non-static member function ‘antlrcppfil::FilParser::ExceptionContext* antlrcppfil::FilParser::ExprContext::exception()’ 804 | _errHandler->recover(this, _localctx->exception); | ~~~~~~~~~~~^~~~~~~~~ I looking in some tutorials and on stackoverflow why i've got these errors. But I didn't found any mention of that. And in tutorials code they have the same code as me, but it compile. So I tried to update my antlr version to version 4.11.1 (originally I use 4.8) but it doesn't change anything. For information, I use c++ 17, and this is my CMakeLists.txt : project(Filc) cmake_minimum_required(VERSION 3.10) set (CMAKE_CXX_STANDARD 17) set(antlr4-jar ${PROJECT_SOURCE_DIR}/bin/antlr-4.11.1-complete.jar) set(antlr4-output ${PROJECT_SOURCE_DIR}/src/generated/FilLexer.cpp ${PROJECT_SOURCE_DIR}/src/generated/FilLexer.h ${PROJECT_SOURCE_DIR}/src/generated/FilParser.cpp ${PROJECT_SOURCE_DIR}/src/generated/FilParserBaseVisitor.cpp ${PROJECT_SOURCE_DIR}/src/generated/FilParserBaseVisitor.h ${PROJECT_SOURCE_DIR}/src/generated/FilParserVisitor.cpp ${PROJECT_SOURCE_DIR}/src/generated/FilParserVisitor.h ) add_custom_target(GenerateLexerParser COMMAND java -jar ${antlr4-jar} -Dlanguage=Cpp -visitor -no-listener -o ${PROJECT_SOURCE_DIR}/src/generated/ -package antlrcppfil ${PROJECT_SOURCE_DIR}/src/antlr/FilLexer.g4 ${PROJECT_SOURCE_DIR}/src/antlr/FilParser.g4 DEPENDS ${PROJECT_SOURCE_DIR}/src/antlr/FilLexer.g4 ${PROJECT_SOURCE_DIR}/src/antlr/FilParser.g4 ) include_directories( src src/generated src/utils antlr-runtime/src ) add_executable(filc src/main.cpp src/utils/cxxopts.hpp src/generated/FilLexer.cpp src/generated/FilLexer.h src/generated/FilParser.cpp src/generated/FilParserBaseVisitor.cpp src/generated/FilParserBaseVisitor.h src/generated/FilParserVisitor.cpp src/generated/FilParserVisitor.h ) add_dependencies(filc GenerateLexerParser) target_link_libraries(filc antlr4-runtime.a) install(TARGETS filc DESTINATION bin) [Edit] Someone found the solution on the antlr github https://github.com/antlr/antlr4/issues/3876
I tried the c++ target on one of my project and it compiled correctly in 4.9.3. Are you sure you didn't mix the version of the runtime you use and the version of antlr4 you used to generate the parser? You need the same version for both.
73,632,839
73,635,362
How to create a manifest file for a C++ project?
I'm trying to add DPI awareness per monitor v2 to a C++ application, using VS2022. Microsoft recommends to do this using the application manifest. So far I have been using an automatically generated intermediate manifest file (using the setting under linker -> generate manifest: yes). However, this file is not actually generated in the filing system (the location where it is purported to be does not contain the desired manifest file). Because it is not being generated, I have no example manifest that I can modify to suit my needs. Various other answers on Stackoverflow all indicate that you can generate a manifest file if you have the C# compiler installed, which I do not. The C++ compiler has no option for creating a manifest file. Lacking both a wizard and an example file, what other options do I have for setting up a manifest file containing all required information?
By default, the manifest is embedded into the compiled application (exe or dll). You can access it with a resource viewer. There is an option to control that in Manifest Tool -> Input and Output -> Embed Manifest. All manifest files included in your project are merged and added to the application manifest (maybe the file type also need to be set as Manifest file for it to work)
73,633,209
73,635,807
Unable to Debug C++ Application in VS 2019
I have a C++ project that I am able to build and run as an exe just fine. However, when I try to debug the project in Visual Studio 2019 I get the following error: "Unhandled exception at 0x75D7C66B (shell32.dll) in MyApp.exe: 0xC0000005: Access violation reading location 0x00000004" It also says: "Source Not Available: Source information is missing from the debug information for this module" I don't understand this error. I have set breakpoints right at the beginning of the main() function but it never gets to these breakpoints so I don't know what causes the exception. I have googled this for quite sometime but haven't found any similar problems. I hope someone can help. Let me know if you need further details. Edit: here is the call stack: shell32.dll!CShellFolderViewOC::GetConnMap(int *) Unknown shell32.dll!`dynamic initializer for 'ATL::IConnectionPointContainerImpl::pConnMap''() Unknown ucrtbase.dll!__initterm() Unknown shell32.dll!dllmain_crt_process_attach() Unknown shell32.dll!dllmain_crt_dispatch() Unknown shell32.dll!dllmain_dispatch() Unknown shell32.dll!__DllMainCRTStartup@12() Unknown ntdll.dll!_LdrxCallInitRoutine@16() Unknown ntdll.dll!LdrpCallInitRoutine() Unknown ntdll.dll!LdrpInitializeNode() Unknown ntdll.dll!LdrpInitializeGraphRecurse() Unknown ntdll.dll!LdrpInitializeGraphRecurse() Unknown ntdll.dll!LdrpPrepareModuleForExecution() Unknown ntdll.dll!LdrpLoadDllInternal() Unknown ntdll.dll!LdrLoadDll() Unknown 01240307() Unknown [Frames below may be incorrect and/or missing] Unknown ntdll.dll!_KiUserApcDispatcher@16() Unknown ntdll.dll!LdrInitializeThunk() Unknown
I fixed it. In Visual Studio under: Options -> Debugging -> General I disabled the option: "Load debug symbols in external process (Native only)" I still don't really understand why this fixed the problem. If someone could explain I would be grateful.
73,633,579
73,744,769
C++ [QT 5.15.2] : virtual keyboard shift button is disabled until I click on my textField
I'm developping an app using QT 5.15 LTS (5.15.2). I have the following QML item that I use to handle virtual keyboard interactions : //InputScreen.qml import QtQuick 2.3 import QtQuick.Layouts 1.3 import QtQuick.Controls 2.2 import QtQuick.VirtualKeyboard 2.3 Rectangle { id: inputScreen property var target: undefined width: app.width height: app.height color: "#44000000" z: 200 onVisibleChanged: { if (inputScreen.visible == true) { fld.text = target.text; inputPanel.forceActiveFocus(); fld.forceActiveFocus(); fld.clicked(); //Tried to force a click here. Explanation below } } Rectangle { anchors.horizontalCenter: parent.horizontalCenter anchors.verticalCenter: parent.verticalCenter height: 40 width: 600 z: 201 TextField { id: fld anchors.left: parent.left anchors.verticalCenter: parent.verticalCenter width: 400 height: 40 font.pixelSize: 24 focus: true } Button { anchors.right: parent.right anchors.verticalCenter: parent.verticalCenter width: 200 height: 40 font.pixelSize: 24 text: "Valider" onClicked: { if (target != undefined) { target.text = fld.text; inputScreen.visible = false; } } } } InputPanel { id: inputPanel height: 400 width: app.width - 40 anchors.bottom: parent.bottom anchors.horizontalCenter: parent.horizontalCenter focus: true z: 201 } MouseArea { anchors.fill: parent onClicked: { target.text = fld.text; inputScreen.visible = false; } } } When my item becomes visible, the textField gets the focus correctly and I can start typing through the InputPanel virtual keyboard. There's however one single problem : the shift key does not work ! In order to make that shift key enable itself, I need to click on the TextField, which beats the purpose of forcing the active focus on it to begin with. Is there any way to fix that problem ? Or at the very least, is there any kind of workaround I can use to enable that shift key ? I have already tried to force a click inside my TextField (as seen in the code above), but it didn't work. For context : here's the content of main.qml as well, in order to give out a working example : import QtQuick 2.6 import QtQuick.Window 2.2 import QtQuick.Layouts 1.3 import QtQuick.Controls 1.4 import QtQuick.VirtualKeyboard 2.3 Window { id: app visible: true width: 640 height: 480 title: qsTr("Example") InputScreen { id: inputScreen visible: false } Rectangle { id: rect height: parent.height * 0.8 width: parent.width * 0.8 anchors.centerIn: parent border.color: "#FF0000" z: 1 TextField { id: myField anchors.centerIn: parent width: 200 height: 24 MouseArea { anchors.fill: parent onClicked: { inputScreen.target = myField; inputScreen.visible = true; } } } } }
I finally managed to find a trick that enabled that shift key without requiring to click on my already focused TextField, and it's actually very simple. I simply added the following line in the onClicked event of the MouseArea inside the "myField" TextField : MouseArea { anchors.fill: parent onClicked: { parent.focus = true; //This line solved the issue ! //... } } I have no idea why, but somehow this was enough to actually unlock the shift key from my InputPanel virtual keyboard without requiring me to click a second time on the TextField from my InputScreen item. I suppose it has probably something to do with the fact that my MouseArea is hijacking the focus of the "myField" TextField, which triggers some sort of odd behaviour on the InputPanel item despite having another TextField item focused. In any case, I hope this will help someone.
73,633,682
73,633,683
What programing languages does Memgraph support?
From which programming languages can I connect to Memgraph? Which protocol is used? I know that Python is for sure supported since there is GQLAlchemy (a fully open-source Python library). What about other languages?
f you want to query Memgraph programmatically, you can do so using the Bolt protocol. The Bolt protocol was designed for efficient communication with graph databases and Memgraph supports versions 1 and 4 of the protocol. You can use the Bolt protocol drivers for the following programming languages: Python C/C++ Rust Node.js C# Go Haskell Java JavaScript PHP Ruby
73,634,271
73,635,329
Iterate over json and change first character of Json keys to upper case
I want go throw all json keys and convert the first character to upper case. i understand that i cant change json keys so crate a new json from the old one i using json::Value, void change_keys(Json::Value& oldJson, Json::Value& newJson) { for (Json::ValueConstIterator it = oldJson.begin(); it != oldJson.end(); ++it) { std::string newKey = it.name(); newKey[0] = std::toupper(newKey[0]); newJson[newKey] = oldJson[it.name()]; if (it->isArray()) { return; } if (it->isObject()) { change_keys(oldJson[it.name()],newJson[newKey]); } } } My problem is in case of array, i don't know to proceed the recursive in case of array of arrays or array of json for this json {"result": { "main": [ { "free": 0, "total": 0 } ] } expected restult {"Result": { "Main": [ { "Free": 0, "Total": 0 } ] }
I think it should be something like: void change_keys(Json::Value& oldJson, Json::Value& newJson) { if (oldJson.isObject()) { for (Json::ValueConstIterator it = oldJson.begin(); it != oldJson.end(); ++it) { std::string newKey = it.name(); newKey[0] = std::toupper(newKey[0]); change_keys(oldJson[it.name()], newJson[newKey]) } } else if (oldJson.isArray()) { for (int i = 0; i != oldJson.size(); ++i) { newJson.append(Json::nullValue); change_keys(oldJson[i], newJson[i]); } } else { newJson = oldJson; } }
73,634,556
73,645,324
How to test a string for containing emoji characters?
I'm using ICU4C and trying to find the clusters in a UTF-8 string that are emojis. This is the closest I've gotten so far but it incorrectly qualifies the simple character '#' as an emoji (because '#️⃣' begins with '#' and is "potentially" an emoji so '#' does carry the property UCHAR_EMOJI). I think the best would be trying to get the property RGI_Emoji as indicated here but that's a "string" property and not a "codepoint" property and I don't know how to do that. If I could I would analyze every single character as a "string" and test for that string property. The documentation states that, currently, using a regular expression is not possible to get "string" properties. const std::string s8 = "#asd‍dds‍️️‍♂️ds#️⃣ds‍‍‍ds‍❤️‍‍ds"; const icu::UnicodeString us = icu::UnicodeString::fromUTF8(s8); UErrorCode status = U_ZERO_ERROR; icu::BreakIterator* bi = icu::BreakIterator::createCharacterInstance(icu::Locale::getUS(), status); bi->setText(us); bool is_emoji = false; for(int32_t e = bi->first(), b = e; e != icu::BreakIterator::DONE; b = e, e = bi->next()) { // Analyze character for emoji-ness. for(int32_t i = b; i != e; ++i) { std::cout << us.char32At(i) << ' '; is_emoji = u_hasBinaryProperty(us.char32At(i), UProperty::UCHAR_EMOJI) || u_hasBinaryProperty(us.char32At(i), UProperty::UCHAR_EMOJI_COMPONENT); } if(is_emoji) { std::cout << "<- is emoji\n"; ++emojis; is_emoji = false; } else { std::cout << "<- is not emoji\n"; } ++characters; } delete bi;
Looks like u_stringHasBinaryProperty will give you access to UCHAR_RGI_EMOJI. Note that this method is not available in ICU versions < 70. I think that you need to distinguish between basic emojis that consist of a single code point (e.g. U+1F600 ), and emoji sequences (e.g. U+0023 U+FE0F U+20E3 #️⃣). The basic emoji will have both UCHAR_EMOJI and UCHAR_BASIC_EMOJI properties set and UCHAR_EMOJI_COMPONENT unset; the first code point in a sequence will have UCHAR_EMOJI and UCHAR_EMOJI_COMPONENT set but not UCHAR_BASIC. Subsequent code points will have UCHAR_EMOJI_COMPONENT set, but not UCHAR_EMOJI (nor UCHAR_BASIC_EMOJI). If you encounter '#' (basically any code point with UCHAR_EMOJI and UCHAR_EMOJI_COMPONENT set) you need to check the next code point. The '#' is part of an emoji only if the next code point doesn't have UCHAR_EMOJI but does have UCHAR_EMOJI_COMPONENT.
73,634,751
73,634,892
C++ - What underlying type would an enum with more than 18,446,744,073,709,551,616 elements have?
This is more of a hypothetical question than a practical one. Of course there would be memory issues if we actually tried to compile a program with that large. Enums in C++ will take on an underlying type to fit the maximum element of the enum. Also, if I specify no integer values, then each element is always 1 more than the previous starting at 0. So, for example, if I make an enum with 5 elements(or labels, however you call them) then it's type could be something like an int since that can fit the values 0,1,2,3,4. The largest integral type in C++ is the long long, and an unsigned long long can take a value of up to 18,446,744,073,709,551,615. So what would happen if I made an enum with 18,446,744,073,709,551,616 elements? This would exceed the largest integral type, so it would need another type than long long. What does the C++ spec have to say about this loophole?
There's no loophole. You'll just get a diagnostic in a conforming compiler. [dcl.enum] 7 ... If no integral type can represent all the enumerator values, the enumeration is ill-formed. ... Or more practically, you'll get an error and compilation will halt. It might even halt sooner, due to implementation defined limits, because that's a lot of enumerators.
73,634,903
73,635,260
How to determine a number wether it's prime or not using while
i am a first semester university student. I am trying to make a program that determine wether the number is prime or not (Ex : if i input 2, there will be an output saying it's a prime number). To make this program, is it possible if i use while loop? Here's a thing i have tried : #include<iostream> using namespace std; int main(){ int a,b; cout<<"Number : "; cin>>a; b = 2; while(a%b==0){ b=b+1; } cout<<"This number : "<<a<<" is a prime number"; } But every number i input, it says it's a prime number
Some remarks/directions: Your program currently has only one outcome. So, without looking at your logic, it will either run forever or will say it's prime. Your brute-force method can and should stop at square-root of a. a % b is the remainder of a divided by b. The remainder becomes 0 when a is a multiple of b (i.e. when it's not prime). Good luck; I'm sure you can get it right. (As suggested in the comments, there are much more efficient algorithms, but using a loop is a nice exercise.)
73,635,072
73,638,126
Passing a pointer to a vector
I'm exploring a c++ library and cant figure out why its examples are written as they are. In the example they do the following std::vector<unsigned int> vec(count); someFunc(&vec[0]); while the fucion is define as void someFunc(unsigned int* a); why are the examples passing a reference to the first element of the vector and not the whole vector. Inst this code the same ? someFunc(&vec); Edit: I should have provided more contex. I simplified the case, but this has proven a bad descision. The function is supposed to simplify a mesh, the vec is a list of all the indicies of the mesh. Presumably somewhere in the code that pointer is used to iterate over the rest of the indicies ?
The reason they have written their example like they have is that someFunc() takes in a unsigned int* type (a pointer to an unsigned int). The reason they call it as: someFunc(&vec[0]); and not someFunc(&vec); is because a std::vector is not like a C-style array (say unsigned int arr[]) where arr can be boiled down a unsigned int* to the first element in the array but is rather a class/struct that acts as a resource handle to some dynamic memory they you access std::vector interface. Thus, like any class in C++, calling foo(&A) (where A is some class instance/object) would return a pointer to the object itself [1]. In their example they have accessed the first element of the vec like a C-style array (using the overloaded operator[]) which is a reference. They then use the C-style unary-prefix ampersand operator (with the signature &A) to access the address of the value obtained through the index operator. There example might be clearer if they used std::vector::data() which returns a pointer to the starting address of the memory owned by the vector or using std::addressof() (although the latter can be verbose). someFunc(vec.data()); /// or ... someFunc(std::addressof(vec[0])); [1] Note: This may not be the case if the class/struct in question has overloaded the & operator to behave differently. std::vector does not in this case. Links std::vector Member Access Operators std::addressof()