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,906,884
73,908,736
Code::Blocks build and run is not working on Chromebook
Whenever I try to build and run any C++ code (I didn’t try it with other programming languages) in Code::Blocks, a prompt pops up saying this: it seems that the project has not been built yet. Do you want to build it now?" with three options of No, Cancel, and Yes. When I click Yes, the prompt closes, and it says this in the build log: -------------- Build: Debug in main (compiler: GNU GCC Compiler)--------------- g++ -Wall -fexceptions -g -c /home/sudo/codeblocks/main/main.cpp -o obj/Debug/main.o g++ -o bin/Debug/main obj/Debug/main.o /bin/sh: 1: g++: not found Process terminated with status 127 (0 minute(s), 0 second(s)) 0 error(s), 0 warning(s) (0 minute(s), 0 second(s)) I use Debian on a Chromebook I have tried some solutions, but so far nothing has worked. I don't know if this matters, but the file is in a console application project or something.
You must install g++ to compile C++ code. According to this question, you can use these commands to install it: sudo apt update sudo apt upgrade sudo apt install build-essential sudo apt install software-properties-common sudo apt install gcc g++
73,907,342
73,907,534
Sequence point, function call and undefined behaviour
main.cpp const int& f(int& i ) { return (++i);} int main(){ int i = 10; int a = i++ + i++; //undefined behavior int b = f(i) + f(i); //but this is not } compile $ g++ main.cpp -Wsequence-point statement int a = i++ + i++; is undefined behaviour. statement int b = f(i) + f(i); is not undefined . why?
statement int b = f(i) + f(i); is not undefined . why? No, the second statement will result in unspecified behavior. You can confirm this here. As you'll see in the above linked demo, gcc gives the output as 23 while msvc gives 24 for the same program.
73,907,424
73,932,914
Visual Studio Remote Makefile project - How to set the remote target program?
I have a visual studio c++ makefile project which I would like to run and debug from the IDE, however I am unsure how to set the remote debug target. When I attempt a remote debug, the remote target be set to root build folder and I get the message GDB Failed with message /home/myuser/myprojects/mytestprog is a directory. I would like to run /home/myuser/myprojects/mytestprog/bin/x86_64/debug/mytestprog but am not sure which property to set for remote execution. In a typical remote project in Visual Studio there is a $(TargetFilename) macro, however this does not exist in a makefile project, and so I would like to know what to set instead. Could someone advise please?
The remote target program can be defined by setting the program property in the debug settings. e.g. $(RemoteOutDir)mytestprog
73,908,186
73,908,270
Why is the declaration of std::unique_ptr valid with an abstract class
for example: // Example program #include <iostream> #include <string> class abstract_class { public: abstract_class() = default; ~abstract_class() = default; virtual void read() = 0; }; int main() { std::unique_ptr<abstract_class> x; std::cout << "Hello, " << "!\n"; } I thought an Abstract Class had these Restrictions Abstract classes can't be used for: Variables or member data Argument types <--------- Function return types Types of explicit conversions In the above code we are using the abstract class as a template argument so why isnt this an error.
First things first, the argument types that you've mentioned in your question is for function call arguments and not for template arguments. why isnt this an error. Because you're creating a unique pointer to the abstract class object and not an object of the abstract class itself. That is, creating a pointer(whether unique or not) to a abstract class type is allowed. For example, just think that you can also write the following without any error: abstract_class *ptr; //this also works for the same reason
73,908,494
73,908,495
QMYSQL driver not loaded on Mac OS for Mac M1/M2 users
When I run following code: QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("localhost"); db.setDatabaseName("SecureChat"); db.setUserName("root"); db.setPassword("zTmUHsbEKZZlWhfofM"); bool ok = db.open(); qDebug() << db.lastError(); I receive error: QT/C++ QSqlDatabase: QMYSQL driver not loaded on OSx How to fix it on Mac m1?
The original solution I have found here thanks to the original author of the question and answer - chriam. I will describe in this post some key points that are not mentioned in the original solution. You have to install MySQL from Oracle cloud Use QT maintenanceTool and choose the option Add or remove components. From the list, choose your current QT version and put a mark on Sources, then click next and wait for files to download. Follow insctruction here to install ninja cd to your Src folder in my case: cd /Users/lamens/Qt/6.3.2/Src Run the following command and wait for its complitaion ./configure -sql-mysql -- -DCMAKE_INCLUDE_PATH="/usr/local/mysql/include" -DCMAKE_LIBRARY_PATH="/usr/local/mysql/lib" cd to your sqldrivers folder in my case: cd /Users/lamens/Qt/6.3.2/macos/plugins/sqldrivers Run mkdir build_sqldrivers and then cd build_sqldrivers Run command: /Users/<user>/Qt/<qt_version>/macos/bin/qt-cmake -G Ninja /Users/<user>/Qt/<qt_version>/Src/qtbase/src/plugins/sqldrivers -DCMAKE_INSTALL_PREFIX=/Users/<user>/Qt/<qt_version>/macos -DMySQL_INCLUDE_DIR="/usr/local/mysql/include" -DMySQL_LIBRARY="/usr/local/mysql/lib/libmysqlclient.dylib" -DCMAKE_OSX_ARCHITECTURES="arm64 Where <user> is your system user and <qt_version> is your QT version :D. sed -i -e 's/-arch x86_64/-arch arm64/g' /Users/<user>/Qt/<qt_version>/macos/plugins/sqldrivers/build_sqldrivers/build.ninja if this fails, change at the build.ninja (it is at the build_sqldrivers folder) file all occurrences of arch x86_64 to the arch arm64. Run at the build_sqldrivers folder cmake --build . Run at the build_sqldrivers folder cmake --install . Then locate your lib using: find ~/Qt -name libqsqlmysql.dylib and move newly generated libqsqlmysql.dylib to the /Users/<user>/Qt/<qt_version>/macos/plugins/sqldrivers folder. Voilaa!
73,909,003
73,909,050
C++ question about iterating over std::vector
My question ("why it doesn't work?") concerns the small sample below. When I run this (after g++ testThis.cc -o testThis) I get: printing 101 printing 102 printing 103 printing 100 printing 100 printing -1021296524 It should not be a problem of myHolder dropping out of scope, so why make a local copy of the vector itself? It should stay cozy in the class itself. #include <vector> #include <iostream> class stdHolder { public: stdHolder(); std::vector<int> getSV() const {return _myVector;} private: std::vector<int> _myVector; }; stdHolder::stdHolder() { _myVector.push_back(1); _myVector.push_back(2); _myVector.push_back(3); } int main() { stdHolder myHolder; // the following works std::vector<int> localSV = myHolder.getSV(); for (std::vector<int>::iterator it = localSV.begin(); it != localSV.end(); it++ ) { std::cout << "printing " << *it + 100 << std::endl; } //return 0; // comment this line to see my problem // the following loops forever for (std::vector<int>::iterator it = myHolder.getSV().begin(); it != myHolder.getSV().end(); it++ ) { std::cout << " printing " << *it + 100 << std::endl; } return 0;
My question ("why it doesn't work?") Because myHolder.getSV().begin() and myHolder.getSV().end() work on different vectors since you're calling the member function stdHolder::getSV() twice and for each invocation there will a different vector returned(as you're returning a vector by value). That is, the iterator it is initialized with myHolder.getSV().begin() but then you're comparing it(pun intended) with the result of myHolder.getSV().end() which is an iterator to a completely different vector returned by the call myHolder.getSV(). One way to solve this is by returning the vector by const reference. That way the first loop will copy from the returned value while the second loop will work correctly because it would be getting iterators off the same vector data member. Note that if you use this then for the second loop you would have to make it a const_iterator. See the comments in the below modified program: class stdHolder { public: stdHolder(); //-----------------------v---------------------------------->return by const lvalue reference const std::vector<int> &getSV() const {return _myVector;} private: std::vector<int> _myVector; }; stdHolder::stdHolder() { _myVector.push_back(1); _myVector.push_back(2); _myVector.push_back(3); } int main() { stdHolder myHolder; //still works std::vector<int> localSV = myHolder.getSV(); for (std::vector<int>::iterator it = localSV.begin(); it != localSV.end(); it++ ) { std::cout << "printing " << *it + 100 << std::endl; } //this works too now //---------------------vvvvvvvvvvvvvv--------------------------------------->const_iterator used instead of iterator for (std::vector<int>::const_iterator it = myHolder.getSV().begin(); it != myHolder.getSV().end(); it++ ) { std::cout << " printing " << *it + 100 << std::endl; } return 0; } Other option is to just add begin and end member function for your stdHolder and then you'll be able to use range-based for loop.
73,909,767
73,910,304
Why does g++ 11 trigger "maybe uninitialized" warning in connection with this pointer casting
After a compiler update from g++ v7.5 (Ubuntu 18.04) to v11.2 (Ubuntu 22.04), the following code triggers the maybe-uninitialized warning: #include <cstdint> void f(std::uint16_t v) { (void) v; } int main() { unsigned int pixel = 0; std::uint16_t *f16p = reinterpret_cast<std::uint16_t*>(&pixel); f(*f16p); } Compiling on Ubuntu 22.04, g++ v11.2 with -O3 -Wall -Werror. The example code is a reduced form of a real use case, and its ugliness is not the issue here. Since we have -Werror enabled, it leads to a build error, so I'm trying figure out how to deal with it right now. Is this an instance of this gcc bug, or is there an other explanation for the warning? https://godbolt.org/z/baaMTxhae
You don't initialize an object of type std::uint16_t, so it is used uninitialized. This error is suppressed by -fno-strict-aliasing, allowing pixel to be accessed through a uint16_t lvalue. Note that -fstrict-aliasing is the default at -O2 or higher. It could also be fixed with a may_alias pointer: using aliasing_uint16_t = std::uint16_t [[gnu::may_alias]]; aliasing_uint16_t* f16p = reinterpret_cast<std::uint16_t*>(&pixel); f(*f16p); Or you can use std::start_lifetime_as: static_assert(sizeof(int) >= sizeof(std::uint16_t) && alignof(int) >= alignof(std::uint16_t)); // (C++23, not implemented in g++11 or 12 yet) auto *f16p = std::start_lifetime_as<std::uint16_t>(&pixel); // (C++17) auto *f16p = std::launder(reinterpret_cast<std::uint16_t*>(new (&pixel) char[sizeof(std::uint16_t)]));
73,910,138
73,910,709
C++ terminate a thread without having acces to the function executed in the thread
I'm making a script handlers in C++14. I get function body in a lua script, that is suppose to be given by a client ( I use interpreter Sol/lua ), and exectute it in a thread. So my problems is if the client put a infinite loop (while true) in his script, I should be able to stop/kill the thread after 3 seconds. I tryed with and detach() but the infinite thread keep running during the entire rest of my programme. Without detach(), SIGABRT is send and stop everything at the end of my scope. #include <thread> #include <chrono> //function that i don't know the content. //In the worst case, it's an infinite loop. void infinitClientFunction() { while (true) {} } void callfunc() { std::thread t(infiniteClientFunction); t.detach(); std::this_thread::sleep_for(std::chrono::milliseconds(3500)); // I want t terminated/kill/stop here (if it is infinite). } int main(){ callfunc(); // But t still exist here. /* rest of my program. ... */ } That's doesn't seem complicated but I'm stuck. Please help me. Have a nice day. (EDIT) To specify, infiniteClientFunction is given by the client (by interpretting Lua Script but this is not the point). So if the client use a correct syntax and lexic but give an unlogic function, I should be able to stop it after a some time.
Nicol Bolas said, "C++ has no mechanism to kill threads." That's because there is no safe way to kill a thread in any language or in any OS. You can never be sure that, at the moment when the thread is killed, it hasn't left something in a bad state—e.g., left a mutex locked, left a data structure in an invalid state—that will prevent the rest of your program from functioning as it should. Running foreign code in your application always is a tricky proposition. The first step you can take toward doing it safely is to run the foreign code in a child process. Killing a process is much safer than killing a thread.
73,910,618
73,913,945
How to Handle Collision in 3D Grid based Game
How do games like 3D Games Minecraft with a grid handle collisions their are thousands of block divided into chunks each with its own bounding box how is collision detected calculated and processed i tried AABB but it didnt work well with each block having its own collider is their a way to check collision with a WHOLE MESH this is the crude AABB function i could come up with bool Entity::AABB(int x, int y, int z) { return (x - 1 <= Position.x && x >= Position.x - Size.x) && (y - 1 <= Position.y && y >= Position.y - Size.y) && (z - 1 <= Position.z && z >= Position.z - Size.z); } plz help... Thanks
Minecraft first calculates the player's AABB, then rounds it bigger to a whole number of blocks on each side, then checks whether the player's AABB (not rounded) collides with the AABB of any of the blocks in the rounded AABB. One extra block is added on the bottom, because fence blocks have AABBs that go up into the next block space above themselves. If the collision check didn't check one block below the AABB, it would miss out on fences. Chunks are irrelevant for this.
73,911,182
73,911,225
box2d falling while moving
Hey my player isn't falling while I'm pressing any of movement inputs while I'm falling. Just stands still and moves right or left. Just watch the video; Video My movement code; if (right == true) { p_pBody.body->SetLinearVelocity(b2Vec2(5, 0)); } else { p_pBody.rect.setPosition(p_xPos * s_METPX, p_yPos * s_METPX); // Set The SFML Graphics } if (left == true) { p_pBody.body->SetLinearVelocity(b2Vec2(-5, 0)); } else { p_pBody.rect.setPosition(p_xPos * s_METPX, p_yPos * s_METPX); // Set The SFML Graphics }
You're setting the vertical velocity to 0 when you're pressing right or left. That's the second coordinate of b2Vec2. If you want to have gravity, replace that zero with the vertical velocity the block has when the buttons are not being pressed.
73,911,444
73,920,036
How to use CHILDID_SELF?
I found this article and tried to follow it to find the position of the caret in any Windows application: How to get caret position in ANY application from C#? However, I have a problem with following it. This is the C# code I was following: var guid = typeof(IAccessible).GUID; object accessibleObject = null; var retVal = WinApiProvider.AccessibleObjectFromWindow(hwnd, WinApiProvider.OBJID_CARET, ref guid, ref accessibleObject); var accessible = accessibleObject as IAccessible; accessible.accLocation(out int left, out int top, out int width, out int height, WinApiProvider.CHILDID_SELF); But I have no idea how to put CHILDID_SELF in the fifth parameter of the IAccessible::accLocation() function: Rect rect; VARIANT varCaret; varCaret.vt = VT_I4; varCaret.lVal = CHILDID_SELF; std::cout << object->accLocation(&rect.x, &rect.y, &rect.w, &rect.h, varCaret); After some research, I found out that I should put CHILDID_SELF in this way. But it's not working as expected. I assume this should be able to get the position of the caret in Microsoft Edge or Chrome, but it just returns S_FALSE. The guy from the link also didn't get the caret position from Chrome or other windows, but made it work after adding CHILDID_SELF. So, I guess the problem I have is related to the way that I'm using CHILDID_SELF. I'm also using 21H1 build 19043.1889, but still I'm using 21H1 so it shouldn't be the problem, in my opinion. I also tried to just plug it in, but of course C++ didn't let me do that: object->accLocation(&rect.x, &rect.y, &rect.w, &rect.h, CHILDID_SELF); object->accLocation(&rect.x, &rect.y, &rect.w, &rect.h, (VARIANT)CHILDID_SELF); What would be the solution of this problem? Am I doing something wrong? FULL CODE #include <iostream> #include <Windows.h> #include <oleacc.h> #pragma comment(lib, "Oleacc.lib") typedef struct { long x; long y; long w; long h; } Rect; int main(int argc, char* argv[]) { HWND hwnd; DWORD pid; DWORD tid; while (true) { system("cls"); GUITHREADINFO info; info.cbSize = sizeof(GUITHREADINFO); hwnd = GetForegroundWindow(); tid = GetWindowThreadProcessId(hwnd, &pid); GetGUIThreadInfo(tid, &info); IAccessible* object = nullptr; if (SUCCEEDED(AccessibleObjectFromWindow(info.hwndFocus, OBJID_CARET, IID_IAccessible, (void**)&object))) { Rect rect; VARIANT varCaret; varCaret.vt = VT_I4; varCaret.lVal = CHILDID_SELF; object->accLocation(&rect.x, &rect.y, &rect.w, &rect.h, varCaret); std::cout << rect.x << std::endl; object->Release(); } Sleep(10); } return 0; } Used Microsoft Visual Studio 2019, x86, Debug to build
Your first code snippet is the correct way to pass CHILDID_SELF in a VARIANT parameter, per the documentation: How Child IDs Are Used in Parameters When initializing a VARIANT parameter, be sure to specify VT_I4 in the vt member in addition to specifying the child ID value (or CHILDID_SELF) in the lVal member. So, the problem must be something else. For instance, one thing I notice is that you are not initializing the COM library before calling AccessibleObjectFromWindow(). Try calling CoInitialize/Ex() first and see if it makes a difference. Also, you are not checking the return value of accLocation() for failure before using the RECT coordinates. Try this: #include <iostream> #include <Windows.h> #include <oleacc.h> #pragma comment(lib, "Oleacc.lib") typedef struct { long x; long y; long w; long h; } Rect; int main(int argc, char* argv[]) { HWND hwnd; DWORD pid; DWORD tid; CoInitialize(nullptr); // <-- add this while (true) { system("cls"); GUITHREADINFO info; info.cbSize = sizeof(GUITHREADINFO); hwnd = GetForegroundWindow(); tid = GetWindowThreadProcessId(hwnd, &pid); GetGUIThreadInfo(tid, &info); IAccessible* object = nullptr; if (SUCCEEDED(AccessibleObjectFromWindow(info.hwndFocus, OBJID_CARET, IID_IAccessible, (void**)&object))) { Rect rect; VARIANT varCaret; varCaret.vt = VT_I4; varCaret.lVal = CHILDID_SELF; if (SUCCEEDED(object->accLocation(&rect.x, &rect.y, &rect.w, &rect.h, varCaret))) { std::cout << rect.x << std::endl; } object->Release(); } Sleep(10); } CoUninitialize(); // <-- add this return 0; }
73,911,466
73,911,730
How come Gdiplus SolidBrush's RGB is different from regular RGB?
I'm trying to paint a simple header on top of my Window with Gdiplus' SolidBrush, but whenever I set the RGB color it's different from what it's suppose to be. How come this is happening? And is there a way to fix that? Thanks! Gdiplus' SolidBrush RGB: Regular RGB:
You are using the Color constructor taking four arguments, a, r, g, and b, in this order. (255, 255, 0, 0) thus means: Fully opaque (first value), red channel at full intensity (second value), and no contribution from other color channels. In other words: You're creating a fully opaque red brush as illustrated in the application screenshot. If you wish to create a Color value from the color channels only, there's a convenience constructor taking r, g, and b arguments. The opacity is implied to be 255 (i.e. fully opaque). Gdiplus::SolidBrush brush(Gdiplus::Color(255, 255, 0)); creates a fully opaque, bright yellow brush.
73,911,521
73,911,594
Nan behaves differently in #pragma cpp
I am learning about the NaN datatype, so, I ran a code to understand it and it goes well, the code worked as expected, but when I add a line #pragma GCC optimize("Ofast") in my code then, it behaves unexpected. I am curious why?? #pragma GCC optimize("Ofast") // C++ code to check for NaN exception // using "==" operator #include <cmath> #include <iostream> using namespace std; // Driver Code int main() { float a = sqrt(2); float b = sqrt(-2); // Returns true, a is real number // prints "Its a real number" a == a ? cout << "Its a real number" << endl : cout << "Its NaN" << endl; // Returns false, b is complex number // prints "Its nan" b == b ? cout << "Its a real number" << endl : cout << "Its NaN" << endl; return 0; } The ouput without pragma is Its a real number Its NaN But after using pragma it gives Its a real number Its a real number
-Ofast turns on -ffast-math, which turns on -ffinite-math-only, which does the following (from the gcc documentation here: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html) -ffinite-math-only Allow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or +-Infs. This option is not turned on by any -O option since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications. I think the "-O option" part is wrong since the -Ofast documentation says it "disregards strict standards compliance". That, or by "any -O option" they mean -O1, -O2, -O3.
73,911,952
73,911,975
Copying values from base class to derived class
Didnt want to put a really long title, continuing - without modifying the base class and without copying one by one. Lets say the base is CClient, but I dont want to add or remove anything: class CClient { public: void (*Connect)(); void (*Disconnect)(); bool m_bIsConnected; }; And say this is derived CClientHook. class CClientHook : public CClient { public: bool Setup(bool hook); bool m_bIsHooked; }; How can I copy values from CClient object to CClientHook object safely? Sorry for weird wording. EDIT: To clarify, there are two objects and no, Connect and Disconnect arent supposed to be methods. CClient g_Client; CClientHook g_ClientHook;
Given CClient a; CClientHook b; There are at least two options: static_cast<CClient &>(b) = a; b.CClient::operator=(a);
73,912,729
73,912,730
What's the name of all the angle brackets?
In C++ we have angle brackets in different places and I think it's sometimes important to distinguish them when talking to other developers, e.g. during mob programming when navigating someone (e.g. "go to the arrow operator in line 36" or "now write the spaceship operator"). While I can of course call them "angle brackets", I think they have better names, depending on what they do. I am thinking of comparison, like bool smaller = a < b; bit shift, like auto x = 1 << 8; console output, like std::cout << "Hello"; console input, like int age; std::cin >> age; types, like std::vector<int> v; templates, like template<typename T> T t() { return 0;} member templates, if that is any different to 6. lambda parameters, like []<int>(){ return 5;} as part of pointers, like a->b(); similarly, but with an additional asterisk, like x->*member(); the new comparison, like int compare = a <=> b; the new return types, like auto main() -> int{} maybe even includes, like #include <iomanip>;, although these are preprocessor and not C++ for completeness sake, the funny stuff like <: and :> or ??< and ??>
In many cases, the angle brackets do not have a name themselves, because they are part of another construct. is called relational operator [source: C++ 20 standard, chapter 7.6.9, [expr.rel], page 140], also comparison operator or just less-than operator and greater-than operator is called shift operator [source: C++ 20 standard, chapter 7.6.7, [expr.shift], page 139] is called insertion operator [source: C++ 20 standard, chapter 29.7.5.6, [ostream.rvalue], page 1422], technically it's implemented as operator<<, just like the shift operator, but of course we don't call it shift operator, because we don't shift a stream. is called extraction operator [source: C++ 20 standard, chapter 29.7.4.6, [istream.rvalue], page 1413] I've also heard the term chevron operator as the superordinate term for both, insertion operator and extraction operator. the whole thing (angle brackets plus type(s)) is called a template argument list [sources: C++ 20 standard, chapter 13.3, [temp.names], page 366, and chapter 13.4.1 (4), [temp.arg], page 369]. the whole thing is a template parameter list [source: C++ 20 standard, chapter 13.1, [temp.pre], page 360] like 6 this is also called a template parameter list [source: C++ 20 standard, chapter 7.5.5.1 (5), [expr.prim.lambda.general], page 103] Regarding the last four: it's a parameter list in the declaration and an argument list when it's used. is an arrow or -> operator (probably pronounced arrow operator) [source: C++ 20 standard, chapter 7.6.1.5, [expr.ref], page 110]. is a pointer to member operator [source: C++ 20 standard, chapter 7.6.4, [expr.mptr.oper], page 137]. is called the three way comparison operator [source: C++ 20 standard, chapter 7.6.8, [expr.spaceship], page 140] or simply the spaceship operator. is called a trailing return type [source: C++ 20 standard, chapter 9.3.1, [dcl.decl.general], page 183]. For concepts, there's a similar thing called return type requirement [source: C++ 20 standard, chapter 7.5.7.4, [expr.prim.req.compound], page 115] is a header name [source: C++ 20 standard, chapter 5.8, [lex.header], page 16] and similar in [source: C++ 20 standard, chapter 15.2, [cpp.cond], page 462] the whole thing is a digraph [source: C++ 20 standard, chapter 5.5, [lex.digraph], page 15] or trigraph (until C++14) [source: C++ 20 standard, chapter C.2.2, [diff.cpp14.lex], page 1662]
73,912,844
73,913,417
.txt File passed into ifstream turns contained data into garbage characters?
I'm trying to make a simple program for a comp sci class that goes through a list of data in a text file, and assigns it to two different arrays using pointer notation, but I'm running into an issue where the file I'm reading will be corrupted after running the program, but even when the program is terminated and restarted, it seems to still understand the data even though it only shows up as junk unicode/japanese characters when I open it up in a text reader like notepad after the fact? I'm not sure if this is an issue with my IDE or not, as I don't have any declarations to output to the file after it's read. Here's what the text file looks like before running the program: https://pastebin.com/raw/JYww96RV This is what it looks like after being ran: https://pastebin.com/raw/yLzDaAtj This is what I have for code: #include <iostream> #include <iomanip> #include <cstdlib> using namespace std; int readFile(int* &id, int* &group); void sortArrays (int *userDataArray, int *identifierDataArray, int arraySize); int binarySearch (int *userDataArray, int *identifierDataArray, int arraySize, int searchValue); int main() { int *ids; int *groups; int sizes; sizes = readFile(ids, groups); for (int i = 0; i < sizes; i++) { cout << *(groups + i) << " " << *(ids + i) << endl; } cout << endl; delete[] ids; delete[] groups; return 0; } int readFile(int* &id, int* &group) { ifstream userData; // We're going to start by declaring our data stream 'userData' userData.open("data.txt"); // Our data stream is now going to open and associate itself with the 'data.txt' file if (!userData) // This is a simple check if the file was properly found, if it wasn't, the error message below will be displayed { cout << "Error reading file! Make sure your data file is named 'data.txt'"; exit(1); } int sizes; userData >> sizes; id = new int[sizes]; group = new int[sizes]; for (int i = 0; i < sizes; i++) userData >> *(id + i) >> *(group + i); userData.close(); return sizes; } I apologize if I didn't do a justice to explaining this problem properly, but I'm a little bit stuck on where to go from here or how to properly find a fix online as I'm new to the language
It seems like it wasn't an issue with the code at all, but an issue with how windows notepad would first read the file in UTF-8, and after running the program, would switch over to UTF-16 LE as Avi alluded to in the comments.
73,913,006
73,913,076
Why is GCC giving me a use of uninitialized value warning?
I've been working on a large C++ program and I forgot to add my usual list of compiler flags/warnings when working on a C project. After enabling the -fanalyzer flag, I began to get a lot of "warning: use of uninitialized value '<unknown>'" messages from GCC 12.2 throughout my code. Here is an isolated example I was able to generate in Compiler Explorer: #include <string> std::string square(int num) { return std::to_string(num * num); } Compiler output: <source>: In function 'std::string square(int)': <source>:4:36: warning: use of uninitialized value '<unknown>' [CWE-457] [-Wanalyzer-use-of-uninitialized-value] 4 | return std::to_string(num * num); | ^ 'std::string square(int)': events 1-2 | | 3 | std::string square(int num) { | | ^ | | | | | (1) region created on stack here | 4 | return std::to_string(num * num); | | ~ | | | | | (2) use of uninitialized value '<unknown>' here | <source>:4:36: warning: use of uninitialized value '<unknown>' [CWE-457] [-Wanalyzer-use-of-uninitialized-value] 4 | return std::to_string(num * num); | ^ 'std::string square(int)': events 1-2 | | 3 | std::string square(int num) { | | ^ | | | | | (1) region created on stack here | 4 | return std::to_string(num * num); | | ~ | | | | | (2) use of uninitialized value '<unknown>' here | Does this simple square function really have such a problem? Or am I missing something bigger? Is the static analysis in GCC broken?
It is clearly a false positive. The analyzer complains about any function returning a std::string (and other standard library types), e.g. #include <string> std::string f() { return {}; } as well. (https://godbolt.org/z/oKrfrbn5o) Surprisingly I could not find any previous bug report on this seemingly obvious issue. However, @JasonLiam has filed one here. -Wanalyzer-use-of-uninitialized-value is also a relatively new feature, added with GCC 12, so it might simply still need some improvements. It can be disabled while leaving other analyzer checks in effect by adding -Wno-analyzer-use-of-uninitialized-value. As it turns out, per developer answer in the linked bug report, -fanalyzer is currently not working properly with C++ and is not recommended to be used on C++ code. A meta bug tracking C++ issues can be found here.
73,913,232
73,924,933
Defining the size of an array on a custom templated Array class
I am making a project to write from scratch several datastructures, procedures, probably a mini-testing framework... things already well known and coded, but just with the purpose of learn and to adquire a much more deeper knowledge of the fundamentals of programming, but in a modern way, or, at least, using the modern tools of the C++ language. So, there's the repo for the code. Zero. The code provided there is currently working under Unix systems, with clang >= 14. Also, the repo contains a tool called Zork, that is a custom C++ project builder focused on build C++ project with the C++20 modules feature. On the root folder of the project, you will find a zork++ file, that is the compiled binary for execute the tool. So, with just ./zork++ the tool will compile and link the project. That's an entry point as an ultra basic testing tool, that is just the main.cpp file calling the things and kind of testing it's funcionalities. There's a zork.conf file, that is the configuration file to set up the commands that will be sent to the compiler to automate the project. This spoiler is for provide the real code behind the question. I plan to make several questions on Stack Overflow for this project, so this one is setted as a base explanation for the "code example" required usually. After this, let's go with the real question. I started for make collections. Custom ones. So, for me, the very basic one (things should be the easy first ones, and then code to the most difficult ones in difficulty ascending order) is to simulate the C++ Array class. This is the snippet: export namespace zero::collections { template <typename T, unsigned long> class Array { private: T array[]; }; } First doubt is about the second parameter of the templated class. Second parameter must provide the desired initial capacity of the array member. I just choose long because is long enought to store any signed number (I guess that is too much...). I don't know the formal way in C++ of define this parameters that have real sense with the implementation. A simple int would fit for most common cases. But I want to make it perfectly generic. I thought about constraint it with a concept. The idea is that parameter, must be an unsiged natural number. But not specifically a short, and int or a long. Something like number, for example. But I can't figure out the best way of code the requirement. What could be the formal way of defining this requirement in modern C++, and use that template parameter to const initialize the array with a fixed size?
Your are looking for the std::size_t, which can be found on some system headers. Extracted from cppreference: Defined in header cstddef Defined in header cstdio Defined in header cstdlib Defined in header cstring Defined in header ctime Defined in header cuchar Defined in header cwchar (since C++17) Basically, you should include one of them, and use std::size_t for the template parameter that must define the amount of elements that the user wants to store in the array. export module your_module; #include <cstddef> export namespace zero::collections { template <typename T, std::size_t N> class Array { private: T array[N]; }; } Also note that you must define the size of the array member with the type parameter N.
73,914,306
73,915,038
PrintDlgEx invalid argument, while PrintDlg works
Problem: I need to get PrintDlgEx working for my project, but no combination of options or arguments works for me. It gives E_INVALIDARG for any combinations of options, as the ones I copied from Microsoft samples or other online samples. Replacing PRINTDLGEX with PRINTDLG and PrintDlgEx with PrintDlg (and eliminating the group of options only from PRINTDLGEX) works fine. Unfortunately I need PrintDlgEx, because I really need the Apply button, to change printers or property sheet without printing, for design and preview. Please help me find why I can't get the dialog to show. Code: while I simplified pieces, like what should happen on successful return, or setting DEVMODE and DEVNAMES, I tried this function exactly, with the same result: Invalid Argument. #include <QDebug> #include <QWindow> #include <windows.h> void showPrintDialog() { // Simplifying the setup: real code passes in a QWidget * QWidget *caller = this; // Not returning a value or doing any work. I just want the dialog to pop up for now // Create the standard windows print dialog PRINTDLGEX printDialog; memset(&printDialog, 0, sizeof(PRINTDLGEX)); printDialog.lStructSize = sizeof(PRINTDLGEX); printDialog.Flags = PD_RETURNDC | // Return a printer device context. Without this, HDC may be undefined PD_USEDEVMODECOPIESANDCOLLATE | PD_NOSELECTION | // Don't allow selecting individual document pages to print PD_NOPAGENUMS | // Disables some boxes PD_NOCURRENTPAGE | // Disables some boxes PD_NONETWORKBUTTON | // Don't allow networking (but it show "Find printer") so what does this do ? PD_HIDEPRINTTOFILE; // Don't allow print to file // Only on PRINTDLGEX // Theis block copied from https://learn.microsoft.com/en-us/windows/win32/dlgbox/using-common-dialog-boxes?redirectedfrom=MSDN // I have tried multiple combinations of options, including none, I really don't want any of them printDialog.nStartPage = START_PAGE_GENERAL; printDialog.nPageRanges = 1; printDialog.nMaxPageRanges = 10; LPPRINTPAGERANGE pageRange = (LPPRINTPAGERANGE) GlobalAlloc(GPTR, 10 * sizeof(PRINTPAGERANGE)); printDialog.lpPageRanges = pageRange; printDialog.lpPageRanges[0].nFromPage = 1; printDialog.lpPageRanges[0].nToPage = 1; printDialog.Flags2 = 0; printDialog.ExclusionFlags = 0; printDialog.dwResultAction = 0; // This will tell me if PRINT // Rest of options are also on PRINTDLG printDialog.nMinPage = 1; printDialog.nMaxPage = 10; // The only options I really need printDialog.nCopies = 1; printDialog.hDevMode = Q_NULLPTR; // which will be better once this works printDialog.hDevNames = Q_NULLPTR; // which will be better once this works printDialog.hwndOwner = reinterpret_cast<HWND>(caller->windowHandle()->winId()); // Calling... int result = PrintDlgEx(&printDialog); qDebug() << (result == E_INVALIDARG ? "Invalid Argument\n" : "Success\n"); // It always is E_INVALIDARG // Cleanup if (printDialog.hDevMode) GlobalFree(printDialog.hDevMode); if (printDialog.hDevNames) GlobalFree(printDialog.hDevNames); if (printDialog.hDC) DeleteDC(printDialog.hDC); } Platform: Windows 10, latest update; Qt version: 5.12.7 or higher (since in VM I have 5.15.1) The fact that I am running in Qt should be irrelevant, since this is all WIN API, beyond the c++ version (11)
I can make your example work if I remove PD_NONETWORKBUTTON flag. Please note that while it is documented for PRINTDLGA struct, it is NOT listed in PRINTDLGEXA NOTE: I did get the same error with that flag.
73,914,315
73,914,362
Can you "swap" slices of C++ std vectors?
If I have two C++ vectors: vector<int> a(5) {1,2,3,4,5}; vector<int> b(5) {6,7,8,9,10}; is there a one-line way to use the swap method to swap slices of a and b? Something like swap(a[something ... something], b[something ... something]); giving, for instance a equal to {1,9,10,4,5} and b equal to {6,7,8,2,3}?
std::swap_ranges. std::swap_ranges(a.begin()+1, a.begin()+3, b.begin()+3); Demo
73,914,499
73,914,628
How to delete a specific node in a linked list?
I have the next linked list code: #include <iostream> #include <string> using namespace std; #define null 0 class Node { public: string name; int age; Node *next; Node(string name, int age) { this->age = age; this->name = name; this->next = null; } }; class LinkedList { private: Node *head; public: LinkedList() { this->head = null; } void insert(string name, int age) { Node *nodenew = new Node(name, age); nodenew->next = null; if (this->head == null) { this->head = nodenew; } else { Node *temp = this->head; while (temp->next != null) { temp = temp->next; } temp->next = nodenew; } } void print() { if (this->head == null) { cout << "Empty"; } Node *temp = this->head; while (temp != null) { cout << temp->name << ", " << temp->age <<endl; temp = temp->next; } } void deletePerson(string name){ Node *temp = this->head; Node* prev = null; if (temp!=null && temp->name == name) { this->head = temp->next; delete temp; return; }else { while (temp != null && temp->name == name) { prev = temp; temp = temp->next; } if (temp == null) { return; } prev->next = temp->next; delete temp; } } }; int main(int argc, char const *argv[]) { LinkedList list; list.insert("David", 45); list.insert("John", 23); list.insert("Katty", 78); list.insert("Stephanie", 25); list.deletePerson("Katty"); list.print(); return 0; } I am trying to delete a node by a given name with the next method: void deletePerson(string name){ Node *temp = this->head; Node* prev = null; if (temp!=null && temp->name == name) { this->head = temp->next; delete temp; return; }else { while (temp != null && temp->name == name) { prev = temp; temp = temp->next; } if (temp == null) { return; } prev->next = temp->next; delete temp; } } But when I compile my code it doesn´t show me anything in console, it just show the next code error: code=3221225477 I tried to debugger my code but vscode just swap me to other class, in prev->next = temp->next; part it just show a little message that says: Exception has occurred. X Segmentation fault My expected output would be: David, 45 John, 23 Stephanie, 25 I hope you can help me to solve that, thanks.
your problem is so simple, it's in that line: while (temp != null && temp->name == name) it should be: while (temp != null && temp->name != name) as the condition of looping, you are looping until you either didn't reach the end (temp != null) or the name isn't found in this iteration (temp->name != name). also, there is a small warning at this line: prev->next = temp->next; imagine if you didn't find the node, then temp will be null, and the line temp->next; will throw an error as you are trying to dereference a null pointer. I know you handled this situation in your code as you wrote: if (temp == null) { return; } but for safety reasons or in case your compiler complained about it as mine, you should check if both prev and temp are null pointers or not, so it should be: if(null != prev && null != temp) prev->next = temp->next; after this edited, this is the output: David, 45 John, 23 Stephanie, 25
73,914,687
73,914,701
Deleting a dynamic array of vectors
I believe this should be pretty simple and straightforward. Why am I getting an error? Here is the code: std::vector<double> *myVectorArr; myVectorArr = new std::vector<double>[10]; delete myVectorArr; The error I get is: munmap_chunk(): invalid pointer Aborted (core dumped) Why would I be getting this error? Thanks in advance!
You need to use the operator delete [] instead of the operator delete delete [] myVectorArr;
73,915,429
73,915,726
Why does my program terminate when it should continue?
#include <iostream> #include <ctime> using namespace std; int main() { int answer; string question; string play = ""; srand(time(NULL)); cout << "What question would you like to ask the Magic 8 ball?: \n"; cout << "\n"; cin >> question; answer = rand () % 8 + 1; if (answer == 1) { cout << "The answer is: It is certain\n"; } else if (answer == 2) { cout << "The answer is: It is decidely so\n"; } else if (answer == 3) { cout << "The answer is: Most likely\n"; } else if (answer == 4) { cout << "The answer is: Signs point to yes\n"; } else if (answer == 5) { cout << "The answer is: Ask again later\n"; } else if (answer == 6) { cout << "The answer is: Don't count on it\n"; } else if (answer == 7) { cout << "The answer is: My sources say no\n"; } else { cout << "The answer is: Reply hazy, try again\n"; } cout << "Would you like to play again?(y/n): "; cin >> play; if (play == "yes" || play == "y") { cin >> question; } else if (play == "no" || play == "n") { cout << "Thank you for playing with the Magic 8 Ball"; } return 0; } It stops the program after it gives my answer, not letting the user answer if they want to play again or not. Please help me, I've been stuck on this for a while now and don't know what to do.
you did most of the work you just have to make a loob like so #include <iostream> #include <ctime> using namespace std; int main() { int answer; string question; string play = ""; srand(time(NULL)); while(play!="no"&&play!="n") { play = ""; cout << "What question would you like to ask the Magic 8 ball?: \n"; cout << "\n"; cin >> question; answer = rand () % 8 + 1; if (answer == 1) { cout << "The answer is: It is certain\n"; } else if (answer == 2) { cout << "The answer is: It is decidely so\n"; } else if (answer == 3) { cout << "The answer is: Most likely\n"; } else if (answer == 4) { cout << "The answer is: Signs point to yes\n"; } else if (answer == 5) { cout << "The answer is: Ask again later\n"; } else if (answer == 6) { cout << "The answer is: Don't count on it\n"; } else if (answer == 7) { cout << "The answer is: My sources say no\n"; } else { cout << "The answer is: Reply hazy, try again\n"; } cout << "Would you like to play again?(y/n): "; while(play != "no" && play != "n"&& play != "y" && play != "yes") {cin >> play; if (play == "no" || play == "n") { cout << "Thank you for playing with the Magic 8 Ball"; } else if (play != "no" && play != "n"&& play != "y" && play != "yes") { cout<<"you enter an unknown value, try agein"<<endl; } } } return 0; } i declare (string play) then i reassign it so it could not save the y/n answer from round to round cuz that would break the program and i add a loob down the code that will get you y/n answer more effective
73,915,510
73,915,698
use std::string to call a function in C++11
I want to use string value to call a function. Is this possible? Can someone please show some implementation. I would appreciate it. class obj { int num1; int num2; } int func1(obj o) { return o.num1 + o.num2; } // This is an example data set. This map would be populated with values in the map below with some piece of code. std::map<std::string, std::string> funcNameMap = {{"func1", "func1"}}; int someFunction(std::string funcName, obj o) { // Get the value associated with the string "funcName" i.e. "func1". // Calls function "func1" with value "o" and returns the value. } int main(){ obj o; o.num1 = 1; o.num2 = 2; auto x = someFunciton("func1", o); std::cout << x << std::endl; return 0; } I am writing a program that collect metric data. I want to execute a particular function for a particular metric. I would name all the functions same as the metric name so that when I give metric name as input (string) it would execute a particular function. I don't want if-else for executing function based on the metric name input as my program is collecting over a hundred metric. It would look pretty awkward to have that may if-else. That is why I am trying to do something this way. Want something that works for both OSs windows/linux
One solution is to create a mapping from function name to function itself. We know that a function is a pointer in C/C++, so we can easily do this after confirming the type of the function pointer. In your case, the target function type is int (*)(obj). Code snippet: #include <iostream> #include <map> #include <string> class obj { public: int num1; int num2; }; int func1(obj o) { // type: int (*)(obj) return o.num1 + o.num2; } // create the mapping from name to function std::map<std::string, int (*)(obj)> funcNameMap = {{"func1", func1}}; int someFunction(std::string funcName, obj o) { // Get the value associated with the string "funcName" i.e. "func1". // Calls function "func1" with value "o" and returns the value. auto fn = funcNameMap.at(funcName); return fn(o); } int main(){ obj o; o.num1 = 1; o.num2 = 2; auto x = someFunction("func1", o); std::cout << x << std::endl; return 0; } Edit: Update according to the comment, use dynamic shared library to avoid manually creating the mapping. I assume you are using Linux. First, move class definition and the type of target functions into a separated header obj.hpp: class obj { public: int num1; int num2; }; // type of target functions typedef int (*ftype)(obj); Collect target functions to a separated file functions.cpp to build dynamic shared library. #include "obj.hpp" extern "C" int func1(obj o) { return o.num1 + o.num2; } extern "C" int func2(obj o) { return o.num1 - o.num2; } In the third file main.cpp, we retrieve functions from the library according to the function name. #include <iostream> #include <map> #include <dlfcn.h> #include <cassert> #include "obj.hpp" // name mapping: public name to inner name std::map<std::string, std::string> funcNameMap = {{"add", "func1"}, {"sub", "func2"}}; int retrieve_fn(void *dl_handler, std::string funcName, obj o) { assert(dl_handler != NULL && funcNameMap.count(funcName) != 0); auto real_fn_name = funcNameMap[funcName]; auto fn = (ftype)dlsym(dl_handler, real_fn_name.c_str()); auto dl_err = dlerror(); if (dl_err) { std::cerr << "Load failed: " << dl_err << std::endl; return -999; } return fn(o); } int main(){ obj o; o.num1 = 1; o.num2 = 2; // open dynamic shared library auto dl_name = "./functions.so"; auto dl_handler = dlopen(dl_name, RTLD_LAZY); auto dl_err = dlerror(); if (dl_err) { std::cerr << "Open failed: " << dl_err << std::endl; return -1; } auto x = retrieve_fn(dl_handler, "add", o); std::cout << x << std::endl; x = retrieve_fn(dl_handler, "sub", o); std::cout << x << std::endl; dlclose(dl_handler); return 0; } Build a dynamic shared library from functions.cpp. $ g++ functions.cpp -shared -fPIC -o functions.so Build an executable file from main.cpp. $ g++ main.cpp -ldl -o main Run and check the results. $ ./main 3 -1
73,915,646
73,915,710
How to create a click effect on a QLabel?
How i could create a click effect similar to push buttons on a QLabel? QPixmap pixmap; pixmap.load(":/files/hotkeys.png"); int w = 131; int h = 71; pixmap = pixmap.scaled(w, h, Qt::KeepAspectRatio); // Label ui.label->setGeometry(220, 220, w, h); ui.label->setPixmap(pixmap); // Button QIcon icon(pixmap); ui.toolButton->setIconSize(QSize(w, h)); ui.toolButton->setIcon(icon); ui.toolButton->setStyleSheet("QToolButton { background-color: transparent }"); By click effect i mean like when you click on a push button containing a picture:
Ideally you'd just use a QToolButton or QPushButton, but if you must use a QLabel, you could do it by subclassing QLabel with a custom paintEvent() to give the desired effect, something like this: class MyLabel : public QLabel { public: MyLabel(const QPixmap & pm) : _isMouseDown(false) {setPixmap(pm);} virtual void mousePressEvent( QMouseEvent * e) {_isMouseDown = true; update(); e->accept();} virtual void mouseReleaseEvent(QMouseEvent * e) {_isMouseDown = false; update(); e->accept();} virtual void paintEvent(QPaintEvent * e) { QPainter p(this); const int offset = _isMouseDown ? 2 : 0; p.drawPixmap(QPoint(offset, offset), *pixmap()); } private: bool _isMouseDown; };
73,916,368
73,932,520
Invalid value while PeakCAN canbus frame printing QT C++
I'm trying to read and print the frame from canbus using the peakcan plugin with QT, but I think I'm making a mistake somewhere. This is my code : qDebug() << "connectCanDevice"; if (QCanBus::instance()->plugins().contains(QStringLiteral("peakcan"))) { // plugin available QString errorString; QCanBusDevice *device = QCanBus::instance()->createDevice( QStringLiteral("peakcan"), QStringLiteral("usb0"), &errorString); if (!device) { // Error handling goes here qDebug() << "Device cannot be created"; } else { qDebug() << "Bit Rate Configration"; device->setConfigurationParameter(QCanBusDevice::BitRateKey, 250000); device->setConfigurationParameter(QCanBusDevice::DataBitRateKey, 100000); device->errorOccurred(QCanBusDevice::ReadError); if(device->connectDevice()) { qDebug() << SIGNAL (framesReceived()); qDebug() << device->framesAvailable(); while(device->framesAvailable()) { QCanBusFrame frame = device->readFrame(); QString test = frame.toString(); std::string text = test.toUtf8().constData(); qDebug()<<test; std::cout<<text<<std::endl; } } } } Here is the output : connectCanDevice qt.canbus.plugins.peakcan: Using PCAN-API version: 4.6.1.728 Bit Rate Configration qt.canbus.plugins.peakcan: Unsupported data bitrate value: 100000 2framesReceived() 0 As a beginner, I couldn't understand much from the qt documents. I can see the frame with Pcanview. There is no problem with canbus.
OK, I see you're missing some points here, this is an simple code example that do the work: if (QCanBus::instance()->plugins().contains(QStringLiteral("socketcan"))) { QString errorString; QCanBusDevice *device = QCanBus::instance()->createDevice( QStringLiteral("socketcan"), QStringLiteral("can0"), &errorString); if (!device) { qDebug() << errorString; } else { bool retval = device->connectDevice(); if(retval == false) { qDebug() << "cannot open CAN interface"; } else { QObject::connect(device, &QCanBusDevice::framesReceived, [=] () { while(device->framesAvailable() > 0) { auto frame = device->readFrame(); QString d = QString("%1 # ").arg(frame.frameId(), 3, 16, QChar('0')); for(int i = 0;i < frame.payload().length();i ++) { d += QString("%1 ").arg(static_cast<uint8_t>(frame.payload().at(i)), 2, 16, QChar('0')); } qInfo() << d; } }); } } } I've used a lambda function here to be short, but you can use other options as you want. I also tested it with socketcan since pcan driver is used by that. Short explanation: I connect QCanBusDevice::framesReceived signal to my function that will be called when a frame(s) has received. then I read all available frames and print it out. You can read more about Qt signal/slot mechanism here
73,916,679
73,922,811
Copying variables, creating temporary variables and move semantics
I was learning about move semantics and rvalue references when I came across this web page https://www.open-std.org/JTC1/SC22/WG21/docs/papers/2006/n2027.html. There is a piece of code that confuses me. Without move semantics template <class T> swap(T& a, T& b) { T tmp(a); // now we have two copies of a a = b; // now we have two copies of b b = tmp; // now we have two copies of tmp (aka a) } With move semantics template <class T> swap(T& a, T& b) { T tmp(std::move(a)); a = std::move(b); b = std::move(tmp); } How can we perform two copies of a b and tmp. Specially a and b since they are passed by reference.
Let a' and b' be the values in a and b before the function. template <class T> swap(T& a, T& b) { T tmp(a); // now we have two copies of a' (in a and tmp) and one of b' (in b) a = b; // now we have two copies of b' (in a and b) and one of a' (in tmp) b = tmp; // now we have two copies of a' (in b and tmp) and one of b' (in a) } that might help. Then we do the move version: template <class T> swap(T& a, T& b) { T tmp(std::move(a)); // a' is in tmp; b' is in b; a is moved-from a = std::move(b); // a' is in tmp, b' is in a; b is moved-from b = std::move(tmp); // a' is in b; b' is in a; tmp is moved-from } the trick is to distinguish between the variable a and the value stored in a.
73,917,256
73,953,709
what grpc c++ `grpc_prefork()` does?
In docs of grpc_prefork() it is written that gRPC applications should call this before calling fork(). There should be no active gRPC function calls between calling grpc_prefork() and grpc_postfork_parent()/grpc_postfork_child(). what this function does? why is it needed? what are grpc function calls? If I have a server that implements some service, and the method of that service is called and not finished, is this a grpc function call?
To start, this function is a part of gRPC Core, not gRPC C++. This is an API for developers of new language bindings for gRPC, e.g. Rust, Haskell. If you're just working with C++, then the grpc_prefork function does not apply to you and you can stop reading. grpc_prefork is how we deal with the fact that threads and the fork syscall do not work well together. When a thread calls fork, only that single thread is copied into the child thread. In the child process, it's as if all of the other threads in the parent process had simply disappeared, regardless of what they were doing. Some might have held a mutex balancing a tree shared between threads. Some might have been doing I/O. As a result, the state in the child process is a minefield of violated assumptions. I like to use the metaphor of everyone else in the world but you suddenly vanishing. It might be peaceful for a bit, but pretty soon planes will start falling out of the sky and nuclear reactors will start melting down. grpc_prefork is a solution to this problem. It's intended to be registered with pthread_atfork. When a thread (thread A) calls fork, it will first run grpc_prefork. This flips a bit signalling to all other threads in the process that they need to close all FDs and come to a known safe state (i.e. no holding any mutexes or actively modifying any data structures). Thread A will block waiting for all other threads to reach that safe state. After that, grpc_postfork_parent is called in the parent and grpc_postfork_child is called in the child. This puts the planes back in the air and the nuclear plant workers back to work, so to speak. what are grpc function calls This means any gRPC Core API. Not many of them are blocking, so it's not a huge concern. The main blocking function that we'd be worried about here is grpc_completion_queue_next, which drives most work in gRPC Core.
73,917,303
74,160,554
Spectra is not computing any values for large sparse matrix?
In a C++ program I computed a large sparse matrix energy_mat which I know is symemtric. I am trying to compute its condition number by getting the largest and smallest eigen values like this: Spectra::SparseGenMatProd<double> op(energy_mat); Spectra::GenEigsSolver<Spectra::SparseGenMatProd<double>> eigs(op, 3, 6); // Initialize and compute eigs.init(); int nconv = eigs.compute(Spectra::SortRule::LargestMagn); // Retrieve results Eigen::VectorXcd evalues; if (eigs.info() == Spectra::CompInfo::Successful) evalues = eigs.eigenvalues(); std::cout << "Eigenvalues found:\n" << evalues << std::endl; I see: Eigenvalues found: I.e. the array is empty. However I know that energy mat is symmetric (I checked) and I am later using it to solve a linear system of equations, so it's numerically sound (it doesn;t have nans or infs). Why is spectra fidning no eigen values?
Increasing the number of iterations from 6 to 40 seems to have fixed the issue.
73,917,322
73,917,566
Check number range in Preprocessor macro
To set the clock prescaler on the Atmega32u4, you have to set TCCR0B according to this table: If you want the prescaler to be 64, you would write this: TCCR0B |= BV(CS01) | BV(CS00); btw, here is BV(): #define BV(x) (1<<x) I want to do this using a macro, this is what I have so far: #define CLK_SEL(n) ((n == 256 || n == 1024) ? BV(CS02) : 0) | \ ((n == 8 || n == 64) ? BV(CS01) : 0) | \ ((n == 1 || n == 64 || n == 1024) ? BV(CS00) : 0) I now want to check if N is equal to 1, 8, 64, 256, or 1024. How would I accomplish this? I tried it using #if and #error, but I haven't come up with a solution that compiles, unfortunately.
Tail wagging the dog; trying to convert some arbitrary bit pattern to one from a selected. limited range... int main() { enum { ePreScl_1 = 1, ePreScl_8, ePreScl_64, ePreScl_256, ePreScl_1024 }; printf( "%X\n", ePreScl_1 ); printf( "%X\n", ePreScl_8 ); printf( "%X\n", ePreScl_64 ); printf( "%X\n", ePreScl_256 ); printf( "%X\n", ePreScl_1024 ); return 0; } 1 // 001 2 // 010 3 // 011 4 // 100 5 // 101
73,917,624
73,917,739
Does this cause memory leakage by not freeing the function pointer? C++
Does this code architecture cause memory leakage by not freeing m_func? And could this be tempered with if this code would be executed at a closed server? Like finding the address of the pointer and replacing the code of the function pointee with malicious code? If so how could I solve this? #include <iostream> template <typename Func> struct endpoint_t { void* m_func; endpoint_t(Func&& func) : m_func((void*) func) {} auto execute() { return ((Func*) m_func)(); } }; int hello_world() { std::cout << "Hello World! \n"; return 0; } int main() { endpoint_t end(hello_world); end.execute(); } Edit: This is the actual goal of the code: To store multiple endpoint functions inside a vector. #include <vector> #include <iostream> template <typename Func> struct endpoint_t { void* m_func; endpoint_t(Func&& func) : m_func((void*) func) {} auto execute() { return ((Func*) m_func)(); } }; int hello_world() { std::cout << "Hello World! \n"; return 0; } int hello_world2() { std::cout << "Hello World 2! \n"; return 0; } int main() { std::vector<endpoint_t<???>> array; array.push_back(hello_world); array.push_back(hello_world2); }
Assuming the prototypes of all your 'hello world' functions is the same (int return value, no parameter), you don't need templates at all. Just store a function pointer. typedef int (*Func_t)(); int hello_world() { std::cout << "Hello World! \n"; return 0; } int hello_world2() { std::cout << "Hello World 2! \n"; return 0; } int main() { std::vector<Func_t> array; array.push_back(&hello_world); array.push_back(&hello_world2); } Assuming that the prototypes do differ, it becomes a wee bit more difficult, but not very much so, thanks to std::function. int hello_world() { std::cout << "Hello World! \n"; return 0; } int hello_world2(int value) { std::cout << "Hello World 2! \n"; return 0; } int main() { std::vector<std::function<int ()>> array; array.push_back(&hello_world); array.push_back(std::bind(&hello_world2, 2)); } Please note, that std::bind and lambdas require you to pass any given parameter at the time of binding. You cannot add the parameter later.
73,917,724
73,917,894
How to let gcc optimize std::bit_cast with std::move?
Consider below code: #include <cstdint> #include <bit> #include <utility> struct A { uint32_t a[100]; }; struct B { uint16_t b[200]; }; void test(const A&); void foo() { B tmp; test(std::bit_cast<A>(std::move(tmp))); } void bar() { B tmp; test(reinterpret_cast<A&>(tmp)); } For clang 15 with -O3, foo and bar are equivalent, but for GCC 12.2 with -O3, foo needs to do data copy (rep movsq). foo(): sub rsp, 808 mov ecx, 50 lea rdi, [rsp+400] mov rsi, rsp rep movsq lea rdi, [rsp+400] call test(A const&) add rsp, 808 ret bar(): sub rsp, 408 mov rdi, rsp call test(A const&) add rsp, 408 ret Which compiler option can make GCC optimize such thing like Clang? Thanks. P.S. -Ofast is not helpful for this question. [Edit] Based on the answer provided by user17732522, I modified the code to be: #include <cstdint> #include <bit> struct A { uint32_t a[100]; }; struct B { uint16_t b[200]; }; void test(const A&); void foo(B arg) { test(std::bit_cast<A>(arg)); } void bar(B arg) { test(reinterpret_cast<A&>(arg)); } Now both GCC and Clang use data copy for foo. So, looks like std::bit_cast is not intended to cover this kind of cases.
std::move into std::bit_cast is completely pointless and doesn't have any effect at all since std::bit_cast has a lvalue reference parameter and no rvalue reference overload. In your test case tmp is never used in foo except to read (uninitialized!) data from it. It is therefore clearly a missed optimization by the compiler to not realize that this object is not needed at all and an uninitialized A could be used directly. This is not something you can solve on the language level. This is completely up to compiler optimization. In fact it seems that GCC is intentionally not eliminating the copy instruction because you are reading uninitialized data. If you zero-initialize the array in B, then GCC produces the same output for both functions without an additional copy in the std::bit_cast version. There is not really anything you can do about this, but I don't really see any value in the test case. You could just declare a A directly and have the same effect.
73,918,086
73,918,171
constexpr variable use const variable at initialization
Why the following example compile with no problems? #include <iostream> int main(){ const int var1 = 2; constexpr int var2 = var1 * 5; return 0; } According to theory: “Variables” that are not constant expressions (their value is not known at compile time) I used gcc compiler, can be the case that each compiler behave different? Then how const var1 is known at compile time in this example? I found other topics about const vs constexpr but I still don't understand it.
Why the following example compile with no problems? The full-expression of any constexpr variable has to be a constant expression, i.e evaluable at compile-time. Your initializer var*5 is a constant expression because var is const-qualifed integral type that is itself initialized by integral constant expression; also 5 is also an integral constant expression, hence, the full-expression var*5 is also a constant expression. So nothing will cause the program to be ill-formed.
73,918,093
73,918,113
prvalue vs xvalue for class types
I've got more confused when I see this question: Is a class instantiation--class_name() a xvalue or a prvalue? I'm trying to understand what does it mean by a class prvalue and a class xvalue. Someone tell me that they're called value category. But I think it would be better if I provide an example, because I'm very confused. class myclass { public: myclass() {}; }; void myfunc(myclass c1){ } int main(void) { myfunc(myclass()); } So what's myclass()? Is it a prvalue or xvalue? I need a rule from the standard so that I wouldn't ask more questions.
The expression myclass() is explicit type conversion using functional notation, per [expr.type.conv]/1: A simple-type-specifier or typename-specifier followed by a parenthesized optional expression-list or by a braced-init-list (the initializer) constructs a value of the specified type given the initializer [..] Here, the simple-type-specifier myclass is followed by parenthesized expression-list () with an empty initializer-list. This expression constructs a value of type myclass from the empty initializer-list. So you might ask, Is that constructed value is prvalue or xvalue or lvalue. So here we've to invoke the immediately next paragraph: [expr.type.conv]/2: If the initializer is a parenthesized single expression, the type conversion expression is equivalent to the corresponding cast expression. Otherwise, if the type is cv void and the initializer is () or {} (after pack expansion, if any), the expression is a prvalue of the specified type that performs no initialization. Otherwise, the expression is a prvalue of the specified type whose result object is direct-initialized with the initializer. Our initializer is empty initializer-list, and the type is not cv void, so we've ended with the sentence that says: Otherwise, the expression is a prvalue of the specified type whose result object is direct-initialized with the initializer. Hence, the expression myclass() is a prvalue, whose result object is direct-initialized, from the empty initializer-list, by calling the default constructor.
73,918,767
73,922,524
Displaying the sizes of all objects, containers, programs etc. С++
Let's imagine that we have a big project. In which there are many classes, objects of these classes, containers of objects, and so on. Can I view the dimensions of all these objects? Output, for example, a table or a list of all objects, containers, with their sizes. Of course, for a project, for example, in 20000+ lines, I will not be able to display everything by hand. It is important that this can be done not only after the completion of the program, but during execution Are there any utilities, programs, perhaps this can be done using gdb or some other means. I hope I explained the question exhaustively, ask questions, I will explain what I can.
Output, for example, a table or a list of all objects, containers, with their sizes. Of course, for a project, for example, in 20000+ lines, I will not be able to display everything by hand. Yes, you can do that. Either by writing appropriate object-tracking code and linking it into your program, or by writing a GDB script to enumerate objects "externally". However, usually this request means that you want to understand your program via debugger instead of understanding it by reading the code. And the former task is usually about 10 times harder than the latter. In addition, 20,000 line program is relatively small. A big project is something with a few million lines of code. Update: Imagine that you have a multi-threaded program with various modules and "legacy code" that leaks a container or something else, such a leak cannot be determined from the dump from the sanitizer, because when the program ends, RAII cleans everything. Ah, so this is a good example of an XY problem. As you can imagine, this problem isn't unique to your project, and there are existing tools to solve it. For example, TCMalloc includes heap profiler, which allows you to snapshot current heap state and answer questions such as "for all currently allocated objects, where did they get allocated from?". One advantage of TCMalloc sampling approach (compared to what you proposed) is that its overhead is quite small, and so it can be live in production -- you don't need a special heap-debug build and can analyze any process at will.
73,918,842
73,918,903
Why not have all variables be a constexpr?
sorry if this sounds like a dumb question but I dont have much experience with C++ programming and im trying to learn as much as a I can about its syntax. I came across the specifier constexpr and was wondering that if it allows you to save time at runtime, why not declare all your variables with it?
First of all not all variables can be made constexpr. For example int x; std::cin >> x; Obviously x cannot be constexpr. The value it will have after it has been read from input is not a compile-time constant. Second, constexpr is part of the contract of a variable or function. By marking it constexpr, you allow other code to use it in a context that requires a constant expression. That means even if it might be possible to declare it constexpr now, you should not do so if you are planning on potentially changing the code so that it will not be constexpr later. If you were to mark it constexpr now, other code might come to rely on this property, and that code will stop compiling when constexpr is removed in a future version of the program.
73,919,215
73,989,643
Can not link yaml-cpp with my cmake project
My CMakeLists.txt cmake_minimum_required(VERSION 3.0 FATAL_ERROR) project(test_includes) #find_package(Boost COMPONENTS system filesystem REQUIRED) #include_directories( ${Boost_INCLUDE_DIRS} ) set(Torch_DIR "${CMAKE_CURRENT_SOURCE_DIR}/libtorch/share/cmake/Torch") find_package(Boost COMPONENTS system filesystem REQUIRED) find_package(Threads REQUIRED) find_package(Torch REQUIRED) find_package(yaml-cpp REQUIRED) include_directories( ${Boost_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIR} ${yaml-cpp_INCLUDE_DIR} ${Torch_INCLUDE_DIRS} include) set(CMAKE_CXX_FLAGS_DEBUG "-g3") set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O3 -g3 -gdwarf -fno-omit-frame-pointer -DNDEBUG") set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra") add_subdirectory(include) #link_directories(libraries) set( LIBS_TO_LINK Domains Agents Planning yaml-cpp ${TORCH_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT})# -llapack) add_executable(testWarehouse testWarehouse.cpp) target_link_libraries(testWarehouse ${LIBS_TO_LINK}) The error message i am getting: ... [100%] Linking CXX executable testWarehouse /usr/bin/ld: CMakeFiles/testWarehouse.dir/testWarehouse.cpp.o: in function `WarehouseSimulation(std::string const&, unsigned long)': testWarehouse.cpp:(.text+0x13af): undefined reference to `YAML::LoadFile(std::string const&)' /usr/bin/ld: CMakeFiles/testWarehouse.dir/testWarehouse.cpp.o: in function `YAML::detail::node_ref::set_scalar(std::string const&)': testWarehouse.cpp:(.text._ZN4YAML6detail8node_ref10set_scalarERKSs[_ZN4YAML6detail8node_ref10set_scalarERKSs]+0x2a): undefined reference to `YAML::detail::node_data::set_scalar(std::string const&)' /usr/bin/ld: CMakeFiles/testWarehouse.dir/testWarehouse.cpp.o: in function `YAML::Node::Scalar() const': testWarehouse.cpp:(.text._ZNK4YAML4Node6ScalarEv[_ZNK4YAML4Node6ScalarEv]+0x79): undefined reference to `YAML::detail::node_data::empty_scalar()' collect2: error: ld returned 1 exit status make[2]: *** [CMakeFiles/testWarehouse.dir/build.make:109: testWarehouse] Error 1 make[1]: *** [CMakeFiles/Makefile2:152: CMakeFiles/testWarehouse.dir/all] Error 2 make: *** [Makefile:91: all] Error 2 note: i do have yamp-cpp installed my full project: i have tried manually adding -lyaml-cpp to the compile commands, with no effect. can someone please check my CMakeLists.txt and tell my if am linking yaml-cpp properly, Thanks. (i am 99% sure that it is correct) i have tried yaml-cpp versions 7.0, 6.3, 5.3 all with the same result looking at .../build/CMakeCache.txt it includes: //The directory containing a CMake configuration file for yaml-cpp. yaml-cpp_DIR:PATH=/usr/share/cmake/yaml-cpp which looks correct to me if you need any more info please ask Thank you
it was pre C++11 ABI issue the solution can be found at: https://github.com/pytorch/pytorch/issues/19353#issuecomment-652314883
73,919,258
73,919,319
reinterpret_cast<const> casts away const qualifier?
In the following case I try to cast a pointer to a struct into a pointer to another struct (which has the same memory layout behind the scenes). I try to do this in a const correct way, however the compiler is complaining. I looked at a similar issue but I need the constness to propagate and it doesn't work like described for me. Demo struct queue { // ... }; typedef struct queue* queue_handle; struct dummy_queue { // ... }; struct queue_wrapper { auto get_queue() const -> queue_handle { return reinterpret_cast<const queue_handle>(&d); } dummy_queue d; }; int main() { queue_wrapper w; w.get_queue(); } Error: <source>: In member function 'queue* queue_wrapper::get_queue() const': <source>:17:16: error: 'reinterpret_cast' from type 'const dummy_queue*' to type 'queue_handle' {aka 'queue*'} casts away qualifiers 17 | return reinterpret_cast<const queue_handle>(&d); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ I'm converting to a const pointer though (which gcc seems to misunderstand somehow). I do not need to change the pointer after returning it. How do I accomplish this conversion without errors?
const queue_handle applies the const to the pointer type itself, not the pointed to type as you intent to. I would suggest adding a const_queue_handle alias to const queue* if you are already using aliases for the pointers (whether or not that is a good idea is a matter of opinion) and then you can use that as template argument to reinterpret_cast. Also beware that even if the struct layout is identical, this is still undefined behavior territory. A compiler may assume that a pointer to one of the struct types won't alias one to the other and use that for optimization. You should probably at least compile everything with -fno-strict-aliasing when doing this.
73,919,400
73,923,976
Unable to transfer complete data stream from Arduino Uno at high baudrate
I am trying to transfer some data at 115200 Bd to a C# form RichTextBox. Below is my Arduino code: void serialEvent() { if (Serial.available()) { int command = Serial.parseInt(); Serial.println(command); switch(command) { case 1: /*executes its job and writes data in the following format in each line - xxxxxx xxx xxx*/ break; case 0: /*executes another unrelated job*/ break; } } } Now the total written lines stop printing to my C# form around the 6000/7000 line. Why is that, and how to rectify it? I can't reduce my baudrate; in fact, I would like to increase it. I would like to have the data accessible in a way that I can perform mathematical functions on it through the C# form and also copy it if I need to. Below is my C# form application code part: private void settext(string val) { richTextBox1.AppendText(val); } private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { string incomstring = serialPort1.ReadLine(); settext(incomstring); } private void button5_Click_1(object sender, EventArgs e) { try { Cursor.Current = Cursors.WaitCursor; if (serialPort1.IsOpen) { serialPort1.WriteLine("1"); } else { MessageBox.Show("Open Port FIrst.", "Port not open.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { Cursor.Current = Cursors.Default; } }
You mentioned 'Arduino', then your 'serial line' is likely a virtual USB-serial port. I had similar problems about a month ago. But I had only control over the code at the receiving end and at a late point in time (for the project) some insight in the code at the sending end. Virtual USB-serial connections are a known source of problems. I did some comparison testing with a physical serial line and did not see the kind of problems I had (and still have) on the virtual USB-serial line. Giving it some tought then, I see two approaches. The first one is adding buffering and flow control. This is a general technique and you should be able to google up some examples of it. The second one is to use a dedicated serial line. Using an Ardino maybe you have some unused I/O spare that you can use for this. An extra requirement is that at your receiving end you need a real serial port. Using an RS232-to-USB converter is not an option for this approach. Then it is much easier to implement flow control by using hardware lines like DTR and RTS or software solutions with Xon/Xoff. You can look up some details at wikipedia edit 2022-oct-7 My original problem is still nagging me, got it working. Played with the C++ version to add priotiry and found this Added a line SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS) at the very start. Got stable communication, tested for three hours transferring about 250 MB every 10 minutes continuously. Process priority makes a big difference.
73,919,449
73,919,585
How to use a vector in a vector
I am trying to use a for statement with a vector in a vector. std::vector<std::string> array = { {"A", "a"}, {"B", "b"}, {"C", "c"} }; for (std::string& a : array) { if (letter == a[1] || letter == a[0]) { std::cout << a[0] << ": " << a[1] << std::endl; break; } } I am new to C++ and cannot figure out why it gives me errors about this. Edit: Error: error: invalid operands to binary expression ('std::string' (aka 'basic_string<char>') and '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' (aka 'char'))
I think {"A", "a"} is already a verctor, and this array varable type should be vector<vector<string>>.
73,920,004
73,921,029
How to delete "end" node from a circular linked list using only tail in c++?
I need to write three separate functions for node deletion in a circular singly linked list (deleteFront(), deleteMiddle() and deleteEnd()). I have to use only tail (last). For some reason, my deleteEnd() function deletes second to the last node. Can anyone please help? struct node { int data; struct node* next; }; // some other functions // 6 -> 5 -> 4 -> 3 -> deleteEnd() does 6 -> 5 -> 3 -> void deleteEnd(struct node* last) { if (last != NULL) { if (last->next == last) last = NULL; else { node* temp = NULL; node* temp1 = last; while (temp1->next != last) { temp = temp1; temp1 = temp1->next; } temp->next = temp1->next; delete temp1; } } }
There are several issues with your deleteEnd function: There is no way that the caller can get the new tail reference, because the tail argument is passed by value. The tail parameter should be a pass-by-reference parameter. The statement after the loop (in the else block) does not remove the correct node. After the loop, temp1->next will be equal to last, and it should be that node that is removed, yet your code removes temp1. You can fix this by changing the loop condition and initialise the temp and temp1 variables to point to one node further in the list. The else block does not update tail, yet it is clear that it should, since the original tail node is deleted. Less of an issue, but in C++ you should not use NULL, but nullptr. Here is a correction: void deleteEnd(struct node* &last) // corrected { if (last != nullptr) { if (last->next == last) last = nullptr; else { node* temp = last; // corrected node* temp1 = last->next; // corrected while (temp1 != last) // corrected { temp = temp1; temp1 = temp1->next; } last = temp; // added temp->next = temp1->next; delete temp1; } } }
73,920,103
73,926,710
Sending numpy array (image) to c++ library with ctypes
I'm trying to make a python program that can run Photoshop Plugins by using this DLL library from Spetric - https://github.com/spetric/Photoshop-Plugin-Host I need to send an image loaded by opencv to the dll (while I can read c++ I cannot program in it and have never been able to get the dll to compile for edits such as loading the image directly from a filename) The description of the function is pspiSetImage(TImgType type, int width, int height, void *imageBuff, int imageStride, void *alphaBuff = 0, int alphaStride = 0); I have tried several suggestions and solutions found here on stackoverflow but they all result in the same thing "OSError: exception: access violation writing 0x00000000" Which is weird because I thought the idea was to pass in a pointer to a long buffer of data and that number wouldn't be 0. I've checked the value/output and it never is zero that I pass in. I have tried accessing the __array_interface++['data'][0], using ctypes.data_as built into the numpy object, various versions of POINTER and c_void_p. My fundamental misunderstanding of what's needed and how to get it and pass it is my problem. Are there any suggestions or helpful hints to point me in the right direction? EDIT: Here is the code I'm currently working with import ctypes import cv2 plugins = {} def main(args=None): plugin_host = ctypes.CDLL('.\\pspiHost.dll') plugin_host.pspiSetPath(".\\8bf filters\\") # Any image will do, I used a PNG to test alpha transparency im = cv2.imread('.\\fish.png', cv2.IMREAD_UNCHANGED) array = im.ctypes.data_as(ctypes.POINTER(ctypes.c_void_p)) width = im.shape[0] height = im.shape[1] # 1 in first parameter is for RGBA format, I'm using a png with transparency plugin_host.pspiSetImage(ctypes.c_int(1), ctypes.c_int(width), ctypes.c_int(height), array, ctypes.c_int(0)) if __name__=='__main__': main()
This is a duplicate of [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer), but I'm going to detail. When working with CTypes, the .dll must export functions using C compatible interface (extern "C"), while pspiSetImage seems to be C++ (default arguments). Also check [SO]: How to write a function in C which takes as input two matrices as numpy array (@CristiFati's answer) for details converting NumPy arrays. Here's a snippet that should fix things. import ctypes as cts import cv2 import numpy as np plugin_host = ctypes.CDLL(r".\pspiHost.dll") pspiSetPath = plugin_host.pspiSetPath pspiSetPath.argtypes = (cts.c_wchar_p,) # Got this from the passed argument pspiSetPath.restype = None # void return? # ... img = cv2.imread(r".\fish.png", cv2.IMREAD_UNCHANGED) # ... pspiSetImage = plugin_host.pspiSetImage pspiSetImage.argtypes = ( cts.c_int, cts.c_int, cts.c_int, np.ctypeslib.ndpointer(dtype=img.dtype, shape=img.shape, flags="C"), #cts.c_void_p, # Extra checks for NumPy array cts.c_int, cts.c_void_p, # Not sure what the array properties are cts.c_int, ) pspiSetImage.restype = None # void return? # ... pspiSetPath(".\\8bf filters\\") img_stride = img.strides[0] pspiSetImage( 1, *img.shape[:2], img, #np.ctypeslib.as_ctypes(img), img_stride, None, 0 ) Notes: Not sure what the function does internally, but bear in mind that the array has 3 dimensions (and you're only passing 2), also its dtype Also, after taking a (shallow) look at Photoshop-Plugin-Host sources, imageStride argument should (most likely) be img.strides[0] Function argument imageBuff is tailored on this specific array. If you need to call it multiple times, with different arrays (shapes and dtypes), you should take the generic approach (have a cts.c_void_p argument and convert it via np.ctypeslib.as_ctypes (or img.ctypes.data_as))
73,920,562
73,920,662
How can I set User Input from Code in C++?
I am creating a test for a function which gets the user input with std::cin, and then returns it. The test just needs to check if the input from the user, is the one actually returned. Problem is, the test should be automated so I can't manually react to the std::cin prompt. What can I do to set the input with code?
I wouldn't bother with automation or redirection of the std::cin functionality. From personal experience it always get much more complicated than it has to be. A good approach would be to separate your behavior. Bad: void MyFunction() { std::string a; std::cin >> a; auto isValid = a.size() > 1; } Better: bool ValidateInput(const std::string& myString) { return myString.size() > 1; } void MyFunction() { std::string a; std::cin >> a; auto isValid = ValidateInput(a); } There are more complex solutions to this with std::cin.rdbuf. You could adjust rdbuf - use this only if you don't have control on the function. For example: #include <sstream> #include <iostream> void MyFunc() { std::string a; std::cin >> a; auto isValid = a.size() > 1; if (isValid) { std::cout << a; } } int main() { std::stringstream s; s << "Hello_World"; std::cin.rdbuf(s.rdbuf()); MyFunc(); } Always separate the input functions from the validation functions and the processing functions. Best of luck!
73,920,645
73,920,682
Function Pointer Initialization in C/C++
As I was going through a ESP IDF's documentation; I saw that a function pointer was initialized in a certain way that does not make sense to me. typedef void *app_driver_handle_t; app_driver_handle_t app_driver_light_init(); app_driver_handle_t app_driver_button_init(); Etc. I thought that in order to initialize a function pointer, you must do it the following way: app_driver_handle_t = app_driver_button_init(); Sorry for my beginner level questions. It would do wonders if someone could explain this. Thanks
Let's break down the code you're looking at. typedef void *app_driver_handle_t; This is not a function pointer. This is a void pointer, which means it can point to basically any values. And this is a type, not a value, so app_driver_handle_t does not actually contain any pointers at all; it's merely a name that's synonymous with void*. app_driver_handle_t = app_driver_button_init(); Given the typedef above, this syntax is never valid. You're setting a type equal to what is presumably a function call. You can't assign to types. Full stop. What you can do is declare variables and assign them the result of function calls. app_driver_handle_t my_variable; my_variable = app_driver_button_init(); or you can do it in one line. app_driver_handle_t my_variable = app_driver_button_init(); Finally, these last two lines. app_driver_handle_t app_driver_light_init(); app_driver_handle_t app_driver_button_init(); These are also not function pointers. These are function prototypes. They're a promise to the compiler, saying, "I will eventually define two functions called app_driver_light_init and app_driver_button_init. These two functions will take no arguments and will return a void*". There's still no function pointer happening here. The functions, when they're eventually defined, will return a void*, which, again, is not a function pointer but a pointer to void.
73,921,009
73,922,711
Kaprekar Number between given range
I'm trying to print all Kaprekar Numbers between Given Range As input the range is between --> 1 to 99999 <-- The Expected Output : 1 9 45 55 99 297 703 999 2223 2728 4950 5050 7272 7777 9999 17344 22222 77778 82656 95121 99999 but I got this output : 1 9 45 55 99 297 703 999 2223 2728 4950 5050 7272 7777 9999 17344 22222 I stay miss 3 output any idea I'm using C++. My code : #include <bits/stdc++.h> #include <cmath> using std::cout; using std::cin; using std::endl; using std::pow; int b = 0, a = 0; int main(int argc, char** argv) { int lower, upper, count = 0; cin >> lower >> upper; for (int i = lower; i <= upper; i++) { int n = i, digits = 0; while (n != 0) { digits++; n /= 10; } n = pow(i, 2); digits = pow(10, digits); b = n % digits; a = (n - b) / digits; if (a + b == i) { cout << i << " "; count++; } digits = 0; a = 0; b = 0; } if (count == 0) cout << "INVALID RANGE"; return 0; }
All the variables used in the posted snippet are of type int, which is probably1 not enough big to store the squares of all the possible input values, so that, as note by Igor Tandetnik in their comment Your program exhibits undefined behavior by way of integer overflow. Using a wider type, like long long2 or int64_t should fix the program. I'd also avoid the use of std::pow, which returns a double, when exact integer arithmetic is needed3. The followig snippet implements a slightly different algorithm4. #include <iostream> int main() { long long int lower{ 1 }; long long int upper{ 99'999 }; int base{ 10 }; for (auto i = lower; i <= upper; ++i) { auto n{ i * i }; // https://en.wikipedia.org/wiki/Kaprekar_number /* "a natural number in a given number base is a p-Kaprekar number if the representation of its square in that base can be split into two parts, where the second part has p digits, that add up to the original number." */ auto b{ n % base }; // So, let's calculate those two parts directly. auto a{ n / base }; auto power{ 1ll }; while ( a >= i ) { power *= base; b += (a % base) * power; // Add one digit to b. a /= base; // Remove one digit from a. } if (a + b == i) { std::cout << i << ' '; } } std::cout << '\n'; } 1) See e.g. What does the C++ standard state the size of int, long type to be? 2) note that a long may be as wide as an int in certain environments. 3) See e.g. Why pow(10,5) = 9,999 in C++ and Is there any advantage to using pow(x,2) instead of x*x, with x double? 4) https://godbolt.org/z/1G9of49xb
73,922,014
73,930,998
AutoCAD ObjectARX c++ What is the syntax to convert a AcString to a std::string value?
I am very new to ObjectARX and c++ and I hope you can help. I am using AutoCAD 2023 and Visual Studio 2019. I have successfully compiled and loaded my c++ function as ARX and called from within AutoLISP. (myfunc "Hello World") I have managed to get the value of Lacstring_parameter_passed_to_myfunc "Hello World" What syntax do I use to get the value of Lacstring_parameter_passed_to_myfunc as a std::string ??? static int myfunc(struct resbuf* rb) { AcString Lacstring_parameter_passed_to_myfunc; if (rb->restype == RTSTR) { Lacstring_parameter_passed_to_myfunc = rb->resval.rstring; } std::string my_string_parameter_passed_to_myfunc = "????????" // What is the syntax to convert a AcString to a std::string value?? }
Try this: AcString base = _T("testżźę"); CT2CA pszConvertedAnsiString(base); std::string strStd(pszConvertedAnsiString);
73,922,406
73,922,447
How to pass tuple elements to callable in C++
How do I pass the elements of a tuple as arguments to any callable in C++? std::apply works only when the callable's arguments exactly match those of the tuple's. For instance: struct Foo { template<typename... Ts> Foo(std::string s, Ts&&... ts) {} } int main() { auto tup = std::make_tuple(5, 5.5f, 100000l); } In the code above, how would I make a Foo object by passing into its constructor some string value followed by the values stored in tup?
Either you can specify template arguments, thereby choosing the overload; or, you might do a simple forwarding lambda: Foo f = std::apply([&](auto&&... args){ return Foo("", std::forward<decltype(args)>(args)...);}, tup); Note that here I have added the first parameter as a string; an int is not accepted by Foo there.
73,922,440
73,922,778
return the output value of a function that asks for an output variable
Title is a bit messy, but i dont know how to simplify it. This is what i want to do: nodeReceivedData[packetSize+1] = itoa(LoRa.packetRssi(), [output], 10); itoa() always asks for a input variable, output variable and a size modifier. What I want to do, is to avoid having to make a temporary variable to then assign it's value to the actual variable I want that data to be. Is there something that can do this? I also tried: itoa(LoRa.packetRssi(), &nodeReceivedData[packetSize+1], 10); but since nodeReceivedData is a byte type variable, itoa() won't accept it. Extra info: int LoRaClass::packetRssi() byte nodeReceivedData[50]
Since "itoa" expects the 2nd argument to be "char*" and 'nodeReceivedData' is byte (assuming it is just an "unsigned char"), you can just cast it to a char* and should work as expected: itoa(LoRa.packetRssi(), (char*)&nodeReceivedData[packetSize+1], 10);
73,922,651
73,922,675
Is it possible to know in a destructor that an r-value referrence is being deleted?
I was testing my own RAII pointer implementation that does some weird stuff (by design). To test it, I made a class that tracks constructors and destructors and makes sure everything is deleted and created exactly once. But I was constantly getting an error that I'm deleting something twice. Weird, right. I found out why and you can see it by running the sample below. This is not the code that originally produced it, but it demonstrates the issue. struct ReportDelete { ReportDelete() = delete; ReportDelete(const std::string& name) : name(name) { std::cout << "create " << name << "\n"; } ReportDelete(ReportDelete&& moveHere) : name(std::move(moveHere.name)) {} ReportDelete& operator=(ReportDelete&& moveHere) { name = std::move(moveHere.name); return *this; } ReportDelete(const ReportDelete&) = delete; void operator=(const ReportDelete&) = delete; std::string name; ~ReportDelete() { std::cout << "delete " << name << "\n"; name = name + "-deleted"; } }; int main(int argc, const char** argv) { std::vector<ReportDelete> moveTest; moveTest.push_back(ReportDelete("test")); } This prints: create test delete delete test So the destructor is still called on the moved value. That does not do anything bad in particular, but it makes it impossible for me to test the create/delete ratio correctly. My actual test class does this in the destructor: virtual ~Value() { std::string error = name + " deleted twice!"; assertm(parent.values[fullname()] == false, error.c_str()); parent.values[fullname()] = true; } Where parent is the class that tracks whether the values are deleted at the end. But how can I know here that this is only being run for Value&& and should be disregarded? I tried this: Value~() && { std::cout << "rvalue destructor ignored...\n"; } But it seems you cannot have a special destructor like that. How can I know that a destructor is being only called on an rvalue refference and that I can therefore ignore it and not track it as a real delete?
This has nothing to do with a destructor getting called for an r-value reference, or not. A destructor is a destructor. An object is getting destroyed. The End. The particular details of the object are immaterial. ReportDelete& operator=(ReportDelete&& moveHere) { name = std::move(moveHere.name); return *this; } This will move name from the moved-from instance of this object. However, the moved-from instance of the object is still a valid, existing object, and at some point it will be destroyed. However you moved-from its name member. Your C++ implementation's result of that is that the moved-from std::string name is left to be an empty string. And when that moved-from object gets destroyed its destructor prints an empty name. This is the output that you're seeing. TLDR: you were not getting an error. What you overlooked is that a moved-from object is still a valid, existing object, and it is still subject to being destroyed. Which it will be, in a well-formed C++ program. In fact, because, in this case, the moved-from object is an rvalue reference that increases, quite significantly, the likelyhood that the moved-from object is about to get nuked from high orbit.
73,922,781
73,922,833
How to import a C++ class head and cpp file in a new cpp file
Here is an example C++ code. header.h class example { int a; int b; public: int sum(int i,int j); }; cpp.cpp #include<iostream> #include"header.h" int example::sum(int i,int j){ a=i; b=j; return a+b; } int main(){ example e1; int b=e1.sum(32,34); std::cout<<b<<std::endl; return 0; } main.cpp #include<iostream> #include"header.h" int main(){ example e1; int b=e1.sum(32,34); std::cout<<b<<std::endl; return 0; } When I use the code in powershell g++ cpp.cpp I get a file a.exe without any problem. When I run the main.cpp it shows the error d:/program files/mingw/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\KISHOR~1\AppData\Local\Temp\ccIMGM4v.o:main.cpp:(.text+0x20): undefined reference to `example::sum(int, int)' collect2.exe: error: ld returned 1 exit status If I have to use the class in a file called main.cpp how do I it? I am working on a bunch of files which has similar usb.cpp and usb.h file. But the cpp fle containing the main program imports only header file. How to tell g++ that definition of the header file is given in cpp.cpp?
You should compile with the command g++ cpp.cpp main.cpp, and comment out the main function in cpp.cpp.
73,922,876
73,923,134
Drawing a simple rectangle in OpenGL 4
According to this wikibook it used to be possible to draw a simple rectangle as easily as this (after creating and initializing the window): glColor3f(0.0f, 0.0f, 0.0f); glRectf(-0.75f,0.75f, 0.75f, -0.75f); This is has been removed however in OpenGL 3.2 and later versions. Is there some other simple, quick and dirty, way in OpenGL 4 to draw a rectangle with a fixed color (without using shaders or anything fancy)?
Is there some ... way ... to draw a rectangle ... without using shaders ...? Yes. In fact, AFAIK, it is supported on all OpenGL versions in existence: you can draw a solid rectangle by enabling scissor test and clearing the framebuffer: glEnable(GL_SCISSOR_TEST); glScissor(x, y, width, height); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); This is different from glRect in multiple ways: The coordinates are specified in pixels relative to the window origin. The rectangle must be axis aligned and cannot be transformed in any way. Most of the per-sample processing is skipped. This includes blending, depth and stencil testing. However, I'd rather discourage you from doing this. You're likely to be better off by building a VAO with all the rectangles you want to draw on the screen, then draw them all with a very simple shader.
73,922,896
73,923,000
Why does == work and = does not in an if statement?
for (unsigned int i = 0; i < list.size(); i++) { if (list.at(i) = n) { cout << "True"; return 0; }} I was wondering why this would not work I understand that tou should use list.at(i) == n. However i thought that a single = means assigning, and a double == means equal to. I understand it is different but wouldn't using only one = still be correct when using it in an if statement?
It would not necessarily be correct. When you use an assignment expression as a boolean for integers, it will return true if the integer is not zero, and it will return false if the integer is zero. Suppose our list looks like this: 1, 2, 0, 5. Now, suppose we have this if-statement: if (list.at(0) = 1) { cout << "True"; } Since the 1 in list.at(0) = 1 is not 0, the if-condition will be satisfied. If we used ==, it would be satisfied since the first value is indeed 1. Now let's suppose we have this if-statement: if (list.at(1) = 3) { cout << "True"; } The "True" would be printed because 3 is not equal to 0. However, if we replaced = with ==, the "True" would not be printed since the second value is not 3. Let's look at one last example. if (list.at(2) = 0) { cout << "True"; } This would not print out "True" since we are assigning list.at(2) to 0. However, if we replaced the = with ==, the "True" would be printed since the third value in the list is actually 0. This shows that = cannot be used as ==. P.S. And, if you wanted to use the list later, your list would be modified into a different list.
73,922,977
73,923,155
Embedding an SVG as std::string in C++ source code
ALL, I finally moved away from the bitmaps and trying to use SVG in my C++ code. I made an SVG using an InkScape and saved it as Compressed. Then I edited the resulting file by adding the static const char data[] = in front of the XML and place every single line of XML inside double quotes. The resulting file then is saved as .h file and included in the C++ source code. However when compiling I am getting following: error: stray ‘#’ in program 13 | " <g stroke="#000">" | ^ What can I do? Linux does not have a notion of resources and I'd rather embed the graphics, than allow external file. TIA!! Below is the beginning of the header file in question: ` static const char query[] = "" "" " " " rdf:RDF" " <cc:Work rdf:about="">" " <dc:format>image/svg+xml</dc:format>" " <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>" " <dc:title/>" " </cc:Work>" " </rdf:RDF>" " " " " " " " " `
You may want raw string literal introduced in C++ 11. static const char data[] = R"xxx(<?xml version="1.0"...)xxx"; This is equivalent to static const char data[] = "<?xml version=\"1.0\"...";
73,922,989
73,923,025
How to write string to .txt file in C++ using FILE
I have string str = "6.5.1" I want to write str to file .txt, but the result is ��j Here my code FILE *outfile = fopen("solution.txt", "w"); string test = "6.5.1"; fprintf(outfile, "%s\n", test); I use string, FILE because I want to pass FILE as an argument, and convert string from another file to method. How can I fix this problem? Thanks. p\s: sorry, tag is c++ not c
You clarified that you needed a c++ solution and required to use FILE *: #include <cstdio> #include <string> int main(void) { FILE *outfile = std::fopen("solution.txt", "w"); std::string test = "6.5.1"; std::fprintf(outfile, "%s\n", test.c_str()); std::fclose(outfile); }
73,923,076
73,923,580
Flash "CurveTo" and "LineTo" in Shapes
I'm working in trying to display some old SWF files with Direct2D. I found swfmill which, for a simple SWF (found here) that displays a "W" produces XML code, part of which is this one: <ShapeSetup x="-214" y="470" fillStyle1="1"/> <LineTo x="-20" y="0"/> <CurveTo x1="-35" y1="-74" x2="-45" y2="-109"/> <CurveTo x1="-46" y1="-109" x2="-109" y2="-244"/> <CurveTo x1="-110" y1="-244" x2="-32" y2="-50"/> <CurveTo x1="-33" y1="-50" x2="-27" y2="-18"/> <CurveTo x1="-27" y1="-19" x2="-21" y2="-3"/> <CurveTo x1="-21" y1="-1" x2="0" y2="-9"/> <CurveTo x1="0" y1="-10" x2="53" y2="0"/> <LineTo x="304" y="0"/> <CurveTo x1="43" y1="0" x2="0" y2="10"/> <CurveTo x1="0" y1="10" x2="-24" y2="0"/> <CurveTo x1="-100" y1="6" x2="0" y2="70"/> <CurveTo x1="0" y1="16" x2="8" y2="27"/> <CurveTo x1="8" y1="27" x2="100" y2="229"/> <CurveTo x1="99" y1="229" x2="59" y2="120"/> <CurveTo x1="22" y1="-56" x2="73" y2="-216"/> <CurveTo x1="72" y1="-215" x2="14" y2="-56"/> <CurveTo x1="-53" y1="-131" x2="-24" y2="-21"/> <CurveTo x1="-24" y1="-22" x2="-41" y2="-7"/> <CurveTo x1="-29" y1="-1" x2="0" y2="-9"/> <CurveTo x1="0" y1="-10" x2="52" y2="0"/> <LineTo x="305" y="0"/> <CurveTo x1="28" y1="0" x2="7" y2="2"/> <CurveTo x1="8" y1="2" x2="0" y2="6"/> <CurveTo x1="0" y1="6" x2="-40" y2="4"/> <CurveTo x1="-84" y1="13" x2="0" y2="68"/> <CurveTo x1="0" y1="106" x2="234" y2="531"/> <CurveTo x1="46" y1="-116" x2="44" y2="-123"/> <LineTo x="80" y="-220"/> <CurveTo x1="35" y1="-97" x2="4" y2="-25"/> <CurveTo x1="5" y1="-25" x2="0" y2="-21"/> <CurveTo x1="0" y1="-89" x2="-85" y2="-2"/> <CurveTo x1="-19" y1="0" x2="0" y2="-10"/> <CurveTo x1="0" y1="-6" x2="6" y2="-2"/> <CurveTo x1="6" y1="-2" x2="28" y2="0"/> <LineTo x="165" y="0"/> <CurveTo x1="74" y1="0" x2="10" y2="2"/> <CurveTo x1="11" y1="1" x2="0" y2="9"/> <CurveTo x1="0" y1="8" x2="-16" y2="0"/> <CurveTo x1="-74" y1="6" x2="-43" y2="83"/> <CurveTo x1="-42" y1="83" x2="-154" y2="449"/> <CurveTo x1="-81" y1="235" x2="-27" y2="64"/> <LineTo x="-21" y="0"/> <CurveTo x1="-58" y1="-160" x2="-55" y2="-132"/> <CurveTo x1="-54" y1="-132" x2="-100" y2="-257"/> <LineTo x="-229" y="681"/> <ShapeSetup/> I'm not sure how to interpret this shape. What I've tried: I tried with a ID2D1PathGeometry and BeginFigure (for the ShapeSetup), AddLine (for each LineTo), AddQuadraticBezier (for each CurveTo) but the result is this: I realized that I must combine some geometries but I'm not sure how. A spec I found here says: FillStyle0 and FillStyle1 The Adobe Flash authoring tool supports two fill styles per edge, one for each side of the edge: FillStyle0 and FillStyle1. For shapes that don’t self-intersect or overlap, FillStyle0 should be used. For overlapping shapes the situation is more complex. For example, if a shape consists of two overlapping squares, and only FillStyle0 is defined, Flash Player renders a ‘hole’ where the paths overlap. This area can be filled using FillStyle1. In this situation, the rule is that for any directed vector, FillStyle0 is the color to the left of the vector, and FillStyle1 is the color to the right of the vector Is there anyone that understands how that shape should be drawn?
Probably, coordinates are all relative. So you need to calculate positions incrementally. For example, <ShapeSetup x="-214" y="470" fillStyle1="1"/> <LineTo x="-20" y="0"/> <CurveTo x1="-35" y1="-74" x2="-45" y2="-109"/> : are to be translated to pSink->BeginFigure(D2D1::Point2F(-214, 470), D2D1_FIGURE_BEGIN_FILLED); pSink->AddLine(D2D1::Point2F(-234, 470)); // -214, 470 + (-20, 0) D2D1_QUADRATIC_BEZIER_SEGMENT seg = { D2D1::Point2F(-269, 396), // -234, 470 + (-35,-74) D2D1::Point2F(-314, 287) // -269, 396 + (-45,-109) }; pSink->AddQuadraticBezier(&seg); : Appendix Testing it in XAML or SVG path-data form, M -214,470 l -20, 0 q -35,-74 -80,-183 q -46,-109 -155,-353 q -110,-244 -142,-294 q -33,-50 -60,-68 q -27,-19 -48,-22 q -21,-1 -21,-10 q 0,-10 53,-10 l 304, 0 q 43,0 43,10 q 0,10 -24,10 q -100,6 -100,76 q 0,16 8,43 q 8,27 108,256 q 99,229 158,349 q 22,-56 95,-272 q 72,-215 86,-271 q -53,-131 -77,-152 q -24,-22 -65,-29 q -29,-1 -29,-10 q 0,-10 52,-10 l 305, 0 q 28,0 35,2 q 8,2 8,8 q 0,6 -40,10 q -84,13 -84,81 q 0,106 234,637 q 46,-116 90,-239 l 80, -220 q 35,-97 39,-122 q 5,-25 5,-46 q 0,-89 -85,-91 q -19,0 -19,-10 q 0,-6 6,-8 q 6,-2 34,-2 l 165, 0 q 74,0 84,2 q 11,1 11,10 q 0,8 -16,8 q -74,6 -117,89 q -42,83 -196,532 q -81,235 -108,299 l -21, 0 q -58,-160 -113,-292 q -54,-132 -154,-389 l -229, 681 Z surely got W.
73,923,145
73,923,278
How do you include your own custom class in C++
I'm trying to learn how to properly create separate classes in my c++. Every tutorial on classes have the custom class in the same file like this. I found this question on combining different files but it doesn't deal with classes. I've created 3 simple files to learn creating classes in different files. car.h #ifndef CAR_H #define CAR_H class Car { public: Car(); Car(double wieght); double get_wieght(); void set_wieght(double wieght); ~Car(); private: double wieght; }; #ENDIF //CAR_H car.cpp #include "car.h" class Car { public: Car(){ wieght = 10.0; } Car(double wieght){ this->wieght = wieght; } double get_wieght(){ return wieght; } void set_wieght(double wieght){ this->wieght = wieght; } ~Car(){ } private: double wieght; }; main.cpp //Program to learn how to use multiple files #include <iostream> #include "car.h" using namespace std; int main(){ Car c; c.set_wieght(100.0); cout << "Car wiegth: " << c.get_wieght() << endl; } My output error when I try to compile it with g++ Main_Multiple_Files.cpp -o main.exe: Undefined symbols for architecture x86_64: "Car::get_wieght()", referenced from: _main in Main_Multiple_Files-fbf3f8.o "Car::set_wieght(double)", referenced from: _main in Main_Multiple_Files-fbf3f8.o "Car::Car()", referenced from: _main in Main_Multiple_Files-fbf3f8.o "Car::~Car()", referenced from: _main in Main_Multiple_Files-fbf3f8.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) Trying to link the files with g++ Main_Multiple_Files.cpp car.cpp -o main.exe: In file included from Main_Multiple_Files.cpp:4: ./car.h:41:2: error: invalid preprocessing directive #ENDIF //CAR_H ^ ./car.h:1:2: error: unterminated conditional directive #ifndef CAR_H ^ 2 errors generated. In file included from car.cpp:1: ./car.h:41:2: error: invalid preprocessing directive #ENDIF //CAR_H ^ ./car.h:1:2: error: unterminated conditional directive #ifndef CAR_H ^ car.cpp:3:7: error: redefinition of 'Car' class Car ^ ./car.h:4:7: note: previous definition is here class Car ^ 3 errors generated. What do I need to do to get this class working? Feel free to obliterate my code I've been trying to do this for a while now.
If you really want the bodies separate, your Car.cpp should look like this: #include "car.h" Car::Car(){ wieght = 10.0; } Car::Car(double wieght){ this->wieght = wieght; } double Car::get_wieght(){ return wieght; } void Car::set_wieght(double wieght){ this->wieght = wieght; } ~Car::Car(){ } (Side note: you have misspelled "weight".)
73,923,148
73,923,186
Why does the output always show 0 as LCM?
ERROR: type should be string, got "\nhttps://github.com/mehedihasrifat\n\nPlease correct my mistake**\n\nHow can I solve this issue?\n\nDid I do something wrong here?**\n\n\nI have been trying to debug this code but ultimately I can't. Please help me, I'm totally new to this platform.\nThis picture shows the following code\n/*\nWritten by Mehedi Hasan Rifat\nWritten on October 2, 2022\n*/\n\n#include <stdio.h>\n\nint main()\n{\n int a, b, t, gcd, lcm;\n\n printf(\"Enter two numbers: \");\n scanf(\"%d %d\", &a, &b);\n\n if (a == 0)\n gcd = b;\n else if (b == 0)\n gcd = a;\n else\n {\n while (b != 0)\n {\n t = b;\n b = a % b;\n a = t;\n }\n\n gcd = a;\n }\n\n lcm = (a * b) / gcd;\n\n printf(\"LCM: %d\\n\", lcm);\n\n return 0;\n}\n\n"
As jasonharper says in the comment, when you finished the gcd calculation, b will be always zero. One quick fix is to add int original_a = a; int original_b = b; and calculate lcm using: lcm = (original_a * original_b) / gcd; Or just use the __gcd() function in the <algorithm> library. #include <algorithm> int main() { ... lcm = (a * b) / std::__gcd(a, b); }
73,923,154
73,923,314
How can I check, straight away, if a set of pairs have a commom number?
Suppose we have 4 pairs, e.g.: pair<int, int> P1(1, 2); pair<int, int> P2(3, 1); pair<int, int> P3(2, 1); pair<int, int> P4(1, 5); How can I compare those 4 pairs straight away and conclude that they all have the number 1 in common? I can only think of comparing two by two, but that is a lot of work for a lot of pairs... Is there some function that does that for any given set of pairs?
In the sample code you've given, you need to check each pair (P1, P2, etc) separately (e.g. if (P1.first == 1 || P1.second == 1 || P2.first == 1 || <etc> )). If you insist on having P1, ... P4 as distinct variables, there are no shortcuts on that, since you've defined P1, P2, ... P4 in a way that imposes no logical or structural relationship between them. (e.g. there is no guarantee where they are located in machine memory - they could be together, they could be in completely unrelated memory locations). But having multiple variables with sequential names like P1, P2, ..... is an indication that you need to use a raw array (e.g. pair<int, int> P[4]) or a standard container (e.g. vector<pair<int, int> > P). If you structure your code using a raw array or a standard container then there are options. For example, a raw array; std::pair<int, int> P[4]; // set the four elements of P bool has_one = false; for (int i = 0; has_one == false && i < 4; ++i) if (P[i].first == 1 || P[i].second == 1) has_one = true; which is readily extendable to an arbitrary number of pairs, as long as the number is fixed at compile time. Keep in mind that array indexing starts at zero, not one (i.e. P[0] exists in the above but P[4] does not). The danger in such code is not updating the number correctly (e.g. changing the number of elements of P from 4 to 27, but forgetting to make the same change in the loop). Instead of a raw array, a better option is to use a standard container - particularly if you want to do multiple things with the set of pairs. If the number of pairs is fixed at compile time, the definition of P above can be changed to use the array standard container. std::array<std::pair<int, int>, 4> P; // array is from standard header <array> // assign the four elements of P (code omitted) which offers a number of advantages over using a raw array. If the number of pairs is not known at compile time (e.g. the number is computed based on values read at run time) you can use another standard container, such as // compute n as the number of elements std::vector<std::pair<int, int> > P (n); In all cases a raw array (with care to avoid problems such as checking more elements than an array has) and the standard containers can be used in loops. However, it is considered better (since it is less error prone) to avoid - where possible - using loops, and instead use algorithms supplied by the C++ standard library. For example (C++11 and later) you could do #include <algorithm> #include <vector> int main() { // compute n as the number of elements (code omitted) std::vector<std::pair<int, int>> P(n); // populate elements of P (code omitted) auto check_if_one = [](std::pair<int, int> a) {return a.first == 1 || a.second == 1;}; bool has_one = (std::find_if(std::begin(P), std::end(P), check_if_one) != std::end(P)); } The advantage of this is that the code always accounts correctly for the number of elements in P. The approach for calculating the value for has_one in the above is identical, regardless of whether P is a raw array, a std::array, a std::vector, or any other container in the standard library.
73,923,232
73,931,330
How to simplify variable parameter template functions?
Recently, I came up with an idea when learning to call function pointers. I used template variable parameters to construct template functions so that I can call function pointers #include<functional> #include<Windows.h> template<class T, class ...Args> decltype(auto) ExecuteFunc(LPVOID f, Args&& ...args) { if (f != nullptr) { return std::function<T>((T*)f)(std::forward<Args>(args)...); } } int main(){ ExecuteFunc<int(HWND, char*, char*, int)>(&MessageBoxA, (HWND)NULL, (char*)"Text", (char*)"caption", MB_OK); return 0; } Although this code runs well, it seems a bit too long picture Is there a way to shorten the code? I hope the code can be simplified to call. ExecuteFunc<int>(&MessageBoxA, (HWND)NULL, (char*)"Text", (char*)"caption", MB_OK); If you have some interesting ideas, please express them freely. Supplementary description. Some of the answers misunderstood my question and changed the type of the argument, which apparently std::invoke doesn't do yet. Argument one is passed in as a function pointer address, not the name of an already exported function Example 2. LPVOID FunAddr=&MessageBoxA; int ret=ExecuteFunc<int>(FunAddr, (HWND)NULL, (char*) "Text", (char*) "caption", MB_OK); int ret=ExecuteFunc<int> means that the return value of the function is of type int FunAddr is the address of a function where you can't directly give the symbolic name of the function the rest of the function's parameters Also I know that FunAddr doesn't have any available type information, but the parameters given can extract this type information and splice it to T(int,int) template<class T,class . .Args> T ExecuteFunc(LPVOID f, Args&&... .args) { }
Thank you to all our friends for your support and comments. Your enthusiastic comments have provided me with constructive help At the moment I have accepted a more simple answer, which meets my needs very well. The code and examples are as follows template<class T,class F, class ...Args> inline decltype(auto) ExecuteFunc(F f, Args&&...args) { return reinterpret_cast<T(*)(Args...)>(f)(args...); } Example #include<Windows.h> #include<iostream> template<class T, class F, class ...Args> inline decltype(auto) ExecuteFunc(F f, Args&&...args) { return reinterpret_cast<T(*)(Args...)>(f)(args...); } int Add(int a, int b) { return a + b; } int main(){ //1. LPVOID funcptr = &Add; std::cout << ExecuteFunc<int>(funcptr, 1, 2) << std::endl; //2. std::cout << ExecuteFunc<int>(Add, 3, 5) << std::endl; //3. ExecuteFunc<int>(MessageBoxA,(HWND)NULL, (char*)"Text", (char*)"caption", MB_OK); return 0; } Output
73,923,530
73,923,827
How to distinguish between pr-values and x-values
In the following code, #include <utility> struct literal_type { // ... }; class my_type { public: my_type(literal_type const& literal); // (1) my_type(literal_type && literal); // (2) // ... }; void foo() { literal_type literal_var { /* ... */ }; my_type var1 (literal_var); // Calls (1) my_type var2 (std::move(var)); // Calls (2) my_type var3 (literal_type{}); // Calls (2) } I understand that the value category of the argument passed in the constructor of var1 is an l-value, var2 is an x-value and var3 is a pr-value. I would like that the constructor of my_type accepts var3, while var1 and var2 should emit a compiler error. var1 is easily solved by removing constructor (1), but I cannot find the way to distinguish between var2 and var3. Is there any way to distinguish between x-value references and pr-value references?
You can't. You can distinguish xvalue and prvalues at the call site, but once you've passed them to a function that accepts them, you've lost the information of which of the two it was. The reason is that the value category is a property of an expression, and inside of the constructors literal has always the lvalue value category, because it's the name of a parameter. The value category of the corresponding argument, instead, can be encoded in the type of the parameter if you declare it as forwarding reference, but that will carry you as far to distinguish lvalue vs rvalue, not giving you the lvalue vs xvalue vs prvalue granularity. #include <iostream> #include <memory> #include <utility> struct literal_type { }; class my_type { public: my_type(literal_type const&) {} template<typename T> my_type(T&&) { static_assert(std::is_same_v<T, literal_type>); // passes static_assert(std::is_same_v<T&&, literal_type&&>); // passes } }; void foo() { literal_type literal_var { }; my_type var2 (std::move(literal_var)); // Calls (2) my_type var3 (literal_type{}); // Calls (2) } And if the original value category of the argument is not encoded in the type of the parameter, where would you ever get it from? After all, the purpose of std::move is exactly to dress up a value like a temporary (whether it was already or not). In other words, if you use f(std::move(nonTemporary)) and f(temporary) at the call site, why would you ever want nonTemporary to be treated differently from temporary? If you really want, then you're misusing std::move in the first place. I saw the suggestion of Make the parameter type non-copyable and non-movable, and pass by value, but I would never take such a route before clarifying first what you actually want to do.
73,923,608
73,923,732
Why are these 2 sectors different?
i tried to read ntfs partition. main function: int main(int argc, char** argv) { BYTE sector[512]; ReadSector(L"\\\\.\\E:", 0, sector); PrintBPB(ReadBPB(sector)); BYTE sector2[512]; ReadSector(L"\\\\.\\E:", 0, sector2); PrintBPB(ReadBPB(sector2)); return 0; } ReadSector function: int ReadSector(LPCWSTR drive, long readPoint, BYTE sector[Sector_Size]) { int retCode = 0; DWORD bytesRead; HANDLE device = NULL; device = CreateFile(drive, // Drive to open GENERIC_READ, // Access mode FILE_SHARE_READ | FILE_SHARE_WRITE, // Share Mode NULL, // Security Descriptor OPEN_EXISTING, // How to create 0, // File attributes NULL); // Handle to template if (device == INVALID_HANDLE_VALUE) // Open Error { printf("CreateFile: %u\n", GetLastError()); return 1; } SetFilePointer(device, readPoint, NULL, FILE_BEGIN);//Set a Point to Read if (!ReadFile(device, sector, 512, &bytesRead, NULL)) { printf("ReadFile: %u\n", GetLastError()); } else { printf("Success!\n"); } CloseHandle(device); } I think the way I copy those bytes into my BPB bpb is fine. So what happend? Why they are different? I can figure out that its relate to winapi, readfile, createfile but I still dont understand it :( sorry for my bad english.
The bug is in the code we cannot see: PrintBPB. Apparently it switches to hexadecimal output (for the "Volume serial number") and then fails to switch back to decimal until later. When the code calls PrintBPB a second time the output mode is still in hexadecimal format, and printing "Bytes per Sector" now displays 200 (0x200 is the same value as 512). If you need to know whether two chunks of memory hold identical values, just memcmp them. This avoids introducing a bug in a transformation (such as console output).
73,923,683
73,923,722
what does while(pointer) and if(pointer) mean?
I don't know why 'currentNode'pointer is in () beside 'while' and 'if'. Node* currentNode = head; while (currentNode) { Node* toBeDeleted = currentNode; currentNode = currentNode->next; delete toBeDeleted; ......} Node* successor = currentNode->next; Node* predecessor = currentNode->previous; if (successor) { successor->previous = predecessor; ....}
A pointer variable is compatible with boolean in C. C considers every not-null pointer variable as True, and every variable pointing to NULL is considered as False.
73,924,259
73,930,415
Is there a way to put as a parameter only one row of a 2d array?
I'm trying to call the getAverage function in the last cout on printResults, but when I call it, it just give me the same average for all the cases. For example, if I put that first students grades are 50 50 and 50, the average would come 50 for the second and third even if they have different scores. I tried a loop with the first and second index, but it sums all of the points of each row. I want it to sum only the points of one row and give me the average. Then when I call it again sum the second row and give me the average. All of this without declaring another variable. (The code is an assigment and I have to do it this way) #include <iostream> using namespace std; const int EXAMS = 3; void getScores(int[][EXAMS], const int); int getAverage(int[], const int); // this method requires an array and its length as parameters char getGrade(int); void printResults(int[][EXAMS], const int); int main() { const int STUDENTS = 5; int scores[STUDENTS][EXAMS] = {0}; printResults(scores, STUDENTS); cout << endl; system("pause"); // for Visual Studio only return 0; } void getScores(int scores[][EXAMS], const int students) { for (int i = 0; i < students; i++) { for (int j = 0; j < EXAMS; j++) { cout << "Enter the score for student #" << i + 1 << ", test #" << j + 1 << ": "; cin >> scores[i][j]; } cout << endl; } } // The getAverage method receives an array and its length as parameters, and // returns an integer value. It computes the average by adding the values in // the array, which are stored in the integer variable sum, and then dividing // by the array's size. Use a for iteration control structure to add all the values. int getAverage(int scores[][EXAMS], const int students) { int sum = 0; for (int i = 0; i < EXAMS; i++) { sum += scores[0][i]; } return sum / EXAMS; } // DO NOT DECLARE any variables in this method. char getGrade(int finalAverage) { if (finalAverage < 59) return 'F'; else if (finalAverage < 69) return 'D'; else if (finalAverage < 79) return 'C'; else if (finalAverage < 89) return 'B'; else return 'A'; } // DO NOT DECLARE any variables in this method. void printResults(int scores[][EXAMS], const int students) { getScores(scores, students); for(int j = 0; j < students; j++) { cout << "The student with test scores "; for (int i = 0; i < EXAMS; i++) { if (i == EXAMS - 1) cout << "and " << scores[j][i] << ", "; else cout << scores[j][i] << ", "; } cout << "scored a final average of " << getAverage(scores, students) << " and earned a(n) " << getGrade(getAverage(scores, students)) << endl; } } I would solve it this way, without the function. But the assignment reequires me to do it with the function and without declaring any variables in the printResults method. void printResults(int scores[][EXAMS], const int students) { getScores(scores, students); for(int j = 0; j < students; j++) { int sum = 0; cout << "The student with test scores "; for (int i = 0; i < EXAMS; i++) { if (i == EXAMS - 1) cout << "and " << scores[j][i] << ", "; else cout << scores[j][i] << ", "; sum += scores[j][i]; } cout << "scored a final average of " << sum / EXAMS << " and earned a(n) " << getGrade(sum / EXAMS) << endl; } }
In the comments section of your question, you stated that the line int getAverage(int scores[][EXAMS], const int students) was written by you and not provided by the assignment. However, according to the code comments above the function definition (which I assume were provided by the assignment and not written by you), the function should only deal with a 1D array, i.e. a sub-array of the 2D array. Therefore, you should change the function signature to the following: int getAverage( int scores[], int students ) Due to array to pointer decay (arrays themselves are not passed to functions, only pointers to arrays), this is equivalent to the following: int getAverage( int *scores, int students ) Since the size of the array is passed to the function, the function should take this size into account. Therefore, the function should be rewritten like this: int getAverage( int scores[], int students ) { int sum = 0; for ( int i = 0; i < students; i++ ) { sum += scores[i]; } return sum / students; } Now that the function getAverage only accepts a 1D array instead of a 2D array, the function call of getAverage in the function printResults should be rewritten to only pass a sub-array of the 2D array, instead of the entire 2D array: void printResults(int scores[][EXAMS], const int students) { getScores(scores, students); for(int j = 0; j < students; j++) { cout << "The student with test scores "; for (int i = 0; i < EXAMS; i++) { if (i == EXAMS - 1) cout << "and " << scores[j][i] << ", "; else cout << scores[j][i] << ", "; } cout << "scored a final average of " << getAverage(scores[j], EXAMS) << " and earned a " << getGrade(getAverage(scores[j], EXAMS)) << endl; } } Note that it is not very efficient to call getAverage twice with the same arguments, because this means that the average must be computed twice. It would be better if you only called the function getAverage once and saved the result in a variable. However, as far as I can tell, your assignment restrictions forbid declaring another variable, so you cannot follow this recommendation in this case. It is also worth noting that it is common practice to use i as the loop counter of the outer loop and j as the loop counter of the inner loop. You are doing the opposite in your case, which is confusing for most programmers reading your code. Additionally, even if this code works, it would probably be more logical to call the function getScores in the function main, instead of the function printResults. This is because the function name printResults implies that the function will only print the results, but not actually calculate the results. Therefore, if the restrictions on your assignment allow it, I would recommend removing the function call to getScores from the function printResults, and rewrite the function main like this: int main() { const int STUDENTS = 5; int scores[STUDENTS][EXAMS] = {0}; getScores(scores, STUDENTS); printResults(scores, STUDENTS); cout << endl; system("pause"); // for Visual Studio only return 0; }
73,924,294
73,924,314
cannot access member data via ' *this '
Say if I have a class named cube which refers to a 3D cube, and it has a private member data called _height. Within the class I tried to use this->_height and it works. (I know '_height' along is enough. I just want to try more about 'this' pointer). However when I use *this._height inside the class. It reports error. 'this' is a pointer points to the object in use thus 'pointer->member' method is valid. Meanwhile '*this' should be the object itself, but why it forbids me to use the '.' (dot) method?
Due to the precedence of the . over the * you need to put brackets around to make sure you get what you want: (*this)._height
73,924,477
73,924,571
Passing an array to a function declared in two different ways
So, I have declared an array using the <array> header in C++, and now I want to pass this array to a function that doesn't return any value but displays each element in a new line on the terminal. Following is the code for that. // to pass an array to a function #include <iostream> #include <array> using namespace std; void myFunction(int arr[5]); // function prototype int main () { array <int, 5> arr{1, 2, 3, 4, 5}; myFunction(arr); } // function definition void myFunction(int arr[5]) { for (size_t counter{0}; counter < 5; ++counter) { cout << arr[counter] << endl; } } The above code isn't working. arr no suitable conversion function from "std::array<int, 5ULL>" to "int *" existsC/C++(413) ... demo.cpp: In function 'int main()': demo.cpp:11:16: error: cannot convert 'std::array<int, 5>' to 'int*' 11 | myFunction(arr); | ^~~ | | | std::array<int, 5> demo.cpp:6:21: note: initializing argument 1 of 'void myFunction(int*)' 6 | void myFunction(int arr[5]); // function prototype | These two are the error messages getting shown to me. Now on the other hand, if I declare the array differently, without using the standard library header, it works fine. arr[5] {1, 2, 3, 4, 5}; // instead of // array <int, 5> arr{1, 2, 3, 4, 5}; It produces the following result 1 2 3 4 5 I just want to know what the array declarations have to do with any of this? If there is a way of doing this using the declaration with <array> header, what is it?
The problem is that your function expects an int* but you're passing a array <int, 5> but since there is no implicit conversion from array <int, 5> to int*, we get the mentioned error. You can also use std::array::data as myFunction(arr.data()); to make this work. The reason your second case works when you create array like int arr[5] {1, 2, 3, 4, 5}; and then pass it like myFunction(arr) is because a built in array decays to a pointer to its first element(int* in your example) due to type decay. So in this modified case, the type of the argument and the parameter matches and this works.
73,924,910
73,924,958
How to ignore parameter pack arguments
With the expression (void)var; we can effectively disable unused variable warnings. However, how does that work with arguments in a parameter pack? template<bool Debug = DebugMode, typename... Arg> void log_debug(const Arg&... args) { if constexpr(Debug) { (std::clog << ... << args) << std::endl; } else { //ignore the arguments willingly when not in debug (void)args; // does not compile } }
I suggest using maybe_unused: template<bool Debug = DebugMode, typename... Arg> void log_debug([[maybe_unused]] Arg&&... args) { If you for some reason don't want that, you could make a fold expression over the comma operator in your else: } else { (..., (void)args); }
73,925,410
73,925,476
static check an out of bounds
I have this method, that just gets an element of a member, which is a c-style array. constexpr T get(const int&& idx) const { static_assert(idx >= sizeof(array) / sizeof(T)); return array[idx]; } I would like to statically check for a value on the parameter that will try to recover an element on the member that is out of bounds. So, the code will refuse to compile. I tried with static assert, but, obviously: function parameter 'idx' with unknown value cannot be used in a constant expression What is the idiomatic way on modern C++ of achieve this? Is possible to check it at compile time? If not, what is the less overhead version of report an illegal access to the member? I would like to mantain the code exception free. Edit: // call site example decltype(auto) a = collections::StackArray<int, 5>{1, 2, 3, 4, 5}; auto val = a.get(6); I am providing a literal (6), so I was thinking that this value should be checked at compile time. Even greater, if I will try to obtain user input for the .get() call, code could also refuse to compile. auto in; cin >> in; a.get(in) // Wrong! But also will limit potencial operations like looping over the array and use the .get() method, I suppose. Even tho, the subscript operator could be used instead (without no bounds checking).
idx is not a compile-time constant, so you cannot assert this at compile-time (which is what static_assert is for). You don't know at compile-time what values the function will be called with. You can use a runtime assert from <cassert> instead, however that is typically meant for debug builds only (defining the macro NDEBUG as typical in release builds will disable all assert). The usual approach in C++ is to throw a std::out_of_range exception: #include<stdexcept> //... constexpr T get(std::size_t idx) const { if(idx >= std::size(array)) { throw std::out_of_range("idx out of bounds"); } return array[idx]; } I also replaced the unsafe size construction with std::size which gives you the size of an array without any potential usage errors as are common with the sizeof construction (e.g. applying it to a pointer instead of a array). Note that if you replace the built-in array with std::array, you get this throwing accessor for free from its .at member function. Furthermore, a const rvalue reference is pointless and really confusing (there is no real use case for them). Just take the index by value: const int&& -> int. And furthermore the index should typically be of type std::size_t to match the natural index type of built-in arrays (and other containers). At the very least it should be unsigned, because otherwise the implicit conversions in the comparison may turn negative values into positive ones and mess up your check. (The compiler should be warning you about this.) In either the throwing or assert case (without NDEBUG defined) the compiler will fail to compile the program if the function is called with an out-of-bounds index in a context which requires a constant expression, which is the closest you can get to doing this check at compile-time. But then again, trying to access the array itself out-of-bounds in a context requiring a constant expression will also cause a compilation failure, so an explicit compile-time check is not needed.
73,925,567
73,927,090
Char sort plus print with rows and columns
Hello i really need help, should make from two chars to camper first with second and if some symbol is include, should print them in row and column, also in same position where they are same; if my inputs are gold and xxlz should look like this. x x gold z if they they dont had same symbol should print on last index of first word. #include <iostream> #include <stdlib.h> #include <string> #include <algorithm> using namespace std; int main() { char firstWord[15]; char secondWord[15]; cout << "enter first than second word\n"; cin >> firstWord >> secondWord; int lenthOne = strlen(firstWord); int lenthSecond = strlen(secondWord); for (int i = 0; i < lenthOne; i++) { cout << firstWord[i]; for (int j = 0; j < lenthSecond; j++) { if (firstWord[i] == secondWord[j]) { cout << secondWord; } } } }
You solved already the comparison of each character of both words. Now, after having found a match, you need to show the crossword. For that, we imagine a 2-dimensional grid of rows and columns. Like the below column row 01234 0 x 1 x 2 gold 3 l 4 We need to print row by row. If the row is equal to the matching index of the first word ("gold", character 'l', index 3), then we need to print the complete first word. If not, then we first need sto print a number of blanks. Also here the number is given by index of the matched character, but here of the second word. So, we will print the number of blanks as explained above and then output the character of the second word at the index of the row. Very simple. There are many many potential solutions. I will show one of the many, but I will not use C-Style char arrays for strings. In C++ we use std::string for that. But you may simply adapt that also to C-style. Please see: #include <iostream> #include <string> int main() { // Here we will store the owrds that shall be evaluated std::string firstWord{}, secondWord{}; // Tell user, what to do and get the words std::cout << "Enter first and second word\n"; std::cin >> firstWord >> secondWord; std::cout << "\n\n"; // Here we will remember, if there was a match at all bool matchFound{}; // Now compare all characters of first word with all characters of second word for (size_t firstWordIndex{}; firstWordIndex < firstWord.length(); ++firstWordIndex) { for (size_t secondWordIndex{}; secondWordIndex < secondWord.length(); ++secondWordIndex) { // Check, if we have an equal character in both words if (firstWord[firstWordIndex] == secondWord[secondWordIndex]) { // Remember that we found at least one match matchFound = true; // We found a matching character. Now show the crossword for (size_t row{}; row < firstWord.length(); ++row) { // If we shall show the complete second word if (row == firstWordIndex) { std::cout << firstWord << '\n'; } else { // Show only part of second word. Insert blanks before for (size_t blankCounter{}; blankCounter < secondWordIndex; ++blankCounter) std::cout << ' '; // print letter std::cout << secondWord[row] << '\n'; } } std::cout << "\n\n\n"; } } } // If there was no match, then simply show both words if (not matchFound) { std::cout << firstWord << '\n'; // Use a separate row for each character of the second word for (size_t row{}; row < secondWord.length(); ++row) { // print blanks in front of character for (size_t blankCounter{}; blankCounter < firstWord.length(); ++blankCounter) std::cout << ' '; // Print the character std::cout << secondWord[row] << '\n'; } } }
73,925,683
73,925,716
Iterating over an std::vector two elements at a time plus last and first elements too
I am trying to iterate over a vector say {1,3,4,2} and collecting pairs basically (1,3), (3,4), (4,2), (2,1). Collecting the first three pairs is easy but doing the last one is a bit difficult. This is what I have: #include <vector> #include <iostream> int main() { auto v = std::vector<int>{1,3,4,2}; auto vecOfPairs = std::vector<std::pair<int,int>>{}; for ( auto it = v.begin(); it != v.end() - 1; ++it) { auto a = *it; auto b = *(it+1); // DO some stuff with a and b vecOfPairs.push_back(std::make_pair(a, b)); } auto front = v.front(); auto back = v.back(); // Do the same some stuff with front and back vecOfPairs.push_back(std::make_pair(back, front)); for (const auto& pair : vecOfPairs) std::cout << pair.first << ", " << pair.second << '\n'; } While this works, there is some code duplication (once I have the two values, I do some further calculations with those two values before making a pair and pushing it to the vectors. Is there a way to avoid this and just do the last operating in the same for loop?
It is simpler if you use plain subscripting. You can then add 1 and take the remainder with % v.size(): for(size_t i = 0; i < v.size(); ++i) { vecOfPairs.emplace_back(v[i], v[(i + 1) % v.size()]); }
73,926,356
73,927,946
How to examine bytes in gdb without printing labels?
GDB is trying to be helpful by labeling what I believe are global variables, but in this case each global is more than 0x10 bytes and so the second part of the variable is printed on the next line, but with an offset added to its label, which throws off the alignment of the whole printout (generated by executing x/50wx 0x604130): Is there a command to disable these labels while examining bytes? Edit: to be more specific, I would like to printout exactly what is shown in the screenshot, just without the <n1> / <n1+16> labels that are throwing off the alignment of the columns
Is there a command to disable these labels while examining bytes? I don't believe there is. One might expect that set print symbol off would do it, but it doesn't. The closest I can suggest is this answer.
73,927,045
73,927,109
Is there a way to give a specification about the allowed values of a non-type template parameter?
For example, is there a way of saying "n must be larger than 2" in this code? template<int n> class MyClass { ... }
Use requires from C++20: template <int n> requires(n > 2) // The parentheses are often optional, but not with this condition. class MyClass { // ... }; Alternatively you can use a static_assert: template <int n> class MyClass { static_assert(n > 2, "N must be less or equal to 2."); // The description is optional. // ... }; The first option doesn't let you specify a custom message, but is "SFINAE-friendly", i.e. it's possible to check the condition from a different template without triggering the error on failure. But it doesn't let you specify a custom message. The first option is usually preferred. The first option can be replicated pre-C++20 with std::enable_if_t, see @SamVarshavchik's answer.
73,927,213
73,927,301
std::regex_search return multiple matches
In regex engines that I'm familiar with, it's possible to return every instance of a matching substring. E.g. the following Perl code gives the output shown: my $data = "one two three four"; my @result = ($data =~ /(\w+)/g); say "@result"; output: one two three four So all four matches are returned, when the "g" modifier is used. If I try to do the same thing using std::regex_search, only the first match is returned. I.e.: std::string srchStr = "one two three four"; std::regex r("(\\w+)"); std::smatch m; if (regex_search(srchStr, m, r)) { std::cout << "m.size()=" << m.size() << std::endl; for (const std::string &s : m) { std::cout << s << std::endl; } } output: m.size()=2 one one Is there something like the g operator in perl that will cause it to return all the matches? Thanks
You use std::sregex_iterator: #include <iostream> #include <regex> #include <string> int main() { std::string const s{"one two three four"}; std::regex const r{"(\\w+)"}; for (std::sregex_iterator it{s.begin(), s.end(), r}, end{}; it != end; ++it) { std::cout << it->str() << '\n'; } }
73,927,332
73,927,472
copy 2d vector without first row and column
Just like in topic. I would like to copy one vector to another without first row and column. ''' std::vector<std::vector<int>> v2(v1.size()-1,std::vector<int>(v1.size()-1)); std::copy((v1.begin()+1)->begin()+1,v1.end()->end(),v2.begin()->begin()); return v2; '''
Using C++ and views it is easy to drop items while enumerating. So you can avoid using raw or iterator loops. Live demo here : https://godbolt.org/z/8xz91Y8cK #include <ranges> #include <iostream> #include <vector> auto reduce_copy(const std::vector<std::vector<int>> values) { std::vector<std::vector<int>> retval{}; // drop first row for (const auto& row : values | std::views::drop(1)) { // add a new row to retval auto& new_row = retval.emplace_back(); // drop first column for (const auto& col : row | std::views::drop(1)) { new_row.emplace_back(col); } } return retval; } int main() { std::vector<std::vector<int>> values{ {1,2,3}, {4,5,6}, {7,8,9} }; auto result = reduce_copy(values); for (const auto& row : result) { for (const auto& value : row) { std::cout << value << " "; } std::cout << "\n"; } return 0; }
73,927,457
74,222,492
Item views: setSelectionModel and support for row editing
In my Qt (6.3.1) application, for a model I developed, I noticed the submit() method being called all the time. After some debugging, I noticed, in void QTableView::setSelectionModel/QTreeView::setSelectionModel, this: if (d->selectionModel) { // support row editing connect(d->selectionModel, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), d->model, SLOT(submit())); } The documentation for QAbstractItemModel::submit() mentions "this function is typically used for row editing", which means this is done on purpose. I have got more than 1 problem with this way of doing things, compared to the alternative of letting/requiring application developers to create the connection themselves: Views do not seem to have a property to stop this connection from being created, hence the behavior is more than just a default, it is mandatory. I do not see any way to know what to do except looking through Qt's source code. I had rather have to create the connection myself if I want it. Only QSqlTableModel seems to have a mechanism to handle this (editStrategy()) but I could find nothing in neither QAbstractItemModel nor QAbstractTableModel. -> what would be a good reason to want this connection above to be always created? Or am I perhaps wrong thinking this design is a bad one?
Answering my own question after 4 weeks without another answer nor any comment. Despite having found a solution that seems to work in every case (see below), I still think this very design choice made by Qt as well as other special case they implemented are bad choices, would be interested to read other opinions in the comments. Better than disconnecting signals, the solution I ended up implementing was to subclass QIdentityProxyModel and create an attribute to block the calls to submit (+ optionally revert). void MyModel::revert() { if (forwardRevertCalls) QIdentityProxyModel::revert(); } bool MyModel::submit() { if (forwardSubmitCalls) return QIdentityProxyModel::submit(); else return false; } The reason for this choice is because of another special case in QStyledItemDelegate::eventFilter. Found in the documentation: If the editor's type is QTextEdit or QPlainTextEdit then Enter and Return keys are not handled. And I suppose things like QSpinBox do not behave this way. This was causing submit to be called whenever I pressed Enter to validate an input in my model and change the selected row in 1 input; more precisely, it would execute case QAbstractItemDelegate::SubmitModelCache in QAbstractItemView::closeEditor.
73,927,884
73,928,252
Does C++ standard guarantee such kinds of indirect access well defined?
Below has 3 different styles for indirect accessing. I am trying to understand if they all have well-defined behavior, and can be safely used for cross-platform code. #include <cstdint> #include <iostream> #include <any> using namespace std; #if 1 #define INLINE [[gnu::always_inline]] inline #else #define INLINE [[gnu::noinline]] #endif INLINE void mod1(void *p) { *static_cast<int*>(p) = 10; } INLINE void mod2(uintptr_t p) { *reinterpret_cast<int*>(p) = 12; } INLINE void mod3(any p) { *any_cast<int*>(p) = 14; } int test1() { int a1 = 5; mod1(&a1); return a1; } int test2() { int a2 = 6; mod2(reinterpret_cast<uintptr_t>(&a2)); return a2; } int test3() { int a3 = 6; mod3(&a3); return a3; } int main() { cout << test1() << "\n"; cout << test2() << "\n"; cout << test3() << "\n"; } I tried inline and noinline, they all work as expected, output 10 12 14 so I think inlining does not matter here. Are they all well-defined behavior by C++ standard? Any help would be greatly appreciated :) [Edit] Even if we consider type-based alias analysis.
Technically the behavior of neither of these is specified by the standard, because you are using implementation-defined attributes which could have any effect. However practically speaking these attributes are irrelevant to the behavior here. That aside: test1 is correct and specified to work as expected. Casting an object pointer to (possibly cv-qualified) void* and back to the original type via static_cast or reinterpret_cast is always allowed and yields the original pointer value. However this round-trip through void* to the same type is the only sequence of such casts that has this guarantee in general. test2 is conditionally-supported. It is not guaranteed by the C++ standard that std::uintptr_t or any other type to which object pointers can be converted exists. If std::uintptr_t does exist, then the behavior is well-defined with the expected output. The mapping between integral and object pointer types is implementation-defined except that round-trip casting back to the original pointer type through an integral type of sufficient size yields the original pointer value. test3 is well-defined to give the expected result, except that it may (in contrast to the other two cases) fail by throwing std::bad_alloc. The whole point of std::any is that you can put any type (e.g. int*) into it and access it again in a type-safe manner with std::any_cast. It also requires RTTI which is sometimes disabled on purpose (in non-conformance to the standard).
73,927,889
73,941,622
How to call c++ methods from rust?
I would like to call the c++ methods from rust. I heard I need to create vtables(VMTs), but how can I do that? How is that different from what I did? C++: struct numbers { int addnums(int a, int b) { return a + b; } }; struct v_numbers { virtual int v_addnums(int a, int b) { return a + b; } }; Rust(wrong, not linking): extern "system" { fn addnums(a: i32, b: i32) -> i32; fn v_addnums(a: i32, b: i32) -> i32; } fn main() { unsafe { println!("{}", addnums(1, 2)); println!("{}", v_addnums(1, 2)); } }
To the people who commented: The example I gave to you, was a simplified version of what I was trying to do. I was thinking this example is so simple, that people would recognize that it is a simplified version of something. I am sorry for assuming something like that. You know, not all C++ libraries have "classic C-style functions". But on the other hand, you had no intentions to help me, right? Yes, obviously I can modify the C++ code in this example, but what would be the point in doing that? I came up with a problem, I needed an answer for that. I could not change the problem, because it would be a different problem then. I solved it. It is working only for pure virtual method structs, but I only need those so, I'm fine with it. C++: struct numbers { virtual int addnums(int a, int b) { return a + b; } }; extern "C" numbers* get_numbers() { numbers* num = new numbers(); return num; } Rust: #![allow(non_snake_case)] extern "system" { fn get_numbers() -> *mut usize; } #[repr(C)] pub struct numbers_vtbl { pub addnums: unsafe extern "system" fn(This: *mut numbers, a: i32, b: i32) -> i32, } #[repr(C)] pub struct numbers { pub lpVtbl: *const numbers_vtbl, } impl numbers { #[inline] pub unsafe fn addnums(&self, a: i32, b: i32) -> i32 { ((*self.lpVtbl).addnums)(self as *const _ as *mut _, a, b) } } fn main() { unsafe { let a = get_numbers() as *mut numbers; let b = (*a).addnums(14, 53); println!("{}", b); } }
73,927,930
73,928,144
How can I have a dynamic array without using a vector? C++
The program question is as follows: Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. That list is followed by two more integers representing lower and upper bounds of a range. Your program should output all integers from the list that are within that range (inclusive of the bounds). For coding simplicity, follow each output integer by a comma, even the last one. The output ends with a newline. My professor is asking me to do this program without the use of vectors. However I can't seem to understand that without a user inputting the total number of indices for the array. When I do try the way with the comments I made I get the error: Exited with return code -11 (SIGSEGV) #include <vector> using namespace std; int main() { int i; int userARR; const int NUM_ARR = 5; int inputList[NUM_ARR]; int minR; int maxR; //cin >> userARR; //i < userARR;? for (i = 0; i < NUM_ARR; ++i) { cin >> inputList[i]; } cin >> minR >> maxR; //i < userARR;? for (i = 0; i < NUM_ARR; ++i) { if ((inputList[i] >= minR) && (inputList[i] <= maxR)) { cout << inputList[i] << ","; } } cout << endl; return 0; }
Because C++ does not support variable length arrays (outside of compiler-specific extensions), you want to use a dynamically allocated array based on the input sample size. Such an array can be created with new, and then deallocated with delete[]. #include <iostream> int main() { int sample, lower_bound, upper_bound; std::cin >> sample >> lower_bound >> upper_bound; auto arr = new int[sample]; for (int i = 0; i < sample; i++) { std::cin >> arr[i]; } for (int i = 0; i < sample; i++) { if (arr[i] >= lower_bound && arr[i] <= upper_bound) { std::cout << arr[i] << ", "; } } std::cout << std::endl; delete[] arr; return 0; } As a general rule, you should avoid using new and delete where possible, favoring std::vector in this scenario, but from an educational standpoint it's good to know how to use them. If you wanted to avoid needing to explicitly deallocate you might alternately use a smart pointer which will handle the memory deallocation for you. #include <memory> #include <iostream> int main() { int sample, lower_bound, upper_bound; std::cin >> sample >> lower_bound >> upper_bound; auto arr = std::make_unique<int[]>(sample); for (int i = 0; i < sample; i++) { std::cin >> arr[i]; } for (int i = 0; i < sample; i++) { if (arr[i] >= lower_bound && arr[i] <= upper_bound) { std::cout << arr[i] << ", "; } } std::cout << std::endl; return 0; }
73,928,772
73,928,797
What are header only version in Boost C++ Libraries?
I am working on my assignment in which I think I can use boost.serialization library. But we are asked to use only header only version of boost. So I want to know wheather boost.serialization fall under header only version or not?
No, it requires linking with the boost_serialization or boost_wserialization library. Failing to link with the library will for the most basic demo on the boost site produce a long list of undefined references: undefined reference to... `boost::archive::archive_exception::~archive_exception()' `boost::archive::archive_exception::archive_exception(boost::archive::archive_exception const&)' `boost::archive::archive_exception::archive_exception(boost::archive::archive_exception::exception_code, char const*, char const*)' `boost::archive::basic_text_iprimitive<std::istream>::~basic_text_iprimitive()' `boost::archive::basic_text_oarchive<boost::archive::text_oarchive>::init()' `boost::archive::basic_text_oarchive<boost::archive::text_oarchive>::newtoken()' `boost::archive::basic_text_oprimitive<std::ostream>::~basic_text_oprimitive()' `boost::archive::detail::basic_iarchive::~basic_iarchive()' `boost::archive::detail::basic_iarchive::load_object(void*, boost::archive::detail::basic_iserializer const&)' `boost::archive::detail::basic_iserializer::~basic_iserializer()' `boost::archive::detail::basic_iserializer::basic_iserializer(boost::serialization::extended_type_info const&)' `boost::archive::detail::basic_oarchive::~basic_oarchive()' `boost::archive::detail::basic_oarchive::end_preamble()' `boost::archive::detail::basic_oarchive::save_object(void const*, boost::archive::detail::basic_oserializer const&)' `boost::archive::detail::basic_oserializer::~basic_oserializer()' `boost::archive::detail::basic_oserializer::basic_oserializer(boost::serialization::extended_type_info const&)' `boost::archive::text_iarchive_impl<boost::archive::text_iarchive>::init()' `boost::archive::text_iarchive_impl<boost::archive::text_iarchive>::load_override(boost::archive::class_name_type&)' `boost::archive::text_iarchive_impl<boost::archive::text_iarchive>::text_iarchive_impl(std::istream&, unsigned int)' `boost::archive::text_oarchive_impl<boost::archive::text_oarchive>::save(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)' `boost::archive::text_oarchive_impl<boost::archive::text_oarchive>::text_oarchive_impl(std::ostream&, unsigned int)' `boost::serialization::extended_type_info::key_register() const' `boost::serialization::extended_type_info::key_unregister() const' `boost::serialization::typeid_system::extended_type_info_typeid_0::~extended_type_info_typeid_0()' `boost::serialization::typeid_system::extended_type_info_typeid_0::extended_type_info_typeid_0(char const*)' `boost::serialization::typeid_system::extended_type_info_typeid_0::is_equal(boost::serialization::extended_type_info const&) const' `boost::serialization::typeid_system::extended_type_info_typeid_0::is_less_than(boost::serialization::extended_type_info const&) const' `boost::serialization::typeid_system::extended_type_info_typeid_0::type_register(std::type_info const&)' `boost::serialization::typeid_system::extended_type_info_typeid_0::type_unregister()' `typeinfo for boost::archive::archive_exception' `typeinfo for boost::archive::detail::basic_iarchive' `typeinfo for boost::archive::detail::basic_iserializer' `typeinfo for boost::archive::detail::basic_oarchive' `typeinfo for boost::archive::detail::basic_oserializer' `typeinfo for boost::serialization::typeid_system::extended_type_info_typeid_0'
73,929,080
73,929,624
Error with Clang 15 and C++20 `std::views::filter`
I'm wondering why this code doesn't compile with clang 15, even though the ranges library is marked as fully supported in clang 15 on the compiler support page? It does compile with g++12, even if the support is marked only as partial, and it compiles with clang trunk. #include <ranges> #include <vector> int main() { std::vector x{1,2,3,4}; auto y = x | std::views::filter([](auto i){ return i <2;}); } Is the code incorrect? And if it is, is there a way to work around the bug until clang 16 gets released. I guess ranges-v3 would work, but perhaps someone knows how to fix it using only the standard library. Interestingly, I get different errors when using -stdlib=libstdc++ and -stdlib=libc++: libstdc++: error: invalid operands to binary expression ('std::vector<int>' and '_Partial<std::ranges::views::_Filter, decay_t<(lambda at <source>:7:37)>>' (aka '_Partial<std::ranges::views::_Filter, (lambda at <source>:7:37)>')) libc++: error: no member named 'views' in namespace 'std' Compiler Explorer.
The code is fine. However Clang's implementation of concepts is broken in a way that libstdc++'s views don't work. This has been a known issue for a while, but apparently has been resolved a few days ago. The code now works on Clang trunk with libstdc++. See similar question and relevant bug reports 1 and 2. Libc++'s implementation of views is guarded behind the -fexperimental-library flag with which the particular example in your question also compiles. I am not sure, but I think the implementation is still incomplete, which is why it isn't enabled by default. It could be that my information on that is outdated though, in which case the guard might be there only to wait for stabilization. Update: Both of these issues have been resolved on current LLVM trunk. The linked bug reports regarding libstdc++'s views implementation have been fixed. The libc++ views implementation (at least for the code in the question) is no longer guarded with -fexperimental-library. So I would expect that the LLVM 16 release will work with the shown code fine.
73,929,123
73,929,204
String functions from Windows Visual Studio seem to not work when compiled through g++ on Ubuntu(Linux Mint)
I was working on a project for my class through visual studio(windows) because I like the compiler a bit more, but when I copy/pasted the code to ubuntu linux(linux mint cinnamon) and ran both a g++ compiler and a cmake build on it, the string functions did not seem to be defined correctly and I received the following errors. The main code which has been causing the issue is here: int main() { //start up //load commands.csv into a singly linked list srand(time(NULL));//starts up a randomized seed fstream commandFile; commandFile.open("commands.csv"); string line = ""; linkedList commandList; Profile* profileList = NULL; int profileSize = 0; while (getline(commandFile,line)) {//while loop will run as long as there is a line to read string name; string description; stringstream inputString(line);//stringstream is used for more string functionallity getline(inputString, name, ','); getline(inputString, description); description.erase(remove(description.begin(),description.end(),'\"'),description.end());//removes all quotation marks from a string. Command data; data.setName(name); data.setDescription(description); commandList.insertNode(data);//commands are being stored in a singly linked list line = ""; } commandFile.close(); or more specifically this line: description.erase(remove(description.begin(),description.end(),'\"'),description.end()); The goal is simply to remove a given character from a given string which is shown on this website: https://www.tutorialspoint.com/how-to-remove-certain-characters-from-a-string-in-cplusplus While I could just write a new function to do this for me, I want to know if this problem can be resolved by including an extra library I don't have, or if there is some difference I'm not seeing when going from visual studio on windows to g++ compiler on linux that can be fixed. hovering over description.begin and description.end in vs code shows this error: no suitable conversion function from "__gnu_cxx::__normal_iterator<char *, std::__cxx11::basic_string<char, std::char_traits, std::allocator>>" to "const char *" existsC/C++(413) I have been tackling this problem for a few days so any help would be greatly appreciated! Edit: Since this may be important the libraries I used are the following: #include<iostream> #include <string> #include <fstream> #include <sstream> #include <cstdlib>//randomizer library #include <time.h>
The problem is simple. You need to include the header <algorithm> #include <algorithm> Otherwise the compiler finds the C function remove int remove(const char *filename); declared in the header <cstdio> because (the C++ 14 Standard, 27.4 Standard iostream objects) 1 The header declares objects that associate objects with the standard C streams provided for by the functions declared in <cstdio> (27.9.2), and includes all the headers necessary to use these objects.
73,929,668
73,929,742
Makefile not doing what I want - Compiling same thing twice
CXX := g++ CXX_FLAGS := -std=c++17 SRC_DIR := ./src LIB_DIR := $(SRC_DIR)/lib OBJ_DIR := $(SRC_DIR)/obj BIN_DIR := $(SRC_DIR)/bin BIN_DEBUG := $(BIN_DIR)/Test-debug BIN_RELEASE := $(BIN_DIR)/Test SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp) LIB_FILES := $(wildcard $(LIB_DIR)/*.cpp) OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES)) $(patsubst $(LIB_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(LIB_FILES)) $(BIN_RELEASE): $(OBJ_FILES) $(CXX) $(CXX_FLAGS) -o $@ $^ $(OBJ_FILES): $(SRC_FILES) $(LIB_FILES) $(CXX) $(CXX_FLAGS) -c -o $@ $< clean: rm ./src/obj/*.o rm ./bin/* run: $(BIN_RELEASE) This is my Makefile and it is doing the same g++ -c command in a row and then failing in the linking because it tries to link the a file to it self. Or can someone say how you debug a Makefile.
This is wrong: $(OBJ_FILES): $(SRC_FILES) $(LIB_FILES) $(CXX) $(CXX_FLAGS) -c -o $@ $< Say you have src/foo.cpp and src/bar.cpp in SRC_FILES. Now OBJ_FILES is src/obj/foo.o and src/obj/bar.o. Now the above rule expands like this: src/obj/foo.o src/obj/bar.o: src/foo.cpp src/bar.cpp $(CXX) $(CXX_FLAGS) -c -o $@ $< It's not the case that make will intuit what you want to do here and match up each object file with the source file, or something like that. The above means exactly the same thing as if you'd written these rules: src/obj/foo.o: src/foo.cpp src/bar.cpp $(CXX) $(CXX_FLAGS) -c -o $@ $< src/obj/bar.o: src/foo.cpp src/bar.cpp $(CXX) $(CXX_FLAGS) -c -o $@ $< Now you can see why every compile line compiles the same source file: the $< variable expands to the first prerequisite, and for every object file the first prerequisite is always the same (here, src/foo.cpp). You need to use a pattern rule here, telling make how to build one single file. And since you're building things in two different ways, you actually need two pattern rules. $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(CXX) $(CXX_FLAGS) -c -o $@ $< $(OBJ_DIR)/%.o: $(LIB_DIR)/%.cpp $(CXX) $(CXX_FLAGS) -c -o $@ $<
73,930,461
73,930,520
How to do a template specialization with multiple arguments (when the type of one of them is known)
Here's the template for a class template <typename T, unsigned int size> class Foo { T myarray[size]; //other code (doesn't matter for the example) } and I want to do a template specialization for it. For example, I have defined class Bar. So I want to make a specialization for class Bar, but I want to keep unsigned int size. How do I do that? template <> class Foo<Bar, unsigned int> { //throws error "type name not allowed" for unsigned int Bar myarray[size]; //other code }
This is called partial template specialization: template<unsigned int size> class Foo<Bar, size> { Bar myarray[size]; };
73,931,285
73,931,592
Is it possible to pass a struct pointer to an int argument of a function?
I am working on the Nachos Operating System as part of my coursework. While modifying the codebase of the OS, I encountered the following comment for a member function that allows you to run a function inside a newly forked thread (in this OS, processes are called threads - don't ask me why - refer to the official documentation). What I am most interested in is the docstring above the function. I am particularly interested in the section NOTE of the comment. I am not entirely sure what is going on here. How can a struct be passed to the Fork function, and how should we write func if it's supposed to use multiple arguments through a struct? Can someone explain this? //---------------------------------------------------------------------- // Thread::Fork // Invoke (*func)(arg), allowing caller and callee to execute // concurrently. // // NOTE: although our definition allows only a single integer argument // to be passed to the procedure, it is possible to pass multiple // arguments by making them fields of a structure, and passing a pointer // to the structure as "arg". // // Implemented as the following steps: // 1. Allocate a stack // 2. Initialize the stack so that a call to SWITCH will // cause it to run the procedure // 3. Put the thread on the ready queue // // "func" is the procedure to run concurrently. // "arg" is a single argument to be passed to the procedure. //---------------------------------------------------------------------- typedef void (*VoidFunctionPtr)(int arg); void Thread::Fork(VoidFunctionPtr func, int arg) { // run the function 'func' in side the forked thread using the argument // 'arg' as its input - look at VoidFunctionPtr type declaration above } I have one question that is related to my question on StackOverflow. I shall link it here. But, I am not completely sure if I understand it. Thanks in advance! PS: Complete source code is linked here: code, thread.h, thread.cc Edit: I understand that using the standard library thread and other standard library implementations is very safe and helpful, but as part of the coursework, I am not allowed to do this. In any case, I want to understand what the authors of this codebase are trying to say.
I want to understand what the authors of this codebase are trying to say.” They are saying, if you want to pass more data than an int, put it into a structure of your own design, say some struct foo x, and pass (int) &x to Thread::Fork. Implicit in the fact they are instructing you to do this is that the Nachos operating system is supported only for platforms on which such conversions preserve the necessary address information of the pointer and support its conversion back to a pointer to the structure type. For example, you could define struct foo this way: struct foo { int a; float b; }; and define func this way: void func(int arg) { struct foo *p = (struct foo *) arg; printf("a is %d.\n", p->a); printf("b is %g.\n", p->b); }
73,931,712
73,931,734
what is for (; e > 0; e >>= 1)?
Can anyone explain to me what's happening in line number 4, and how to understand these types of loops in future. I was solving this problem. I have used basic approaches like pow(2,n) and (1<<n), but it overflows. Then I got this solution, but I'm unable to understand that fourth line. I know how to use for() loops in C++, but I'm a bit confused because of starting, i.e. nothing is there i.e. for(; e > 0; e >>= 1). long long modpow(long long b, int e) { long long ans = 1; for (; e > 0; e >>= 1) { if (e & 1) ans = (ans * b) % mod; b = (b * b) % mod; } return ans; }
The for loop has 3 components: for (a; b; c) { } a runs at the start. The loop will break when b is no longer true, and after each iteration c is executed.
73,931,831
74,024,993
How to get the default, max, min value of Video Proc Amp/Camera Control parameters from UVC camera?
I want to get the default, max, and min values of control parameters from UVC camera like the picture. I try to get the default value with the below function. However, it only gets the current value of XU control and I cannot get the default values of XU control or any value of Video Proc Amp/Camera Control like the above picture. //Function to set/get parameters of UVC extension unit HRESULT SetGetExtensionUnit(GUID xuGuid, DWORD dwExtensionNode, ULONG xuPropertyId, ULONG flags, void* data, int len, ULONG* readCount) { GUID pNodeType; IUnknown* unKnown; IKsControl* ks_control = NULL; IKsTopologyInfo* pKsTopologyInfo = NULL; KSP_NODE kspNode; HRESULT hr = pVideoSource->QueryInterface(__uuidof(IKsTopologyInfo), (void**)&pKsTopologyInfo); CHECK_HR_RESULT(hr, "IMFMediaSource::QueryInterface(IKsTopologyInfo)"); hr = pKsTopologyInfo->get_NodeType(dwExtensionNode, &pNodeType); CHECK_HR_RESULT(hr, "IKsTopologyInfo->get_NodeType(...)"); hr = pKsTopologyInfo->CreateNodeInstance(dwExtensionNode, IID_IUnknown, (LPVOID*)&unKnown); CHECK_HR_RESULT(hr, "ks_topology_info->CreateNodeInstance(...)"); hr = unKnown->QueryInterface(__uuidof(IKsControl), (void**)&ks_control); CHECK_HR_RESULT(hr, "ks_topology_info->QueryInterface(...)"); kspNode.Property.Set = xuGuid; // XU GUID kspNode.NodeId = (ULONG)dwExtensionNode; // XU Node ID kspNode.Property.Id = xuPropertyId; // XU control ID kspNode.Property.Flags = flags; // Set/Get request hr = ks_control->KsProperty((PKSPROPERTY)&kspNode, sizeof(kspNode), (PVOID)data, len, readCount); CHECK_HR_RESULT(hr, "ks_control->KsProperty(...)"); done: SafeRelease(&ks_control); return hr; } int main(void) { ... SetGetExtensionUnit(xuGuidUVC, 2, 1, KSPROPERTY_TYPE_GET | KSPROPERTY_TYPE_TOPOLOGY, (void*)data, 1, &readCount) // XU_FUNC1 Get Value Pass SetGetExtensionUnit(xuGuidUVC, 2, 1, KSPROPERTY_TYPE_DEFAULTVALUES | KSPROPERTY_TYPE_TOPOLOGY, (void*)data, 1, &readCount); // XU_FUNC1 Get Value FAIL SetGetExtensionUnit(xuGuidUVC, 1, 2, KSPROPERTY_TYPE_GET | KSPROPERTY_TYPE_TOPOLOGY, (void*)data, 2, &readCount); // BRIGHTNESS Get Value FAIL ... } How could I get the default value but the current value from XU control? I think I cannot get the parameters of Video Proc Amp/Camera Control because I set the XU GUID but the correct GUID. How could I get the correct GUID and get the default, max, min values from UVC cameras?
I found the solution to my question. I use IAMVideoProcAmp and IAMVideoProcAmp to realize this function. HRESULT hr; IAMVideoProcAmp* procAmp = NULL; IAMCameraControl* control = NULL; ... hr = pVideoSource->QueryInterface(IID_PPV_ARGS(&procAmp)); if (SUCCEEDED(hr)) { hr = procAmp->GetRange(prop, &min, &max, &step, &def, &caps); procAmp->Release(); return hr; } ... hr = pVideoSource->QueryInterface(IID_PPV_ARGS(&control)); if (SUCCEEDED(hr)) { hr = control->GetRange(prop, &min, &max, &step, &def, &caps); control->Release(); return hr; }
73,932,381
73,957,603
" /bin/sh: 1: Syntax error: "(" unexpected " error while building code for raspberry pi pico
I am on Ubuntu. I am trying to build a simple project that I know worked! (I already made it work) I don't think I changed something to it but it has been three days and I cannot find a way to make it build again. I use a library named pico-DMX, whenever I don't add it to my project with "include" in cmake, than the make starts building. Otherwise, if I include the library in the cmake code, cmake .. command process and generate normally but the build ctrying to build a simple project that I know workedrashes instantaneously. I cannot seem to understand where it comes from. This is the error message: PICO_SDK_PATH is /home/andrew/pico/pico-sdk PICO platform is rp2040. Build type is Release PICO target board is pico. Using board configuration from /home/andrew/pico/pico-sdk/src/boards/include/boards/pico.h TinyUSB available at /home/andrew/pico/pico-sdk/lib/tinyusb/src/portable/raspberrypi/rp2040; enabling build support for USB. cyw43-driver available at /home/andrew/pico/pico-sdk/lib/cyw43-driver lwIP available at /home/andrew/pico/pico-sdk/lib/lwip -- Configuring done -- Generating done -- Build files have been written to: /home/andrew/pico/serial_pico (copy)/build Scanning dependencies of target bs2_default [ 1%] Building ASM object pico-sdk/src/rp2_common/boot_stage2/CMakeFiles/bs2_default.dir/compile_time_choice.S.obj [ 2%] Linking ASM executable bs2_default.elf /bin/sh: 1: Syntax error: "(" unexpected make[2]: *** [pico-sdk/src/rp2_common/boot_stage2/CMakeFiles/bs2_default.dir/build.make:98: pico-sdk/src/rp2_common/boot_stage2/bs2_default.elf] Error 2 make[2]: *** Deleting file 'pico-sdk/src/rp2_common/boot_stage2/bs2_default.elf' make[1]: *** [CMakeFiles/Makefile2:1493: pico-sdk/src/rp2_common/boot_stage2/CMakeFiles/bs2_default.dir/all] Error 2 make: *** [Makefile:91: all] Error 2 This is my main cmake files: cmake_minimum_required(VERSION 3.13) include($ENV{PICO_SDK_PATH}/pico_sdk_init.cmake) project(usb_control C CXX ASM) set(CMAKE_CXX_STANDARD 17) pico_sdk_init() include($ENV{HOME}/pico/libraries/lib/Pico-DMX/interfaceLibForPicoSDK.cmake) add_executable(usb_control main.cpp ) target_link_libraries(usb_control picodmx pico_stdlib hardware_pio hardware_dma) pico_enable_stdio_usb(usb_control 1) pico_enable_stdio_uart(usb_control 0) pico_add_extra_outputs(usb_control) The previous cmake file include $ENV{HOME}/pico/libraries/lib/Pico-DMX/interfaceLibForPicoSDK.cmake which contains : ## Include this file if you want to use the Pico-DMX library ## in YOUR (Pico-C-SDK-based) project. cmake_minimum_required(VERSION 3.12) # Define the Pico-DMX library add_library(picodmx INTERFACE) target_sources(picodmx INTERFACE ${CMAKE_CURRENT_LIST_DIR}/src/DmxInput.cpp ${CMAKE_CURRENT_LIST_DIR}/src/DmxOutput.cpp ) pico_generate_pio_header(picodmx ${CMAKE_CURRENT_LIST_DIR}/extras/DmxInput.pio ) pico_generate_pio_header(picodmx ${CMAKE_CURRENT_LIST_DIR}/extras/DmxOutput.pio ) target_include_directories(picodmx INTERFACE ${CMAKE_CURRENT_LIST_DIR}/src ) Again, I know there are no mistakes in the C++ code, it worked! It started to bug and wouldn't work again when I played with the Cmake to include directly the library dependencies of pico-dmx in its cmake file. If you have any questions feel free to ask, I'll answer quickly. In advance thank you for your help
As mentioned in the comments, the cause is the name of your directory. In order to accurately explain why it happens, I reproduced your situation myself. I created a dummy project under "/tmp/test checkout (copy)" and built using CMake: cd "/tmp/test checkout (copy)/build/pico-sdk/src/rp2_common/boot_stage2" && \ arm-none-eabi-objdump -h /tmp/test\ checkout\ (copy)/build/pico-sdk/src/rp2_common/boot_stage2/bs2_default.elf >bs2_default.dis Note that the spaces in the full filename are correctly escaped with a backslash, but the parentheses are not. This confuses the shell. I raised this issue on the Pico SDK. Until it is fixed, people should steer clear of using special characters in their directory structures. This is a good recommendation in general as it avoids situations like these.
73,932,857
73,932,892
C++ Exception codes vs classes
I am developing a header-only C++20 library, and now I need to add exception classes. And I have two choices: One base class and many subclasses class library_error : public std::exception { // ... other work }; class parse_error : public library_error { // ... }; class playing_error : public library_error { // ... }; class bad_attr : public library_error { // ... }; // ... One exception class based on error codec, a errc and a category class library_error : public std::exception { // ... public: const std::error_code& code() const noexcept; }; enum class library_errc { parse_error = 0xbadbad, playing_error = 0x9ood9ood, bad_attr = 0x123456, // ... }; class library_erorr_category : public std::error_category { // ... }; This library has a lot of detailed exception types. Which is better? Or is there any better solution?
Likely, an exception is not only thrown blank, but there are arguments to it. E.g. the file missing, the device on which the playing error occurred. You'd likely expect the exception handler to be able to process these. Therefore, I'd strongly suggest not to go around the type system and have an exception type hierarchy.
73,933,905
73,933,979
C++ template defining number of parameters of function
Lets say i have a class looking like this template<int n> class A{ array<size_t, n> sizes; //... public: template <int k> A<k> reshape(array<size_t, k> new_sizes){ return A<k>(new_sizes): } }; it works but the parameter new_sizes is syntatically suboptimal, since i have to call it like that: foo.reshape(array<size_t, 3>{1,2,3}); This does not work: foo.reshape({1,2,3}); Is there a way to either define a initializer_list with compile time size (so i could use it instead of the array) OR (even better) a way to define the size of a variadic parameter, so i could write something like foo.reshape(1,2,3);
OR (even better) a way to define the size of a variadic parameter, so i could write something like foo.reshape(1,2,3); You could take the sizeof... a parameter pack: template <size_t N> class A { std::array<size_t, N> sizes; public: A() = default; template <class... Args> A(Args&&... ss) : sizes{static_cast<size_t>(ss)...} {} template <class... Args> A<sizeof...(Args)> reshape(Args&&... new_sizes) { // ^^^^^^^^^^^^^^^ return A<sizeof...(Args)>(static_cast<size_t>(new_sizes)...); } }; // deduction guide: template <class... Args> A(Args&&...) -> A<sizeof...(Args)>; Demo
73,934,455
73,934,635
friend function is not a friend of all template instances?
In the following example I try to access the private member function subscribe() from a templated class type from within its friend function. However it appears that the friend function is only befriended in one instantiation of the class and not the other, hence yielding a "private within this context"-error. Check out the following: Demo #include <cstdio> template <typename T> class my_class { template <typename... Ts> friend auto observe(my_class<Ts>... args) { ([&]{ args.subscribe(); }(), ...); } void subscribe() { printf("subscribed!\n"); } }; int main() { my_class<int> a{}; my_class<bool> b{}; observe(a,b); } Error: <source>:19:20: required from here <source>:7:17: error: redefinition of 'template<class ... Ts> auto observe(my_class<Ts>...)' 7 | friend auto observe(my_class<Ts>... args) { | ^~~~~~~ <source>:7:17: note: 'template<class ... Ts> auto observe(my_class<Ts>...)' previously declared here <source>: In instantiation of 'auto observe(my_class<Ts>...) [with Ts = {int, bool}; T = int]': <source>:20:12: required from here <source>:8:29: error: 'void my_class<T>::subscribe() [with T = bool]' is private within this context 8 | ([&]{ args.subscribe(); }(), ...); | ~~~~~~~~~~~~~~^~ <source>:11:10: note: declared private here 11 | void subscribe() { | ^~~~~~~~~ Is this actually correct by the compiler?
Yes, this is correct. my_class<int> and my_class<bool> are separate classes, and everything inside them will get defined separately for each instantiation of the template. Normally this is fine, because the stuff inside the classes is class members, so i.e. my_class<int>::subscribe and my_class<bool>::subscribe are different functions. But observe is not a class member, so the fact that it gets defined by both my_class<int> and my_class<bool> is a violation of the One Definition Rule. What you need to do is move the definition of observe outside of my_class so that it only gets defined once: #include <cstdio> template <typename T> class my_class { public: template <typename... Ts> friend auto observe(my_class<Ts>... args); void subscribe() { printf("subscribed!\n"); } }; template <typename... Ts> auto observe(my_class<Ts>... args) { ([&]{ args.subscribe(); }(), ...); } int main() { my_class<int> a{}; my_class<bool> b{}; observe(a,b); } Demo
73,934,596
73,934,825
Idiomatic template parameter pack wrapper for template parameter pack deduction disambiguation
My initial goal is to disambiguate the following: template<typename... T, typename... U> void foo(){} In that case, foo< <a_sequence_of_types> >() always results in T = <a_sequence_of_types> and U = <empty_parameter_pack>. A classic solution is to pack T... and U... in std::tuple<T...> and std::tuple<U...> respectively and use these types as default arguments in foo. template<typename... T, typename... U> void foo(std::tuple<T...>, std::tuple<U...>){} Problems arise if any of the involved template parameters is not default constructible as it is becomes impossible to bind the dummy parameters of foo in that case. Then I started looking for a standard, idiomatic template parameter pack wrapper without luck. A false hope was std::index_sequence_for that does not enable template parameter pack deduction as it is only a template alias for std::integer_sequence that erases its template type parameter pack. I ended up using my own wrapper template<typename... T> struct TypePack{}; template<typename... T, typename... U> void foo(TypePack<T...>, TypePack<U...>){} which is trivially constexpr default constructible and works like a charm in place of std::tuple. But it lacks the clarity that standard types provide when used in an idiomatic way. Is there any such more idiomatic way? NOTE: This is part of the implementation of my code base and is not visible from the end user. Please do not tackle that question under the angle of API design. I am more interested in self-documenting code at that point.
Problems arise if any of the involved template parameters is not default constructible as it is becomes impossible to bind the dummy parameters of foo in that case. You can pass std::type_identity<T> instead of T to tuple to pass type: foo(std::tuple<std::type_identity<int&>, std::type_identity<const float&>>{}, std::tuple<std::type_identity<void>>{}); Another possibility is to break foo in 2 parts: template <typename... Ts> struct foo_t { template <typename... Us> static void foo() {/*...*/} }; with usage similar to foo_t<int&, const float&>::foo<void>();
73,935,448
73,948,866
Installing and Linking to Apache Arrow inside Cmake
I'm trying to build and link-to apache-arrow v9.0.0 inside my cmake project using the following section in my CMakeLists.txt file. ExternalProject_Add(arrow URL "https://www.apache.org/dist/arrow/arrow-9.0.0/apache-arrow-9.0.0.tar.gz" SOURCE_SUBDIR cpp) message(STATUS "arrow source dir: ${arrow_SOURCE_DIR}") include_directories(${arrow_SOURCE_DIR}/cpp/src) The compilation complains that the apache-arrow headers are missing fatal error: 'arrow/array.h' file not found #include <arrow/array.h> ^~~~~~~~~~~~~~~ 1 error generated. supported by the fact that the output of message(STATUS "arrow source dir: ${arrow_SOURCE_DIR}") is empty -- arrow source dir: Another error seemingly related to the apache-arrow installation reported by cmake is that CMake Error at cmake_modules/ThirdpartyToolchain.cmake:267 (find_package): Could not find a configuration file for package "xsimd" that is compatible with requested version "8.1.0". The following configuration files were considered but not accepted: /opt/homebrew/lib/cmake/xsimd/xsimdConfig.cmake, version: 9.0.1 Call Stack (most recent call first): cmake_modules/ThirdpartyToolchain.cmake:2245 (resolve_dependency) CMakeLists.txt:575 (include) Of course, the traditional approach of installing apache-arrow externally with say brew install apache-arrow and using find_package works well enough, but I'd like something more cross-platform. One of the arrow devs had provided a link on how to properly use include_directories with ExternalProject_Add for an earlier question, but I guess that example is now outdated. What's the recommended way of installing and then linking-to apache-arrow inside a cmake project using ExternalProject_Add? Edit: Minimal Example CMakeLists.txt cmake_minimum_required(VERSION 3.24) project(arrow_cmake) set(CMAKE_CXX_STANDARD 23) include(ExternalProject) ExternalProject_Add(Arrow URL "https://www.apache.org/dist/arrow/arrow-9.0.0/apache-arrow-9.0.0.tar.gz" SOURCE_SUBDIR cpp CMAKE_ARGS "-Dxsimd_SOURCE=BUNDLED" ) add_executable(${PROJECT_NAME} main.cpp) target_link_libraries(${PROJECT_NAME} arrow_shared) main.cpp #include <iostream> #include <arrow/array.h> // not found! int main() { std::cout << "Hello, World!" << std::endl; return 0; }
Building arrow from sources in cmake took quite some doing. It's heavily influenced by this link. cmake/arrow.cmake # Build the Arrow C++ libraries. function(build_arrow) set(one_value_args) set(multi_value_args) cmake_parse_arguments(ARG "${options}" "${one_value_args}" "${multi_value_args}" ${ARGN}) if (ARG_UNPARSED_ARGUMENTS) message(SEND_ERROR "Error: unrecognized arguments: ${ARG_UNPARSED_ARGUMENTS}") endif () # If Arrow needs to be built, the default location will be within the build tree. set(ARROW_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/arrow_ep-prefix") set(ARROW_SHARED_LIBRARY_DIR "${ARROW_PREFIX}/lib") set(ARROW_SHARED_LIB_FILENAME "${CMAKE_SHARED_LIBRARY_PREFIX}arrow${CMAKE_SHARED_LIBRARY_SUFFIX}") set(ARROW_SHARED_LIB "${ARROW_SHARED_LIBRARY_DIR}/${ARROW_SHARED_LIB_FILENAME}") set(PARQUET_SHARED_LIB_FILENAME "${CMAKE_SHARED_LIBRARY_PREFIX}parquet${CMAKE_SHARED_LIBRARY_SUFFIX}") set(PARQUET_SHARED_LIB "${ARROW_SHARED_LIBRARY_DIR}/${PARQUET_SHARED_LIB_FILENAME}") set(ARROW_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/arrow_ep-build") set(ARROW_CMAKE_ARGS "-DCMAKE_INSTALL_PREFIX=${ARROW_PREFIX}" "-DCMAKE_INSTALL_LIBDIR=lib" "-Dxsimd_SOURCE=BUNDLED" "-DARROW_BUILD_STATIC=OFF" "-DARROW_PARQUET=ON" "-DARROW_WITH_UTF8PROC=OFF" "-DARROW_WITH_RE2=OFF" "-DARROW_FILESYSTEM=ON" "-DARROW_CSV=ON" "-DARROW_PYTHON=ON") set(ARROW_INCLUDE_DIR "${ARROW_PREFIX}/include") set(ARROW_BUILD_BYPRODUCTS "${ARROW_SHARED_LIB}" "${PARQUET_SHARED_LIB}") include(ExternalProject) externalproject_add(arrow_ep URL https://github.com/apache/arrow/archive/refs/tags/apache-arrow-9.0.0.tar.gz SOURCE_SUBDIR cpp BINARY_DIR "${ARROW_BINARY_DIR}" CMAKE_ARGS "${ARROW_CMAKE_ARGS}" BUILD_BYPRODUCTS "${ARROW_BUILD_BYPRODUCTS}") set(ARROW_LIBRARY_TARGET arrow_shared) set(PARQUET_LIBRARY_TARGET parquet_shared) file(MAKE_DIRECTORY "${ARROW_INCLUDE_DIR}") add_library(${ARROW_LIBRARY_TARGET} SHARED IMPORTED) add_library(${PARQUET_LIBRARY_TARGET} SHARED IMPORTED) set_target_properties(${ARROW_LIBRARY_TARGET} PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${ARROW_INCLUDE_DIR} IMPORTED_LOCATION ${ARROW_SHARED_LIB}) set_target_properties(${PARQUET_LIBRARY_TARGET} PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${ARROW_INCLUDE_DIR} IMPORTED_LOCATION ${PARQUET_SHARED_LIB}) add_dependencies(${ARROW_LIBRARY_TARGET} arrow_ep) endfunction() Use it in your CMakeLists.txt file as ... set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake) include(arrow) build_arrow()
73,935,536
73,936,155
Syntax for std::bit_cast to an array
#include <bit> #include <array> struct A { int a[100]; }; struct B { short b[200]; }; void test(const A &in) { const auto x = std::bit_cast<short[200]>(in); // error: no matching function for call to 'bit_cast<short int [200]>(const A&) const auto y = std::bit_cast<B>(in); // OK const auto z = std::bit_cast<std::array<short, 200>>(in); // OK } The initialization of x is not working, I am curious if there is a syntax to std::bit_cast to an array without extra struct, std::array, memcpy or similar helper functions. Thanks.
Not even std::bit_cast can return an array, so wrapping in a class (perhaps std::array) is the best you can do.
73,935,618
73,936,608
Change background color with OpenGL
The Qt OpenGL Window Example shows a colored triangle. The colors, RGB corners, are set with: static const GLfloat colors[] = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }; How do I change the black background to another color?
You set the clear color with use of glClearColor function: C Specification void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); Parameters red, green, blue, alpha Specify the red, green, blue, and alpha values used when the color buffers are cleared. The initial values are all 0. Description glClearColor specifies the red, green, blue, and alpha values used by glClear to clear the color buffers. Values specified by glClearColor are clamped to the range [0,1]. As documentation suggests, the clear color is used when you clear the color buffer via glClear function (by specifying GL_COLOR_BUFFER_BIT argument): glClearColor(0, 1, 0, 1); // sets green color glClear(GL_COLOR_BUFFER_BIT);
73,935,704
73,935,990
How to declare a <vector> object and use push_back inside a class?
I'm trying to build a class named "Tombola" which should contain as private variable an empty vector. This should be filled at runtime through the class member Tombola.estrai(), which generates a random number and insert it inside the vector named "order" by the method order.push_back(number). This is the class definition in the tombola.h header: #ifndef TOMBOLA_H #define TOMBOLA_H #include <cstdlib> #include <vector> using namespace std; class Tombola { private: bool on_off[90]; int tabellone[9][10]; int x_max = 9; int y_max = 10; vector<int> order; public: Tombola(); ~Tombola(); void nuovo(); int estrai(); bool completato(); void stampa(); void stampa_tab(); }; #endif And this is the implementation of constructor/destructor and Tombola::estrai() inside tombola.cc: #include "tombola.h" #include <cstdlib> #include <cmath> #include <ctime> #include <vector> #include <iostream> using namespace std; Tombola::Tombola () { vector<int> ord; order = ord; int z=1; for(int i=0;i<90;i++) { on_off[i] = false; } for(int j=0;j<=x_max;j++) { for (int k=0;k<=y_max;k++) { tabellone[j][k] = z; z++; } } } Tombola::~Tombola() { cout << "Tombola is destroyed" << endl; } int Tombola::estrai() { srand(time(NULL)); int estrazione = int(ceil(rand()/double(RAND_MAX)*90)); on_off[estrazione]==true; order.push_back(estrazione); return order.back(); } and this is the call to the method in the main.cpp file: #include "tombola.h" #include <cstdlib> #include <iostream> #include <vector> #include <ctime> using namespace std; int main () { Tombola natale; cout << natale.estrai(); } When I compile the program everything goes fine, but when I execute the main I get a segmentation fault error which seems to be due to some sort of allocation error when trying to store the item inside the order vector, as reported by the debugger. Could someone explain to me how to solve the error and why the error occours? Thank you.
The reason of segmentation fault is in the constructor. You have to change for(int j=0;j<=x_max;j++) to for(int j=0;j<x_max;j++) in order not to cross the bounds of the array. for(int j=0;j<x_max;j++) { for (int k=0;k<y_max;k++) { tabellone[j][k] = z; z++; } } However, there are also some minor issues in the code that are worth being mentioned declaring default-initialized ord vector and assigning it to order is pointless because order is already default-initialized.(See member initializer list for more information). using namespace std; in a header file is a terrible idea, because if you had a large codebase, and had multiple source files where you want to include that header, everywhere the using statement will be applied, which probably is not desired.
73,935,778
73,935,901
C++ bitset strange value
#include <bitset> #include <assert.h> #include <stdio.h> using namespace std; int main() { bitset<128> bs(42); bs[11]=0; bs[12]=1; assert(bs[12]==1); printf("bs[11]=%d\n", bs[11]); printf("bs[12]=%d\n", bs[12]); return 0; } console output: Why can't I simply get 0 or 1 as output ?
printf with %d is for integer values, whereas std::bitset::operator[] returns a std::bitset::reference. You can use std::cout from <iostream> header (which is anyway a more c++ "way" to print to the console): #include <bitset> #include <assert.h> #include <iostream> int main() { std::bitset<128> bs(42); bs[11] = 0; bs[12] = 1; assert(bs[12] == 1); std::cout << "bs[11]=" << bs[11] << std::endl; std::cout << "bs[12]=" << bs[12] << std::endl; return 0; } Output: bs[11]=0 bs[12]=1 A side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.
73,935,913
73,936,630
nested vector with polymorphic_allocator cannot be constructed via emplace_back
The following code: std::pmr::vector<std::pmr::vector<int>> outer_vec(std::pmr::get_default_resource()); outer_vec.emplace_back(std::pmr::get_default_resource()); fails with quite inconceivable error message ending with static assertion failed: construction with an allocator must be possible if uses_allocator is true The vector can clearly be constructed with an argument of std::pmr::get_default_resource(), such as: std::pmr::vector<std::pmr::vector<int>> outer_vec(std::pmr::get_default_resource()); std::pmr::vector<int> inner_vec(std::pmr::get_default_resource()); outer_vec.push_back(std::move(inner_vec)); And std::pmr::vector can use emplace_back to construct an element, such as: std::pmr::vector<std::vector<int>> outer_vec(std::pmr::get_default_resource()); outer_vec.emplace_back(); Why does the combination of both fails? What static_assert is failing? Note that if the outer vector is not pmr, it works: std::vector<std::pmr::vector<int>> vec; vec.emplace_back(std::pmr::get_default_resource());
std::pmr::polymorphic_allocator uses uses-allocator construction if supported by the constructed type. std::vector does support uses-allocator construction and the allocator type of the inner std::vector is compatible with that of the outer one. In consequence uses-allocator construction will be used by the outer vector. This means, whenever the vector constructs a new element it will automatically pass its own allocator as another argument to the constructor of the element. (Specifically get_allocator()->resource() is passed at the end of the argument list in this case.) You are trying to pass an allocator manually to emplace_back, so that in effect with the above two allocators will be passed to the inner vector's construction, resulting in failure. So, what you really want is just outer_vec.emplace_back();. It will propagate the outer vector's allocator to the inner vector. Note that outer_vec.push_back(std::move(inner_vec)); will do the same. It will also propagate the outer allocator to the new "move"-constructed inner vector, resulting in moving all elements to a new allocation if necessary. It won't use the original allocation of inner_vec if its allocator compares unequal to outer_vec's allocator.
73,936,188
73,936,418
how are integers stored in stack
main.cpp #include <iostream> int main(){ int x = 1, j = 2; int *p = &j; // std::cout << &x << std::endl; std::cout << *(p-1) << std::endl; } I get different output with the line std::cout << &x << std::endl; commented out and uncommented. Are integers stored in consecutive locations in stack? values: commented: 0 (probably garbage value) uncommented: 1
You didn't use x, so the compiler didn't store it anywhere. Remember, when you write C++ you aren't writing a program. You're describing the behavior of the program you want your compiler to write for you. The compiler can write any program as long as its behavior matches the behavior you described. If you declare a variable whose initialization has no observable side-effects and you never use it anywhere then you haven't described any behavior. The compiler doesn't need to generate any code to deal with that, so it will often omit variables like that entirely. Note that in this case the instructions you gave don't have any defined behavior, so the compiler can write any program it wants. Attempting to offset a pointer outside the array it points to is undefined (where non-array variables are treated like arrays of one element), so p - 1 is not defined.
73,937,606
73,937,670
How do I convert a String into a char in C++
I want to convert a string that is inside a vector of strings (vector) into a char. The vector would look something like the following: lons = ["41", "23", "N", "2", "11" ,"E"]. I would like to extract the "N" and the "E" to convert them into a char. I have done the following: char lon_dir; lon_dir = (char)lons[lons.size()-1].c_str(); But I get the following error message: cast from 'const char*' to 'char' loses precision [-fpermissive] How do I fix that?
You cannot directly cast a c string (char* or const char*) to a char as it is a pointer. More precisely a pointer to an array of chars! So once you retrieve the right char* (or const char*) from your array lons it suffices to dereference said pointer, this will return the first character of that string char* str = "abc"; char a = *str; char b = *(str + 1); etc...
73,937,814
73,938,007
How to make a class static variable which depends on the complete class type a constexpr?
I have a class MyClass which has a static variable instance. The value of instance is a compile-time constant, but it depends on the complete type MyClass. Is there any way to make instance a constexpr? // memchunk.hpp #ifndef MEMCHUNK_HPP #define MEMCHUNK_HPP #include <new> #include <utility> enum class DestroyOption { Implicit, Explicit, }; // a wrapper for placement new template <class T, DestroyOption Opt = DestroyOption::Implicit> class MemChunk { alignas(T) char buf[sizeof(T)]; public: template <typename... Args> void construct(Args &&...args) { new (buf) T(std::forward<Args>(args)...); } void destroy() { get()->~T(); } constexpr T *get() { return reinterpret_cast<T *>(buf); } ~MemChunk() { if constexpr (Opt == DestroyOption::Implicit) destroy(); } }; #endif // MEMCHUNK_HPP // myclass.cpp #include "memchunk.hpp" // struct MyClass; // forward declaration // MemChunk<MyClass> obj; // error: incomplete type MyClass class MyClass { static const MyClass *instance; // better to be constexpr }; MemChunk<MyClass> obj; const MyClass *MyClass::instance = obj.get();
Use a function instead: class MyClass { static constexpr MyClass* instance(); }; MemChunk<MyClass> obj; constexpr MyClass* MyClass::instance() { return obj.get(); } However, this is pointless because obj.get() cannot be used in a constexpr context (because of the reinterpret_cast, as mentioned in the comments). Demo
73,937,862
73,937,940
How to increment the C++list's Iterator inside a for loop to iterate over specific pattern say for example each second element?
Usually in C++ one can iterate over each second element by doing so: for (int i = 0; i < 10; i = i + 2 ){ //do Somthing } and for a C++ list (from library list) one can iterate over each element like so: std::list<int> dY = {5,4,5,8,9,7,10,4}; std::list<int>::iterator iterdY; for (iterdY = dY.begin(); iterdY != dY.end(); iterdY++) { // do Something } Now my question is what should I write instead of iterdY++ to iterate over each second element ??
std::advance(iterdY, 2) But you can no longer use the comparison iterdY != dY.end() because if the list has an odd number of elements you will skip over the end iterator, and into the territory of undefined behavior. You must make sure that the list have an even number of elements first, if using iterators, or use some other way to keep track of the iterator not passing beyond the end. If your compiler supports C++23 you can use ranges and stride_view to skip over every second element in the container. See example here (using the earlier Ranges v3 library, which is the base for the C++20 standard library ranges). Using the original ranges v3 library with earlier C++ standards is possible as well.