question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
71,157,117
71,157,361
Qt How can I use DocumentsLocation
I am trying to develop an application with Qt. My problem is: I need to write and delete something in a text file. I am writing the text file as full path, the path on my computer. If the application runs on another computer, it will not find this path. I found out that I can use QStandardPaths::DocumentsLocation for its solution. But I couldn't figure out how to use it. Can you teach me or give an example?
You can get Documents location by below code: #include <QGuiApplication> #include <QDebug> #include <QStandardPaths> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); qDebug() << QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); return app.exec(); } This code prints current user's Documents Location. You can store this folder location in QString and then use it as you need to store your files. Reference: QStandardPaths::StandardLocation
71,157,159
71,157,385
Use arbitrary classes as parameter for parametrized tests in googletest
I have some repetive tests where the input of the tests needs to be created uniquely in a non-repetive way. Imagine 2 tests like this: struct ComplexInput{}; ComplexInput CreateA(); ComplexInput CreateB(); bool FunctionUnderTest(ComplexInput& input); TEST(TestCase, TestWithA) { auto input = CreateA(); auto ret = FunctionUnderTest(input); EXPECT_TRUE(ret); } TEST(TestCase, TestWithB) { auto input = CreateB(); auto ret = FunctionUnderTest(input); EXPECT_TRUE(ret); } Is there any way to parametrize the tests to specify the function which should be called e.g. with templates? The only solution I can think of is using an enum to specify the data and using a function which returns the correct data based on the enum type, but this feels like a hack: struct ComplexInput{}; ComplexInput CreateA(); ComplexInput CreateB(); bool FunctionUnderTest(ComplexInput& input); class enum InputChoice { A, B }; ComplexInput GetComplexInput(InputChoice c) { switch(c) { case A: return CreateA(); case B: return CreateB(); } } class ParamTest : public ::testing::TestWithParam<InputChoice>{}; TEST_P(ParamTest, Test) { InputChoice c = GetParam(); auto input = GetComplexInput(c); auto ret = FunctionUnderTest(input); EXPECT_TRUE(ret); } INSTANTIATE_TEST_CASE_P ( Tests, ParamTest, ::testing::Values ( InputChoice::A, InputChoice::B // maybe this could also be automated? ) ); Please keep in mind that this code is only to demonstrate the scenario and it could be that it does not compile.
You can store function pointers and pass them to parameterized tests, as long as they have the same type (i.e., same parameters and return type) See it online struct ComplexInput{}; ComplexInput CreateA(); ComplexInput CreateB(); bool FunctionUnderTest(ComplexInput& input); class ParamTest : public ::testing::TestWithParam<ComplexInput(*)()>{}; TEST_P(TestCase, TestWithA) { auto uutCreator = GetParam(); auto input = uutCreator(); auto ret = FunctionUnderTest(input); EXPECT_TRUE(ret); } INSTANTIATE_TEST_SUITE_P(MyParamTest, ParamTest, ::testing::Values(CreateA, CreateB)); If the functions do not have the same signature in reality, they you need to consider if you can use some wrappers to get them to the same signature or if it's better to just have separate (non-parameterized) tests. Important note: This will work for lambdas with empty capture list, free functions or static member functions. For lambdas that have a non-empty capture list you must use std::function<ComplexInput()> instead of ComplexInput(*)(). Non-static member functions will have a bit more involved syntax.
71,157,409
71,217,683
Error while trying to make Camera Calibration using Charuco Board (OpenCV, C++)
I'm trying to find distortion coeffitients using Charuco Board from the Aruco OpenCV library. I'm using Qt and OpenCV libraries compiled for Qt. First I've needed to do is to create the Charuco Board. I've done it using this: using namespace std; using namespace cv; using namespace cv::aruco; ... Ptr<Dictionary> dictionary = getPredefinedDictionary(DICT_6X6_250); Ptr<CharucoBoard> board = CharucoBoard::create(5, 7, 0.04f, 0.02f, dictionary); Ptr<DetectorParameters> params = DetectorParameters::create(); params->cornerRefinementMethod = CORNER_REFINE_NONE; After that I have found Markers and Charuco Corners with its IDs on photos using detectMarkers(...) and interpolateCornersCharuco(...) functions. I had 28 photos with the board or its parts. Operation result looks like this (from 5 to 24 allocated corners per each image): Allocated Charuco Corners After that I tried to find Camera Matrix and Distortion Coeffitients using this: Mat cameraMatrix, distCoeffs; vector<Mat> rVectors, tVectors; double repError = calibrateCameraCharuco(allCharucoCorners, allCharucoIds, board, imgSize, cameraMatrix, distCoeffs, rVectors, tVectors); allCharucoCorners and allCharucoIds are vectors of vectors with equal size, board configured like shown above, imgSize got using function cv::Size(loadedImg.cols, loadedImg.rows). The program always tries to execute this function, but can not do it. Every time I try I have the project crash without any critical messages. So maybe someone have an idea about what can be wrong?
The problem was in OpenCV library. Maybe it was badly compiled, or the problem is in the library itself. I have used OpenCV version 4.5.3 before. Then I compiled 4.5.4 version, and the program started to work well.
71,157,560
71,158,910
std::string class wrapped with cstring API (property proxy pattern)
I want to convert static data structures using cstrings in our legacy codebase to dynamic ones by using std::strings instead. The problem is that, right now, it is unfeasible to adapt all the functions in our codebase that use them. I proposed using a wrapper class (property proxy pattern) that exposes a cstring API using a std::string internally. This would allow the usage of cstring functions (strcpy, strlen, memset, etc.) and make the data structures backward-compatible. This is what I have so far: Original data structure: struct data { char property1[20]; char property2[20]; } New structure: struct data { CStringProperty property1; CStringProperty property2; } Wrapper class: class CStringProperty { public: CStringProperty(){} CStringProperty(std::string& value) : _value{value}{} CStringProperty(char* value) : _value{value}{} CStringProperty& operator=(std::string value) { _value = value; return *this; } CStringProperty& operator=(char* value) { std::string valueStr = value; return operator=(valueStr); } operator std::string() { return _value; } operator char*() { return &_value[0]; } char& operator[](int i) { return _value[i]; } std::string to_str() { return _value; } private: std::string _value; friend std::ostream& operator<<(std::ostream& os, CStringProperty& value); }; std::ostream& operator<<(std::ostream& os, CStringProperty& value) { return os << value.to_str(); } Tests int main() { CStringProperty a= "Hello"; std::cout << "Test 1: " << a << std::endl; // Works CStringProperty b; b = a; std::cout << "Test 2: " << b << std::endl; // Works CStringProperty c; char d[10] = "Hello"; c = d; std::cout << "Test 3: " << c << std::endl; // Works char* e = a; std::cout << "Test 4: " << e << std::endl; // Works CStringProperty f; std::cout << "Test 5: " << f << std::endl; // Works CStringProperty g = "Hello"; g[0] = 'X'; std::cout << "Test 6: " << g << std::endl; // Works CStringProperty h = "Hello"; std::cout << "Test 7: " << std::to_string(strlen(h)) << std::endl; // Works CStringProperty p = "hello"; strcpy(p,"bye"); std::cout << "Test 8.1: " << std::to_string(strlen(p)) << std::endl; // Works std::cout << "Test 8.2: " << p << std::endl; // Doesn't work CStringProperty q; strcpy(q,"bye"); std::cout << "Test 9.1: " << std::to_string(strlen(q)) << std::endl; // Works std::cout << "Test 9.2: " << q << std::endl; // Doesn't work return 0; } I'm aware of std::string::data() exposing the underlying cstring, but this returns a const char*, so it's obviously only meant for reading purposes. Using a const_cast I supose would be similar to what I'm doing above and leads to undefined behaviour. I would be extremely discouraged to know there's no way of doing this, since it would mean a truly tremendous refactoring effort, so I'm thankful for any help or ideas.
The reason why 9.2 and 8.2 do not work is because std::string has a size_ data member. strcpy function does not modify it. You can use friend functions (or regular functions) to workaround this issue. class CStringProperty { public: CStringProperty(){} CStringProperty(std::string const& value) : _value{value}{} CStringProperty(char const* value) : _value{value}{} CStringProperty& operator=(std::string value) { _value = value; return *this; } CStringProperty& operator=(char* value) { std::string valueStr = value; return operator=(valueStr); } operator std::string() { return _value; } operator char const*() { return _value.c_str(); } char& operator[](int i) { return _value[i]; } private: std::string _value; friend std::ostream& operator<<(std::ostream& os, CStringProperty const& value) { return os << value._value; } friend void strcpy(CStringProperty& value, char const* src) { value._value = src; } friend size_t strlen(CStringProperty const& value) { return value._value.size(); } }; The other issue is you do not use const where needed. And also you pass std::string by value, which could affect the performance.
71,157,598
71,157,803
Multiple failed attempts to open a text file in C++
I have been spending the past hour trying to figure out how to display a text document programmatically in c++. The following is the simple main.cpp code, in which I create a directory "Profiles", and another directory "TestProfile" inside. In Profiles/TestProfile I create a "TestFile" and write "Test data" into it. #include <iostream> #include <fstream> #include <sys/stat.h> #include "Profile.hpp" #include <stdlib.h> using namespace std; int main(int argc, const char * argv[]) { ofstream fs; mkdir("/Users/dario/Desktop/Profiles", S_IRWXU); mkdir("/Users/dario/Desktop/Profiles/TestProfile", S_IRWXU); fs.open("/Users/dario/Desktop/Profiles/TestProfile/TestFile"); fs << "Test data\n"; string path = "/Users/dario/Desktop/Profiles/TestProfile/TestFile"; system(path.c_str()); return 0; } Everything up until line 30 works as expected. The directories are there, and "TestFile" is present with data written. There are no errors present when compiling, but ./a.out gives me a permission denied darios-mbp:FMES dario$ g++ -std=c++2a main.cpp darios-mbp:FMES dario$ ./a.out sh: /Users/dario/Desktop/Profiles/TestProfile/TestFile: Permission denied I tried a few approaches. First, I checked the permissions of the text file using ls -l, it returned -rw-r--r--, so I used chmod 755. After that, the file permissions said -rwxr-xr-x. When running the same code, ./a.out returned no permission denied and it seems like it worked, but the text file was not opened. Secondly, after the first approach didn't work, I deleted the directories and ./a.out to recreate the original permission denied issue. I was getting permission denied as before, and this time I tried changing the ownership or the directory. sh: /Users/dario/Desktop/Profiles/TestProfile/TestFile: Permission denied darios-mbp:FMES dario$ chown -R $USER /Users/dario/Desktop/Profiles/TestProfile/TestFile darios-mbp: The command worked, but running the code still did nothing despite no errors. I tried chmod 755, but again no file was opened. On previous attempts to fix this issue, after changing the ownership the same way I just explained, I even had an error where it was trying to run the first word of the textfile as a command Line 1: Test: command not found Although I was not able to recreate that while writing this. Perhaps I am doing something completely wrong, but I looked as much as I could for solutions online before writing this post. None of them seemed to work. Perhaps my situation is unique in some way and someone here could help point me in the right direction. I apologize in advance if my post is in any way not to standard (if so, please let me know how I can improve questions for next time).h I am running the code on xcode EDIT Thanks to @Codo for the answer, the following edit did what I was looking for string path = "/Users/dario/Desktop/Profiles/TestProfile/TestFile"; string cmd = "open -a TextEdit "; system(cmd.c_str());
I understand that you want to open the created file with an appropriate application. Let's assume the file is /dir/file. To open a file from the command line / terminal, you would run: open /dir/file Or, if you want a specific applications: open -a TextEdit /dir/file Also see The macOS open Command. If you just run: /dir/file you would execute the file. That's probably not what you intended. And execution is only possible if the file meets certain criteria like execution rights and in the case of a shell script an appropriate header. In C++, the system() function executes a command that would be valid on the command line (in the terminal). Thus, to fix your program, change the line with system() to: string cmd = "open -a TextEdit "; cmd += path; system(cmd.c_str()); And for your next question: Paste code as text, not as image: Why not upload images of code/errors when asking a question?
71,157,686
71,157,971
Copy Constructors of classes instantiating derived classes
I have unsuccessfully been trying to create a copy constructor of a class that instantiates a derived class. Let's say I have the following pure virtual class: class AbstractBar{ public: virtual void printMe() = 0; }; Class Bar inherits from AbstractBar as follows: class Bar: public AbstractBar { std::string name_; public: explicit Bar(std::string name) : name_ {std::move(name)}{}; void printMe() override { std::cout << name_ << std::endl; } }; My class Foo now attempts to make use of polymorphism by declaring a pointer to type AbstractClass as follows: class Foo{ std::unique_ptr<AbstractBar> theBar_; public: explicit Foo(std::unique_ptr<Bar> bar){ theBar_ = std::move(bar); }; void printBar(){ theBar_->printMe(); } }; I do however want Foo to be copied so I add the following copy constructor: Foo(const Foo &other) { theBar_ = std::unique_ptr<AbstractBar>(); *theBar_ = *(other.theBar_); } And this is where it breaks. What I gather is that this may be a problem since theBar in the copy constructor thinks it is pointing to an AbstractBar but when I try to copy the object it points to, in the next line, I actually give it a derived Bar class. Is there a proper way to implement this copy constructor?
First off, std::unique_ptr<T> is indeed unique. Therefore you cannot expect two things to point to the same instance-of-whatever by copying them. That said, I think what you're trying to do is clone whatever the "thing" is that is held by that member unique_ptr to allow a deep copy of a Foo. If that is the case, you need a covariant clone. See below: #include <iostream> #include <string> #include <memory> struct AbstractBar { virtual ~AbstractBar() = default; virtual std::unique_ptr<AbstractBar> clone() = 0; virtual void printMe() = 0; }; class Bar : public AbstractBar { std::string name_; public: explicit Bar(std::string name) : name_{std::move(name)} {}; std::unique_ptr<AbstractBar> clone() override { return std::make_unique<Bar>(name_); } void printMe() override { std::cout << name_ << std::endl; } }; class Foo { std::unique_ptr<AbstractBar> theBar_; public: explicit Foo(std::unique_ptr<Bar> bar) : theBar_(std::move(bar)) { } Foo(const Foo &other) : theBar_(other.theBar_->clone()) { } void printBar() { theBar_->printMe(); } }; int main() { Foo foo(std::make_unique<Bar>("Some String")); Foo bar(foo); foo.printBar(); bar.printBar(); } Important: foo and bar will each have their own Bar instance via a unique pointer to the abstract base of Bar, namely AbstractBar. Hopefully that was the intent. This isn't the only way to do this, but it is probably the easiest to understand.
71,159,998
71,184,493
Guarantees on the Object lifetime of inline static Meyers singleton, with explicit placement in a section?
I have inherited some code that compiles fine under g++ 9 and 10, but gives a runtime error for both compilers when optimization is turned on (that is, compiling -O0 works, but compiling -Og gives a runtime error from the MMU.) The problem is that there is a Meyers singleton defined in an inline static method of a class, and that object seems to be optimized away. There is a complication that the static object in the method is declared with a section attribute (this is the g++ language extension for placing options in specific sections in the object file.) Here is a summary of the situation. File c.hpp namespace my_prod { class C { // C has a default c'tor public: static C& instance() { static C c __attribute__((section("MY_C_SECTION"))); return c; } void f(); }; } File c.cpp #include "c.hpp" using namespace my_prod; void C::f() { // implementation of f, doesn't use instance() } File p.hpp namespace my_prod { class P { public: static void g(); }; } Then file p.cpp #include "p.hpp" #include "c.hpp" using namespace my_prod; void P::g() { C::instance().f(); } The linker script includes: MEMORY { BIG_CHUNK (rw) : ORIGIN = <address>, LENGTH = <enormous> } SECTIONS { .my_space (NOLOAD) : { . = ALIGN(32); *(MY_C_SECTION) } > BIG_CHUNK } For both optimization levels, objdump -C -r -t p.o gives 00000000 w O MY_C_SECTION 00002220 my_prod::C::instance::c (ie, so not local, not global, but it is weak.) But objdump on the elf file shows that symbol in BIG_CHUNK when optimization is -O0, but missing when it is -Og. It may be relevant that the project defines the following switches:: -ffunction-sections -fdata-sections -Wl,--gc-sections although these switches are applied consistently for all builds. The solution was to move the definition of the my_prod::C::instance() method into c.cpp. The symbol is then locally defined and not weak anymore, and appears in the final elf irrespective of the optimization level. My question is, what are the rules of C++ that explain this behavior?
GCC uses COMDAT section groups when available to implement vague linkage. Despite being explicitly named as MY_C_SECTION, the compiler still emits a COMDAT group with _ZZN7my_prod1C8instanceEvE1c as the key symbol: .section MY_C_SECTION,"awG",@progbits,_ZZN7my_prod1C8instanceEvE1c,comdat I expect that your other uses of MY_C_SECTION are not part of a COMDAT group with the same signature symbol. This creates an ambiguous situation for section garbage collection by the link editor. Without optimization, the compiler emits a reference to the _ZZN7my_prod1C8instanceEvE1c signature symbol, and it happens that in this particular implementation of linker garbage collection, this is enough to retain the MY_C_SECTION section in the object file and the _ZZN7my_prod1C8instanceEvE1c symbol definition. With optimization, that reference is gone, and due to the ambiguity of the situation, the link editor discards the definition. Without an inline definition of my_prod::C::instance(), there is no vague linkage and COMDAT group involved, so the ambiguity does not arise, and the linker script works as expected. To address this while preserving the inline definition, it may be sufficient to use a unique section name instead of MY_C_SECTION and reference that in the linker script.
71,160,713
71,161,492
Delete last element from dynamic array in C++
I was making a std::vector like clone for a fun little project in C++, and I've come across the following problem: I'm trying to implement the method pop_back but for some reason, I can't get it to work. The class I'm using is called Array and is defined in ../d_arrays/d_array.h and ../d_arrays/d_array.cpp I have a main.cpp file in the root folder. Here is what I have so far: RootDir/d_arrays/d_array.h #include <iostream> using namespace std; class Array { public: Array(int len); void pop_back(); void print(); private: int* _array = NULL; int _len = 0; }; RootDir/d_arrays/d_array.cpp #include <iostream> #include "d_array.h" using namespace std; Array::Array(int len) { _array = new int[len]; _len = len; } void Array::pop_back() { _len--; // reduce length by 1 int* tmp = new int[_len]; // create temp copy for (int i = 0; i < _len; i++) { tmp[i] = _array[i]; } _array = tmp; delete[] tmp; } void Array::print() { for (int i = 0; i < _len; i++) { cout << _array[i] << " "; } cout << endl; } RootDir/main.cpp #include <iostream> #include "d_arrays/d_array.h" using namespace std; int main() { Array a = Array(10); cout << "Before: "; a.print(); a.pop_back(); cout << "After: "; a.print(); return 0; } Im using g++ -o main main.cpp d_arrays/d_array.cpp to compile my code and ./main to run it. whenever I run ./main I get the following output: Before: 0 0 0 0 0 0 0 0 0 0 After: 0 0 118968336 21854 0 0 0 0 0 What is happening here?
Your problem is here: delete[] tmp; Now: _array = tmp means: Point _array to the memory address that tmp is pointing to. Now, _array is pointing to &tmp (& means 'address of'), and then you delete tmp, which causes issues. Also resizing the entire array would be ok if the array is small. But it would not be ok if the array is big. For example, if the array contains millions of elements, resizing the array is going to take a long time. So you can just not resize the array, as _len is what handles the number of elements. So the new pop_back function can be as follows: void Array::pop_back() { _len--; // reduce length by 1 /* int* tmp = new int[_len]; // create temp copy for (int i = 0; i < _len; i++) { tmp[i] = _array[i]; } _array = tmp; delete[] tmp; */ } As you can see I've commented out all code except _len--; But if you really want to resize the array at some point, you can declare a separate function for that as such: void Array::shrink_to_fit() { int* tmp = new int[_len]; // create temp copy for (int i = 0; i < _len; i++) { tmp[i] = _array[i]; } delete[] _array; // Delete what _array is pointing to _array = tmp; // Point _array to the memory address that tmp is pointing to } But with this new function, don't forget to define shrink_to_fit() in your class definition. So the new class definition: class Array { public: Array(int len); void pop_back(); void print(); void shrink_to_fit(); private: int* _array = NULL; int _len = 0; };
71,160,909
71,161,071
Can you use a string(or c string) as a typename
I have a map loading function that takes input using ifstream from a file and creates objects from them. Here is what the file might look like: tree=50,100,"assets/tree.png" box=10,10,"assets/box.png" Which should create the objects tree and box and pass the values to their constructor. I already have the value part figured out, but I don't know how to take the string "tree" and create a tree object. Is it possible to take a string(or c string) and use it as a type name? Things I've tried: Passing the string as a template typename #include <string> struct A {}; template<typename T> T* createType() { T* type = new T() return T; } int main() { std::string tname = "A"; auto* type = createType<tname>; } Using the using keyword #include <string> template<std::string T> struct someType {} struct A {}; struct B {}; using someType<"A"> = A; using someType<"B"> = B; int main() { std::string tname1 = "A"; std::string tname2 = "B"; someType<tname1> typeA; someType<tname2> typeB; } Problems: I can't seem to find a clear answer about this but is seems like there are some problems with using a string as a template parameter. I don't know if it is ok to pass a variable as a template parameter I don't think that you can cast template types (from string to typename) Is there any way that either of these, or some other way might work to accomplish this? Or is this just not possible?
No. As far as I know, there is no provision in C++ for finding types from an in-language string of any kind. As for your other problems: A value template parameter must be constexpr: since C++11, you can use variables of some constexpr types as template parameters Apparently you can use a constexpr string_view template parameter in C++17, and a constexpr string template parameter in C++20 Regardless of these other answers, you still can't turn those strings into types. That kind of operation is typical of dynamic languages, but C++ is a statically typed, compiled language. And, while it is possible to design a static language that can do that kind of operation at compile time, that is not the path that C++ design has taken. I think it's reasonable to ask: why you want to do this in the first place? There is probably a better way to accomplish whatever prompted the question, but without further information it is hard to know how to help. Edit, in response to updated question: In order to read datastructures from a file, you will need do the string-to-type mapping yourself. Generally, you will have some "driver" object where you register types that you want to create from your file, which it will then use when reading from the file. The simplest way is to register each typename in association with a callback to construct the data. The most straightforward, object-oriented way to handle the resulting heterogeneous datastructures is to derive all their types from a common Readable base class. Registration is where you will provide the typename to be used in the file. If you don't feel like repeating the typename with every registration line, you can use macros to do that -- something like: #define REGISTER(type) (driver.register(#type, &(type)::construct)) (note that #name is the C preprocessor's "string-izing" syntax)
71,161,221
71,161,271
std vector.data return void
I required your help for a very strange behaviour that I can't understand. I wrote a simple usage of vector.data : void* ptr = NULL; // really initialized somewhere else bool* boolPtr = NULL; boolPtr = ((std::vector<bool>*)ptr)->data(); and when I compile (with -std=c++17) I got the error void value not ignored as it ought to be I try a lot a things but it seems that each time I call, from a casted vector (from void*), the data() method return a void instead of a bool*. What did I miss ?
vector<bool> is not a proper vector. As weird as that sounds, that's the way it is. It can't give you a pointer to its internal bool array, because it doesn't have one, since it stores the values packed into single bits.
71,161,989
71,162,481
Finding a hierarchy of polygons
I need an algorithm to determine a hierarchy of polygons. For example, I have only closed loops of vertices, where polygons have CCW vertices order and holes have CW vertices order. I want to create a structure to contain such hierarchy of polygons and holes. using Loop = std::vector<Point>; class PolygonHierarchy { public: PolygonHierarchy(const std::vector<Loop>& loops); ~PolygonHierarchy(); private: class Polygon { public: std::vector<Point> vertices; std::vector<Polygon*> childPolygons; bool isCCWOrder; } std::vector<Polygon*> polygonHierarchies; } Can someone explain how to find child polygons and form such tree? (it's not necessary to provide code).
As per what @YvesDaoust said in the comments, for each polygon/hole, you can find all the polygons/holes which contain it. This will give you a directed graph. In this graph, for each node, you may have more than one incoming edges. For instance, something like this: 1 (a) |\ | \ | 2 (b) 3 / Here, both 1 and 2 know about 3, but ideally only 2 should. Here, 1 is a parent of 2. If you generalise this, since there wont be any intersecting polygons, if you have two conflicting nodes a and b, and if a is an ancestor of b, you can discard a (otherwise discard b), and you can continue in this fashion, until only one incoming edge remains for each node,
71,162,266
71,170,101
Getting a std::string or C string from a QString representing an arbitrary filename on Windows
I'm using QFileDialog::getOpenFileName() to have the user select a file, but I need the result to be a C string, since I have to pass it to something written in C which uses fopen(). I cannot change this. The problem I'm finding is that, on Windows/MinGW, using toStdString() on the resulting QString doesn't work well with Unicode/non-ASCII filenames. Trying to open the file based on the std::string fails, because some character set conversion seems to be occurring. Sometimes using toLocal8Bit() to convert works, but sometimes it doesn't. Consider the following (MinGW) program: #include <cstdio> #include <iostream> #include <QApplication> #include <QFileDialog> #include <QFile> int main(int argc, char **argv) { QApplication app(argc, argv); auto filename = QFileDialog::getOpenFileName(); QFile f(filename); std::cout << "fopen: " << (std::fopen(filename.toStdString().c_str(), "r") != nullptr) << std::endl; std::cout << "fopen (local8bit): " << (std::fopen(filename.toLocal8Bit().data(), "r") != nullptr) << std::endl; std::cout << "Qt can open: " << f.open(QIODevice::ReadOnly) << std::endl; } For a file called ☢.txt, toStdString() works, local8Bit() doesn't. For a file called ä.txt, toStdString() doesn't work, local8Bit() does. For a file called Ȁ.txt, neither works. In all cases, though, QFile is able to open the file. I suppose it's probably using Unicode Windows functions while the C code is using fopen(), which, to my understanding is a so-called ANSI function on Windows. But is there any way to get a “bag of bytes”, so to speak, from a QString? I don't care about the encoding of the filename, I just want something that can be passed to fopen() to open the file. I've found that using GetShortPathName to get a short filename from filename.toWCharArray() seems to work, but that's very cumbersome, and my understanding is that NTFS filesystems can be told not to support short names, so it's not a viable solution in general anyway.
File paths in the non-unicode API of Windows are either parsed in the current ANSI (Microsoft codec) codepage, or in the OEM codepage (see also https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/fopen-wfope). ANSI is the default. So your question translates to: How can I convert a UTF-8 or UTF-16 string to ANSI or OEM? There's an answer for the ANSI conversion: How to convert from UTF-8 to ANSI using standard c++ Anyhow, it's important to realize that not all UTF strings can be represented in these more narrow codecs...
71,162,411
71,162,455
Vector subscript out of range AND The application was unable to start correctly [c++]
I'm writing quite simple program in c++ using Visual Studio but i keep getting 2 errors and i could use some help. One sometimes pops up when i run Local Windows Debugger after the app crashed and it says: The application was unable to start correctly (0xc0000142) message sometimes when running And the second one i guess happens between after cin >> kwota;. Don't really know when though, because VS is not showing any exception. It's just a message box from the os. It says: Debug Assertion Failed! [...] File: "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\vector" Line: 1566 Expression: vector subscript out of range message after puting second time into cin Here you have my code. I got no idea what can cause it so any help would be great. #include <iostream> #include <vector> #include <string> #include <sstream> #include <algorithm> using namespace std; int wyznaczZlote(vector<int> c, int z, int k) { int nowakwota, pozycja, ilosc; if (z > k) return 0; for (int p = k/z; p >= 0; p--) { nowakwota = k % z; while (nowakwota > 0) { pozycja = c.size() - 1; while (c[pozycja] > nowakwota && pozycja >= 0) { pozycja--; if (pozycja < 0) break; } if (pozycja < 0) break; ilosc = nowakwota / c[pozycja]; nowakwota = nowakwota % c[pozycja]; } if (nowakwota == 0) return p; } return -1; } int main() { int ilecyna, ilezloto, kwota, liczbazlotych; vector<int> cyna; vector<int> zloto; string wejscie, wejscie2; cin >> ilecyna; cin.ignore(); getline(cin, wejscie); stringstream wejscieStream(wejscie); int element; for (int i = 0; i < ilecyna; i++) { wejscieStream >> element; cyna.push_back(element); } sort(cyna.begin(), cyna.end()); cin >> ilezloto; cin.ignore(); getline(cin, wejscie2); stringstream wejscieStream2(wejscie2); for (int i = 0; i < ilecyna; i++) { wejscieStream2 >> element; cyna.push_back(element); } sort(zloto.begin(), zloto.end()); cin >> kwota; liczbazlotych = wyznaczZlote(cyna, zloto[0], kwota); cout << '\n'; if (liczbazlotych >= 0) cout << liczbazlotych << '\n'; else cout << "NIE" << '\n'; cin.ignore(); getchar(); } Thanks!
This sstatement cin >> wejscie; inputs only one word as soon as a white space character is encountered. So this for loop does not make a sense. stringstream wejscieStream(wejscie); int element; for (int i = 0; i < ilecyna; i++) { wejscieStream >> element; cyna.push_back(element); } Instead of using the operator >> in this statement cin >> wejscie; it seems you need to use std::getline like std::getline( std::cin, wejscie ); But before using it you need to clear the input buffer like #include <lomits> //... std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' ); Also this for loop for (size_t p = k/z[0]; p >= 0; p--) is an infinite for loop because the variable p having the unsigned integer type size_t never can be less than 0. And this while loop is suspecious while (c[pozycja] > nowakwota) pozycja--; because there is no check whether pozycja becomes less than 0. And use English word as identifiers of variables. Otherwise your code will be unreadable for the most of users. Also it is unclear why the second parameter denotes a vector vector<int> z while the only one its element z[0] is used within the function.
71,162,463
71,199,698
How to use clang AST matcher usingDirectiveDecl to find using namespace directive with specific name?
I'm trying to prototype a clang-tidy matcher with clang-query to find using namespace directive with a certain name like using namespace ns1::ns2;. With clang-query I tried these variants but none is matching anything: clang-query> match usingDirectiveDecl(hasName("ns1")).bind("changeNamespaceName") 0 matches. clang-query> match usingDirectiveDecl(hasName("ns2")).bind("changeNamespaceName") 0 matches. clang-query> match usingDirectiveDecl(hasName("ns1::ns2")).bind("changeNamespaceName") 0 matches. Is usingDirectiveDecl the right matcher for this task? What is the right way to find a using namespace directive with a specific name?
Unfortunately, it appears to be impossible to do this with a clang-query AST matcher alone. usingDirectiveDecl matches using namespace declarations, but further restriction based on the nominated namespace is incomplete. While UsingDirectiveDecl does have a name, it is simply the placeholder string ::<using-directive>: clang-query> m usingDirectiveDecl(matchesName("^::<using-directive>$")) Match #1: /home/scott/wrk/learn/clang/using-namespace/un1.cc:22:3: note: "root" binds here using namespace ns1; ^~~~~~~~~~~~~~~~~~~ Match #2: /home/scott/wrk/learn/clang/using-namespace/un1.cc:28:3: note: "root" binds here using namespace ns1::ns2; ^~~~~~~~~~~~~~~~~~~~~~~~ 2 matches. It turns out we can use hasDescendant to filter based on a namespace qualifier if one is present: clang-query> m usingDirectiveDecl(hasDescendant(nestedNameSpecifier(specifiesNamespace(matchesName("ns1"))))) Match #1: /home/scott/wrk/learn/clang/using-namespace/un1.cc:28:3: note: "root" binds here using namespace ns1::ns2; ^~~~~~~~~~~~~~~~~~~~~~~~ 1 match. This is filtering using the QualifierLoc member of UsingDirectiveDecl. But there's no way to filter on what comes after the qualifier, nor if there is no qualifier at all. The reason appears to be simply the absence of an AST matcher that would restrict UsingDirectiveDecl based on its NominatedNamespace field. Consequently, within a clang-tidy check, the best you can do is use a matcher to find all using namespace declarations, then (in subsequent C++ code) inspect the result of calling getNominatedNamespace().
71,162,642
71,172,028
CMake C++ library includes toolchain name
I am building a Python extension in C++ using pybind11 and scikit-build. I base on the example provided at https://github.com/pybind/scikit_build_example/blob/master/setup.py. My CMakelists boils down to this: pybind11_add_module(_mylib MODULE ${SOURCE_FILES}) install(TARGETS _mylib DESTINATION .) setup.py: setup( name="mylib", version="0.0", packages=['mylib'], cmake_install_dir="mylib", ) And on the python side I have in mylib/__init__.py: from _mylib import * This all works great. I can install the package with pip and importing mylib successfully imports the library by proxy. This proxy is necessary because I do more in the library than just the C++ library. Except there is one problem. The name of the built library includes the tools chain. For my system it looks like _mylib.cpython-38-x86_64-linux-gnu.so where I expect _mylib.so. __init__.py cannot find library unless either I rename it manually on the python side or I change the so name. How can I resolve this issue?
Conclusion: as Alex said this part of the name is necessary. See https://www.python.org/dev/peps/pep-3149/. Python will automatically figure out it can use _mylib.cpython-38-x86_64-linux-gnu.so if you import _mylib.
71,162,842
71,163,194
Override C++ method from multiply inherited templated base class
The enclosed code is a trimmed-down example of something I'm encountering. First, here's an even more simplified version that manages to compile: #include <string> template<typename T> class Base { public: Base() {} virtual ~Base() {} virtual size_t Size (void) const = 0; }; template<typename T> class Derived : public virtual Base<T> { public: Derived() {} virtual ~Derived() {} virtual size_t Size (void) const override { return 0; } }; class Impl : public virtual Derived<std::string>, public virtual Base<char const *> { public: Impl() {} virtual ~Impl() {} using Base<char const *>::Size; virtual size_t Size() const override { return 1; } }; int main(int argc, char **argv) { Impl oImpl; } The issue is being able to implement Base<std::string>::Size() as well as Base<char const *>::Size(). This question was instrumental in reaching this stage. (The using statement was key.) However, the problem is that, in the real code, I'm not merely returning a size_t, but an instance of a nested class. #include <string> template<typename T> class Base { public: Base() {} virtual ~Base() {} class Contained { public: Contained(); virtual ~Contained(); }; virtual Contained begin (void) const = 0; }; template<typename T> class Derived : public virtual Base<T> { public: Derived() {} virtual ~Derived() {} virtual typename Base<T>::Contained begin (void) const override { return typename Base<T>::Contained(); } }; class Impl : public virtual Derived<std::string>, public virtual Base<char const *> { public: Impl() {} virtual ~Impl() {} using Base<char const *>::begin; virtual typename Base<char const *>::Contained begin() const override { return typename Base<char const *>::Contained(); } /* virtual typename Base<char const *>::Contained Base<char const *>::begin() const override { return typename Base<char const *>::Contained(); } */ }; int main(int argc, char **argv) { Impl oImpl; } Somehow, g++/clang++ thinks this is a redefinition of Base<std::string>::Size, not Base<char const *>::Size – it complains of an invalid covariant type. So the using statement that worked so well in the first code sample is ineffective here. If I try to fully qualify the name, i.e. the commented-out section, g++ gives me cannot define member function 'Base<const char*>::Size' within 'Impl' (without saying why), and clang++ gives me non-friend class member 'Size' cannot have a qualified name (which I don't understand at all). Does anyone know how to override methods from different instances of the same templated base class? If anyone's interested, Base is a generic "enumerable" class, and I'm trying to create a class that has both a mutable interface (i.e. derived from Base<std::string>) and a read-only interface (i.e. derived from Base<char const *>) that doesn't leak how the string data is stored internally. (In general, I'm trying to implement C#-style enumerable interfaces in C++, e.g. so a client doesn't have to know that the underlying class is based on a list, vector, set, map, or whatever, only that its contained values can be enumerated through a non-specific interface class...implying that Contained is actually an iterator class).
What you have is essentially this: struct A { virtual int foo() { return 0;} }; struct B { virtual double foo() { return 0;} }; struct C : A, B { int foo() override { return 42; } double foo() override { return 3.14; } }; Oops! You can't do that. Each overrider of foo() in C overrides all foo() (same argument list, any return type) in all base classes. No fiddling with using changes that. What you need is essentially rename foo such that C inherits two functions of different names. Stroustrup proposes a technique of doing exactly that (in D&E I think but don't quote me on that). struct A { virtual int foo() { return 0;} }; struct B { virtual double foo() { return 0;} }; struct AA : A { virtual int foo1() { return 1; } // Essentially rename foo to foo1 int foo() override { return foo1(); } }; struct BB : B { virtual double foo2() { return 1; } // Essentially rename foo to foo2 double foo() override { return foo2(); } }; struct C : AA, BB { int foo1() override { return 42; } double foo2() override { return 3.14; } }; Now C still has two functions named foo() but they are frozen. From this point on, you manipulate only foo1 and foo2. Of course you can still call foo() via A and B, and these will call the correct version. So yes, C::foo is essentially a forbidden name. That's the price.
71,162,855
71,164,666
Thrust How could i acces my flatten array with a thrust::make_zip_iterator
Could some one could explain me why i can't access to my data. I got a flatten vector thrust::host_vector<double> input(10*3); inside i have points data X,Y,Z i make try to use a zip_iterator to access to my data so i make : typedef thrust::tuple<double, double, double, int> tpl4int; typedef thrust::host_vector<double>::iterator doubleiter; typedef thrust::host_vector<int>::iterator intiter; typedef thrust::tuple<doubleiter, doubleiter, doubleiter, intiter> tpl4doubleiter; typedef thrust::zip_iterator<tpl4doubleiter> tpl4zip; tpl4zip first = thrust::make_zip_iterator(thrust::make_tuple(input.begin(), input.begin() + N/3, input.begin() + 2*N/3, K.begin())); I try to acces to my data like this : std::vector<tpl4int> result_sorted(N); thrust::copy(first,first+N/3,result_sorted.begin()); std::cout << "row 0 = " << result_sorted[0].get<0>() << std::endl; std::cout << "row 1 = " << result_sorted[0].get<1>() << std::endl; std::cout << "row 2 = " << result_sorted[0].get<2>() << std::endl; std::cout << "row 0 = " << result_sorted[0].get<3>() << std::endl; but i didn't get the expected result X = 1.0245 Y = 1.0215 Z = 5.001 index = 0 instead of input[0] = 1.0245; input[1] = 2.54; input[2] = 3.001; index = 0; could someone tell my where i'm wrong ? here the full code #include <thrust/host_vector.h> #include <thrust/iterator/zip_iterator.h> #include <thrust/sequence.h> #include <thrust/fill.h> #include <thrust/tuple.h> #define N 30 // make this evenly divisible by 3 for this example typedef thrust::tuple<double, double, double, int> tpl4int; typedef thrust::host_vector<double>::iterator doubleiter; typedef thrust::host_vector<int>::iterator intiter; typedef thrust::tuple<doubleiter, doubleiter, doubleiter, intiter> tpl4doubleiter; typedef thrust::zip_iterator<tpl4doubleiter> tpl4zip; int main() { thrust::host_vector<double> input(10*3); int i=0; // input[0] = vec3(0,0,5.005); input[i++] = 1.0245; input[i++] = 2.54; input[i++] = 3.001; // input[1] = vec3(0,0,5.005); input[i++] = 2.0; input[i++] = 1.0; input[i++] = 5.01125; // input[2] = vec3(0,0,5.005); input[i++] = 6.0; input[i++] = 1.0; input[i++] = 5.0145; // input[3] = vec3(2,1,5.001); input[i++] = 6.0; input[i++] = 1.0215; input[i++] = 6.001; // input[4] = vec3(3,0,5.001); input[i++] = 6.0; input[i++] = 1.0845; input[i++] = 5.00125; // input[5] = vec3(4,0,5.001); input[i++] = 5.0; input[i++] = 0.0; input[i++] = 5.001; // input[6] = vec3(5,0,5.001); input[i++] = 5.0; input[i++] = 0.0; input[i++] = 5.001; // input[7] = vec3(6,0,10.501); input[i++] = 6.0; input[i++] = 0.0; input[i++] = 10.501; // input[8] = vec3(0,0,5.001); input[i++] = 1.0; input[i++] = 0.0; input[i++] = 5.0015478; // input[8] = vec3(0,0,5.001); input[i++] = 6.0; input[i++] = 1.005; input[i++] = 5.001; thrust::host_vector<int> K(N/3); // keys in one row thrust::sequence(K.begin(), K.end(), 0); // set index for key tpl4zip first = thrust::make_zip_iterator(thrust::make_tuple(input.begin(), input.begin() + N/3, input.begin() + 2*N/3, K.begin())); std::vector<tpl4int> result_sorted(N/3); thrust::copy(first,first+N/3,result_sorted.begin()); std::cout << "row 0 = " << result_sorted[0].get<0>() << std::endl; std::cout << "row 1 = " << result_sorted[0].get<1>() << std::endl; std::cout << "row 2 = " << result_sorted[0].get<2>() << std::endl; std::cout << "row 0 = " << result_sorted[0].get<3>() << std::endl; return 0; } Thanks in advance..
Because this is how a zip iterator works: It takes multiple buffers (Struct of Arrays: SoA) and lets you access them as if you had one buffer of tuples (Array of Structs: AoS). The first element accessed by your zip iterator is the tuple input[0], input[10] and input[20] (ignoring the integer). The second element is input[1], input[11] and input[21] and so on. This should somewhat make sense to you when looking at how you initialized your zip iterator with input.begin(), input.begin() + N/3 and input.begin() + 2*N/3 instead of input.begin(), input.begin() + 1 and input.begin() + 2 (which would not work as you would need an iterator with configurable stride to do it this way). Using a zip iterator is often good for performance on the GPU, because it allows for memory coalescing. It might be a good practice on the CPU as well if you want to make use of SIMD vectorization. If your input comes in AoS format, you will have to "transpose" it to use the zip iterator correctly. Depending on the use case this "transpose" might not be worth the effort, as it is an expensive operation on big vectors. Ideally you would get three input vectors x, y and z in the first place. Another good reason to use zip iterators is that they allow you to use more inputs or outputs per operation for many algorithms.
71,162,974
71,163,441
C++ ConcurrencyInAction: 7.2.2 Stopping those pesky leaks: managing memory in lock-free data structures
I am trying to understand how more than one thread hold head pointer in pop(), If two threads hold head pointer at "node *old_head = head.load();" then the first thread will complete the loop by updating the head and at the end let's say we delete the old_head and Thread1 completes it's work, now Thread2 is still holding deleted old_head and it will enter the while loop and old_head and current head are not same, so it will go to else if condition and set "old_head = head;" and loop again and update the head and come out of loop and delete the old_head. In the above process Thread2 never dereference the deleted node because it will come to else if condition if head and old_head are not same. But as per the Author from C++ ConcurrencyInAction Book do we really need to check for other Threads holding the old_head ? From C++ ConcurrencyInAction Book: The basic problem is that you want to free a node, but you can’t do so until you’re sure there are no other threads that still hold pointers to it. #include <memory> #include <atomic> using namespace std; template <typename T> class lock_free_stack { private: struct node { std::shared_ptr<T> data; node *next; node(T const &data_) : data(std::make_shared<T>(data_)) { } }; std::atomic<node *> head; public: void push(T const &data) { node *const new_node = new node(data); new_node->next = head.load(); while (!head.compare_exchange_weak(new_node->next, new_node)); } std::shared_ptr<T> pop() { node *old_head = head.load(); while (old_head && !head.compare_exchange_weak(old_head, old_head->next)); // background steps of compare_exchange_weak /* if ((old_head != nullptr) && (head == old_head)) { try { head = old_head->next; return true; // loop ends } catch(exception &e) { return false; // loop forever, at the end if we are deleting old_head then we are deleting head, it makes Stack without head } } else if ((old_head != nullptr) && (head != old_head)) { old_head = head; return false; } else { return false; // loop forever } */ return old_head ? old_head->data : std::shared_ptr<T>(); } }; int main() { return 0; }
In the above process Thread2 never dereference the deleted node because it will come to else if condition if head and old_head are not same. This is not true. Consider this line: head.compare_exchange_weak(old_head, old_head->next) This will access the value of old_head->next before the compare_exchange_weak even runs. Which means if old_head is a dangling pointer you get Undefined Behavoir. (Note that head will not equal old_head in this case and so the value of old_head->next will not be used but just accessing it before we know we'll not use it already causes the issue). Additionally in your pseudocode for cew it seems you think that accessing old_head->next will throw an exception? This isn't true in c++. Accesssing a bad pointer will immediately cause Undefined Behavoir which means all bets are off.
71,163,557
71,166,590
Linking glfw and assimp for a "standalone" project
I have a project following this tutorial. It works fine on my pc, but not on others since the libraries are not installed there. I have assimp, glfw, glm and stb installed through msys, so they are not directly included in the project. How would i need to link the libraries so that the application runs on other mashines? Ideally i would like to use static links (not sure how tho), but including the libraries with the appilcation would be fine too. Makefile: CC = g++ SRC = $(wildcard src/*.cpp) $(wildcard src/**/*.cpp) $(wildcard lib/**/**/*.c) LIBS = -lassimp.dll -lglfw3.dll CFLAGS = -Wall -Wextra -g3 -O2 -Ilib -Ilib/glad/include -Isrc OUT = bin/main all: $(CC) $(SRC) $(CFLAGS) $(LIBS) -o $(OUT)
Static linking is now working! The commands for linking now look like this: -l:libglfw3.a -opengl32 -lgdi32 -l:libassimp.a -lminizip -lz I just had some libraries missing that glfw and assimp depended on.
71,163,651
71,164,557
Collection of template child classes
I'm still new to template classes. But I have a parent class and then a template child class. namespace Foo::Bar { class BaseClass { // No declarations }; template<typename ChildClassType> class ChildClass : public BaseClass { public: /// Public declarations private: // Private Members }; } Edit: Including further information about the ChildClassType So I have several structs that will use this template class. struct foofoo { // Declarations } struct barbar { // Declarations } I want to be able to have a vector of multiple Child classes of each type so I used std::vector<std::unique_ptr<BaseClass>> allChildTypeVector; std::unique_ptr<ChildClass<foofoo>> childPtr; allChildTypeVectors.push_back(childPtr); Which is recommended by several other answers on here. But I am getting. no instance of overloaded function "std::vector<_Tp, _Alloc>::push_back ....." matches the argument list This same error is given if I do allChildTypeVectors.push_back(new ChildClass<ChildClassType>); I know something is going wrong with my types but I can't seem to figure it out.
std::unique_ptrs cannot be copied. If you could copy them they would not be unique. Hence you get the error when you try to call push_back. If you do have a std::unique_ptr<ChildClass<foofoo>> to be placed in the vector you can move it: #include <string> #include <memory> #include <vector> class BaseClass {}; template<typename ChildClassType> class ChildClass : public BaseClass {}; struct foofoo {}; int main() { std::vector<std::unique_ptr<BaseClass>> allChildTypeVector; std::unique_ptr<ChildClass<foofoo>> childPtr; allChildTypeVector.push_back(std::move(childPtr)); } Note that this has nothing to do with ChildClass being a template. There are no template classes. ChildClass is a class template, and ChildClass<foofoo> is a class. So then why does allChildTypeVectors.push_back(new ChildClass); not work? Because that would be the ideal solution. The constructor that takes a raw pointer is explicit. See here: https://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr. You can call the constructor explicitly or use std::make_unique: allChildTypeVector.push_back(std::unique_ptr<ChildClass<foofoo>>(new ChildClass<foofoo>)); allChildTypeVector.push_back(std::make_unique<ChildClass<foofoo>>()); A non-explicit constructor would be less than ideal because then raw pointers would implicitly convert to unique_ptrs unnoticed. For details I refer you to Why is unique_ptr<T>(T*) explicit?.
71,163,739
71,163,785
Does base class destructor need to be virtual if only some derived classes are polymorphic?
I have a similar situation to this question where I have 2 classes that share a public interface function, and so I've pulled that function (manage_data_in_memory() in the example) out into a base class which the 2 classes inherit from. However, the 2 classes are otherwise not related, and one of them is polymorphic, whereas the other one isn't. It is also not expected for someone to declare an object of this base class, as it exists only to prevent code duplication (is there a way to enforce this? I know pure virtual functions can prevent an object from being instantiated, but declaring a dummy pure virtual that does nothing in the derived class seems like bad design). Does the base class destructor need to be virtual in this case? This would force the other derived class to also have a virtual destructor, which it doesn't need. Thanks. So now I have code in the form class base { // don't instantiate an object of this, is there a way to enforce this? public: void manage_data_in_memory(); protected: data; }; class derived : public base { public: void sendData(); private: virtual void sendDataHelper(); // override this in derived classes which need to send custom data in addition to the default data }; class derived2 : public base { public: void do_Z_On_data() };
The destructor of a base class must be virtual if and only if an instance of a derived class will be destroyed through a pointer to the base object. If the destructor isn't virtual in such case, then the behaviour of the program would be undefined. Example: struct Base { // ... }; struct Derived : Base {}; std::unique_ptr<Base> ptr = std::make_unique<Derived>(); // Base::~Base must be virtual It's possible to prevent the user of the class from doing this (at least by accident) by using private inheritance. If the destructor isn't virtual, then inheritance should be private except possibly in special cases where you need a standard layout class. is this because private inheritance would make the destructor private No, private inheritance doesn't make destructor private. which prevents anyone from declaring an object of Base? No, and declaring an object of Base isn't a problem. Private inheritance prevents conversion from derived pointer into a base pointer outside the member functions of the derived class (and friends). The inability acquire a pointer to base of the derived class would prevent the user from deleting a derived object through such pointer.
71,164,023
71,164,448
How to pass a std::function callback to a function requiring a typedef of a pointer to a function
I've got a C library that takes a function pointer to register commands. I want to use this in my C++ application. I've tried to use std::function in combination with std::bind to create a C compatible function pointer that will call my member function inside a class. When trying to pass the std::function, I get an compilation error. // The way the C library typedef's the function typedef int (*console_cmd_func_t)(int argc, char **argv); // Function to register the callback needs a struct struct { console_cmd_func_t func; } console_cmd_t; void console_cmd_register(const console_cmd_t *cmd) { // Register the command } // In my C++ class typedef std::function<int(int argc, char **argv)> ConsoleFunction; ConsoleFunction fn = std::bind(&MyClass::consoleCommandHandler, this, std::placeholders::_1, std::placeholders::_2); const esp_console_cmd_t runCommand = { .func = fn }; console_cmd_register(&runCommand); However, this results in the following error: cannot convert 'ConsoleFunction' {aka 'std::function<int(int, char**)>'} to 'console_cmd_func_t' {aka 'int (*)(int, char**)'} in initialization Obviously its not the same definition. If I try to correct that however: typedef std::function<console_cmd_func_t> ConsoleFunction; I get the following error: variable 'ConsoleFunction fn' has initializer but incomplete type How can I successfully register the command?
struct { console_cmd_func_t func; } console_cmd_t; void console_cmd_register(const console_cmd_t *cmd) { // Register the command } Your C program is ill-formed. I'm going to assume that console_cmd_t isn't actually an instance of an unnamed struct as is depicted in the quoted code, but is rather a typedef name: typedef struct { console_cmd_func_t func; } console_cmd_t; How can I successfully register the command? By using the types that the functions expect. They don't expect a std::function, so you may not use std::function. There's also no way to register a non-static member function, nor a capturing lambda. A working example (assuming the correction noted above): int my_callback(int, char **); console_cmd_t my_struct { .func = my_callback, }; console_cmd_register(&my_struct); In order to call a non-static member function, you would typically pass a pointer to the class as an argument into the callback. If the C API doesn't allow passing user defined arguments, then the only option is to use global state. Example: static MyClass gobal_instance{}; int my_callback(int argc, char **argv) { gobal_instance.consoleCommandHandler(argc, argv); } To avoid global state, you need to re-design the C library.
71,165,137
71,165,593
How do I use getline to read from a file and then tokenize it using strtok?
I want my program to read lines from a file using getline(), and then tokenize the words using strtok(), and put them into a two-dimensional array. I understand there are probably way better ways to do this, but I am limited by what I've learned so far and the assignment requirements. I've tried using these threads/sites to refer to for help: C++ strtok() tutorial using getline to read from file in c++ #include <iostream> #include <fstream> #include <cstring> using namespace std; int main(int argc, char **argv) { char words[100][16]; //Holds the words int uniquewords[100]; //Holds the amount of times each word appears int counter; //counter if (argc = 2) { cout << "Success"; } else { cout << "Please enter the names of the files again. \n"; return 1; } ifstream inputfile; ofstream outputfile; inputfile.open(argv[1]); outputfile.open(argv[2]); char *token; while(inputfile.getline(words, 100)) { token = strtok(words[100][16], " "); cout << token; } } The error message I'm getting is error: no matching function to call to 'std::basic_ifstream::getline(char [100][16], int)'
First of all, the line if (argc = 2) is probably not doing what you intend. You should probably write this instead: if (argc == 2) The function std::istream::getline requires as a first parameter a char *, which is the address of a memory buffer to write to. However, you are passing it the 2D array words, which does not make sense. You could theoretically pass it words[0], which has space for 16 characters. Passing words[0] will decay to &words[0][0], which is of the required type char *. However, the size of 16 characters will probably not be sufficient. Also, it does not make sense to write the whole line into words, as this 2D array seems to be intended to store the result of strtok. Therefore, I recommend that you introduce an additional array that is supposed to store the entire line: char line[200]; (...) while( inputfile.getline( line, sizeof line ) ) Also, the line token = strtok(words[100][16], " "); does not make sense, as you are accessing the array words out of bounds. Also, it does not make sense to pass a 2D array to std::strtok, either. Another issue is that you should call std::strtok several times, once for every token. The first parameter of std::strtok should only be non-NULL on the first invocation. It should be NULL on all subsequent calls, unless you want to start tokenizing a different string. After copying all tokens to words, you can then print them in a loop: #include <iostream> #include <fstream> #include <cstring> using namespace std; int main(int argc, char **argv) { char line[200]; char words[100][16]; int counter = 0; ifstream inputfile; inputfile.open(argv[1]); while( inputfile.getline( line, sizeof line) ) { char *token; token = strtok( line, " "); while ( token != nullptr ) { strcpy( words[counter++], token ); token = strtok( nullptr, " " ); } } //print all found tokens for ( int i = 0; i < counter; i++ ) { cout << words[i] << '\n'; } } For the input This is the first line. This is the second line. the program has the following output: This is the first line. This is the second line. As you can see, the strings were correctly tokenized. However, note that you will be writing to the array words out of bounds if any of the tokens has a size larger than 16 characters, or the total number of tokens is higher than 100. To prevent this from happening, you could add additional checks and abort the program if such a condition is detected. An alternative would be to use a std::vector of std::string instead of a fixed-size array of C-style strings. That solution would be more flexible and would not have the problems mentioned above.
71,165,146
72,311,693
Conditionally import a module on C++20
Is there a way to conditionally import a module on C++20 without a preprocessor directive? pseudo-code: if WINDOWS: import my_module; else: import other_module; If there's no way, what would be the cleanest way of do it with the preprocessor?
If your goal is to have multiple implementations of the same functionality (for example, platform dependent) then cleaner way of doing this is to have multiple implementation units for the common module interface. For example, we want to have "my_module" module that provides platform dependent functionality void show_notification(std::string). We can have one common module interface file "my_module.ixx" that contains declarations: // my_module.ixx export module my_module; import <string>; export void show_notification(std::string text); Then we can have multiple module implementation units, one for each of the platforms: // my_module_windows.cpp module; // Windows specific includes module my_module; // Windows specific includes void show_notification(std::string text) { // Windows specific code ... } // my_module_linux.cpp module; // Linux specific includes module my_module; // Linux specific includes void show_notification(std::string text) { // Linux specific code ... } Both my_module_linux.cpp and my_module_windows.cpp provides implementation for my_module. Then we can use build system to include suitable module implementation unit in our build depending on platform or other settings. For example if we include my_module_windows.cpp in the set of translation units of our project we would have windows implementation.
71,165,150
71,166,491
How to open a std::ofstream using a custom allocator?
I'm writing a debugging tool in C++. The tool is not allowed to use the malloc heap, because doing so might alter the behavior of the program being debugged. Instead, the debugging tool has its own heap, separate from the malloc heap (let's call it the "debugger's heap"). My debugging tool is making heavy use of the C++ STL 'Allocator' parameter, to ensure that all my data structures go into the debugger's heap. So far, this is working fine. Now I need to write an output file to disk. I'm pretty sure that opening a std::ofstream would allocate memory on the heap. I mean, the file buffers have to go somewhere. But the std::ofstream doesn't accept an Allocator parameter. Is there any way to open an output file, and put the file buffers into the "debugger's heap"?
Yes, you can't use streams in your scenario. On most platforms, you can use the POSIX open function and then call read, write and close as appropriate. On Windows they renamed it _open, but it's basically the same. These functions are unbuffered, so incur no heap allocations. On the other hand, if you perform a lot of small reads or writes your program will be slower because of the lack of buffering, so you need to take this into account when designing your code.
71,166,102
71,178,118
Add OpenGL to Linux Vscode
I followed this tutorial successfully. But it doesn't explain how to configure on vscode. Glad is in this folder /usr/include and I did use sudo in the terminal to compile and generate a.out. How do I do that in vscode? I have this error output when I try to build task: terminal Starting build... /usr/bin/g++ -fdiagnostics-color=always -g /home/raijin/Documents/Code/C++/OpenGL/*.cpp -I/home/raijin/Documents/Code/C++/OpenGL/ -o /home/raijin/Documents/Code/C++/OpenGL/main /home/raijin/Documents/Code/C++/OpenGL/main.cpp:3:10: fatal error: /usr/include/glad/glad.h: Permission denied 3 | #include <glad/glad.h> My tasks is configured like that: tasks.json { "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "C/C++: g++ build active file", "command": "/usr/bin/g++", "args": [ "-fdiagnostics-color=always", "-g", "${workspaceFolder}/*.cpp", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "compiler: /usr/bin/g++" } ] } How do I configure OpenGL vscode?
If anyone has the same problem I solved it adding these args in tasks.json "${workspaceFolder}/*.c", "-lGL", "-lglfw", "-ldl" And the folder glad in /usr/include for some reason had a gray x on the folder icon and it couldn't be accessed without sudo command. I deleted and made a glad empty folder and copied glad.h inside it. After that the code worked as expected in vscode.
71,166,339
71,166,543
Return class object with member variable
Why the function test() works even I'm not returning a Base class ? What happens with the compilation ? Can someone explain me ? #include <iostream> class Base { public: Base(){} Base(int val): _val(val){}; ~Base(){}; Base test(int n){ return (n); } int &operator *() { return (_val); }; private: int _val; }; int main() { Base base; Base a; a = base.test(42); std::cout << *a << std::endl; return (0); }
You declared a constructor that takes in an int, and you declared that test(int n) should always return a Base class. The compiler knows that in order to create a Base object you need either nothing (default constructor) or an int, so it creates an object using the constructor that takes an int an returns that. If you wanted to, you could be explicit about it and do something like the following and get the exact same behaviour: Base test(int n){ return Base(n); } In short, n is implicitly cast to a Base object, as you declared a constructor that requires only an int.
71,166,391
71,167,460
(C++ vectors) How to assign values in a range of elements inside a vector?
I have a vector of ints, like {0, 0, 0, 0, 0}. I need to increase v[i] by 1 for a range of elements, like v[1] to v[3] so that I have {0, 1, 1, 1, 0}. How to do that?
Just use a simple iterative loop, eg: std::vector<int> v = {0, 0, 0, 0, 0}; for(size_t i = 1; i <= 3; ++i) { v[i]++; } Online Demo Which you can also replicate using standard library algorithms like std::for_each() and std::transform(), eg: std::vector<int> v = {0, 0, 0, 0, 0}; std::for_each(v.begin()+1, v.begin()+4, [](int& i){ ++i; } ); Online Demo std::vector<int> v = {0, 0, 0, 0, 0}; std::transform(v.begin()+1, v.begin()+4, v.begin()+1, [](int i){ return i+1; } ); Online Demo
71,167,077
71,211,660
Overloading with template nested type
Consider #include <iostream> template <typename T> void foo (T*) { std::cout << "foo (T*) called.\n"; } template <typename T> void foo (typename T::Node*) { std::cout << "foo (typename T::Node*) called.\n"; } struct A { struct Node { }; }; int main() { A* a = new A; foo(a); A::Node* node = new A::Node; foo(node); } Output: foo (T*) called. foo (T*) called. How do I fix the code so that the second output gives foo (typename T::Node*) called.?
This is because when you call foo the type for T needs to be deduced by the compiler. Since both A and A::Node are valid for the first foo. And the second Foo is not more specific. It'll call the first version of foo (substituting T with A and A::Node). To force the compiler to replace T with A and then see T::Node* you can specify what the template argument should be. foo<A>(node); A quick way to see what the compiler is using for its types is by using the __PRETTY_FUNCTION__ macro. Which would output: foo (T*) called. sig: void foo(T *) [T = A] foo (T*) called. sig: void foo(T *) [T = A::Node] for the original code and foo (typename T::Node*) called. sig: void foo(typename T::Node *) [T = A] for foo<A>(node); See https://godbolt.org/z/4xb45svYW
71,167,185
71,168,763
opengl drawing a 3d cube with with EBO
I am trying to draw a cube with OPENGL by using EBO, VAO, and VBO. the first function init the VAO of the cube initVAO() { GLfloat cube_vertices[] = { // front -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, // back -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0 }; GLushort cube_elements[] = { // front 0, 1, 2, 2, 3, 0, // right 1, 5, 6, 6, 2, 1, // back 7, 6, 5, 5, 4, 7, // left 4, 0, 3, 3, 7, 4, // bottom 4, 5, 1, 1, 0, 4, // top 3, 2, 6, 6, 7, 3 }; vertices.insert(vertices.begin(), std::begin(cube_vertices), std::end(cube_vertices)); indices.insert(indices.begin(), std::begin(cube_elements), std::end(cube_elements)); /* create vao */ glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); /* create ebo */ glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_elements), cube_elements, GL_STATIC_DRAW); /* create vbo */ glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); /* unbind buffers */ glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindVertexArray(0); } and the second function use it to draw draw() { shader->activateShader(); /* calculate projection matrix */ //TODO:: find a new place for the projection matrix calculation int width = (GLfloat)ResourceManager::getInstance()->getWindowSize().x; int height = (GLfloat)ResourceManager::getInstance()->getWindowSize().y; glm::mat4 proj = glm::perspective(glm::radians(45.0f), (float)width / height, 0.1f, 100.0f); /* update shader uniforms*/ glUniformMatrix4fv(shader->projectionUniform, 1, GL_FALSE, glm::value_ptr(proj)); glUniformMatrix4fv(shader->viewUniform, 1, GL_FALSE, glm::value_ptr(Engine::getInstance()->camera->createViewMatrix())); glUniformMatrix4fv(shader->modelUniform, 1, GL_FALSE, glm::value_ptr(transform->createModleMatrix())); glUniform4f(shader->colorUniform, color.x, color.y, color.z, 1); glBindVertexArray(VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindVertexArray(0); glUseProgram(0); } right now the program is not drawing anything and I cant figure out what is wrong with it I know that the other parts of the code works because I tested it without a EBO and it worked but I don't know what to do.
See Index buffers. The index buffer binding is stated within the Vertex Array Object. When a buffer is bound to the target ELEMENT_ARRAY_BUFFER, then this buffer is associated to the vertex array object which is currently bound. When calling glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); the binding of the element buffer to the currently bound VAO is broken. Remove this line of code: glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); The type specification in the glDrawElements must match the type of the indices. Since the type of the indexes is GLushort, the specified type must be GL_UNSIGNED_SHORT: glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, 0);
71,167,585
71,167,680
How can I return a calloc pointer from C into C++?
I am working on a personal project that requires me to call C functions from C++ code. These C functions return a calloc() pointer. 1t5.h #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> char * prob1(char * number); 1t5.c #include <1t5.h> char * prob1(char * number) { int ni = atoi(number); char prompt[] = "hello\n"; char * answer = (char*)calloc(ni, sizeof(prompt)); for (int i = 0; i < ni; i++) { strcat(*answer, prompt); } return answer; } That C code is supposed to return a given number of "hello\n". linking.cpp string Link::problemRouting(string problem, vector<string> contents) { string answers = ""; char * ca; int pi = stoi(problem); for (int i = 0; i < contents.size(); i++) { ca = cv.stringToChar(contents[i]); // C Standard if (pi <= 5) { char * answer; switch(pi) { case 1:{ answer = prob1(ca); } case 2: { answer = prob2(ca); } case 3: { answer = prob3(ca); } case 4: { answer = prob4(ca); } case 5: { answer = prob5(ca); } } cout << answer; answers+=answer; free(answer); } } return answers; } This C++ code takes the return value and saves it to store into a text file later. The problem is when I input a number, lets say 257, then the return value is 257, and not a ton of "hello\n".
Thanks to @Remy Lebeau for the answer. My code contained many chances for memory to leak, resulting in a mess of a return value. string Link::problemRouting(string problem, vector<string> contents) { string answers = ""; char * ca; int pi = stoi(problem); for (int i = 0; i < contents.size(); i++) { ca = cv.stringToChar(contents[i]); // C Standard if (pi <= 5) { char * answer; switch(pi) { case 1:{ answer = prob1(ca); break; } } free(ca); cout << answer; answers+=answer; free(answer); } } return answers; }
71,167,650
71,167,762
Why we can reuse a moved socket_ in acceptor_.async_accept?
Reference: https://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/reference/basic_socket_acceptor/async_accept/overload1.html boost::asio::ip::tcp::acceptor acceptor(io_service); ... boost::asio::ip::tcp::socket socket(io_service); // you have to initialize socket with io_service first before //you can use it as a parameter on async_accept. acceptor.async_accept(socket, accept_handler); Reference: https://github.com/vinniefalco/CppCon2018/blob/master/listener.cpp listener:: listener( net::io_context & ioc, tcp::endpoint endpoint, std::shared_ptr < shared_state > const & state): acceptor_(ioc), socket_(ioc), state_(state) { // Accepts incoming connections and launches the sessions class listener : public std::enable_shared_from_this<listener> { tcp::acceptor acceptor_; tcp::socket socket_; ... } // Handle a connection void listener:: on_accept(error_code ec) { if (ec) return fail(ec, "accept"); else // Launch a new session for this connection std::make_shared < http_session > ( std::move(socket_), // socket_ is moved here? state_) -> run(); // Accept another connection acceptor_.async_accept( socket_, // why we still can use it here? [self = shared_from_this()](error_code ec) { self -> on_accept(ec); }); } Based on my understanding, std::move(socket_) allows the compiler to cannibalize socket_. In other word, the listener::socket_ originally initialized by socket_(ioc) will become uninitialized. Question> How can we give an uninitialized socket_ to acceptor_.async_accept? Thank you
It all depends on the implementation of the types. We can loosely describe the intent of a move as "the compiler is allowed to cannibalize". But really, for user-defined types we're going to have to tell it how to do that, exactly. In language "doctrine" a moved-from object may only be assumed safe to destruct, but in practice many libraries make more lenient guarantees (e.g. keeping all the invariants, or making sure that a moved-from object is comparable to a newly constructed one). Indeed, ASIO documents this: Remarks Following the move, the moved-from object is in the same state as if constructed using the basic_stream_socket(const executor_type&) constructor.
71,168,032
71,168,072
Retrieving structure from vector of structs following a find_if
I have written this small program to search for a struct inside a vector of structs. After this line in the code below, how should I extract the element of the vector that matched. i.e. the structure and its contents. if (std::find_if(jobInfoVector.begin(), jobInfoVector.end(), pred) != jobInfoVector.end()) #include <iostream> #include <vector> #include <algorithm> #include "boost/bind.hpp" using namespace std; struct jobInfo { std::string jobToken; time_t startTime; time_t endTime; }; typedef struct jobInfo JobInfo; int main() { std::vector<JobInfo> jobInfoVector; JobInfo j1 = {"rec1",1234,3456}; JobInfo j2 = {"rec2",1244,3656}; JobInfo j3 = {"rec3",1254,8456}; jobInfoVector.push_back(j1); jobInfoVector.push_back(j2); jobInfoVector.push_back(j3); auto pred = [](const JobInfo &jobinfo) { return jobinfo.startTime == 1234; }; if (std::find_if(jobInfoVector.begin(), jobInfoVector.end(), pred) != jobInfoVector.end()) { cout << "got a match" << endl; } else { cout << "Did not get a match" << endl; } return 0; }
You can save the result of the std::find_if() as an iterator, then dereference to extract its components. Like: #include <iostream> #include <vector> #include <algorithm> #include "boost/bind.hpp" using namespace std; struct jobInfo { std::string jobToken; time_t startTime; time_t endTime; }; typedef struct jobInfo JobInfo; int main() { std::vector<JobInfo> jobInfoVector; JobInfo j1 = {"rec1",1234,3456}; JobInfo j2 = {"rec2",1244,3656}; JobInfo j3 = {"rec3",1254,8456}; jobInfoVector.push_back(j1); jobInfoVector.push_back(j2); jobInfoVector.push_back(j3); auto pred = [](const JobInfo &jobinfo) { return jobinfo.startTime == 1234; }; auto it = std::find_if(jobInfoVector.begin(), jobInfoVector.end(), pred); if (it != jobInfoVector.end()) { jobInfo& match = *it; cout << "got a match" << endl; //Do whatever job with match } else { cout << "Did not get a match" << endl; } return 0; }
71,168,173
71,168,203
How to call a function from another function using STL list in C++?
I'm new to data structures in C++, I want to write a code using STL list to display the following: Input for data radius: Radius 1: 20 Press [Y] for next input: Y Radius 2: 12 Press [Y] for next input: N List of Existing Records: ID:1, Radius: 20, Volume: 33,514.67 ID:2, Radius: 12, Volume: 7,239.17 Total record: 2 I wrote the code like this, but I'm no so sure on how exactly to include the volume value dataVolume() so that I can get the desired output: #include <iostream> #include <list> using namespace std; struct sphere { int recordID; double radius, volume; }; double dataVolume(sphere* values) { double v = (4 * 3.14 * (values->radius) * (values->radius) * (values->radius)) / 3.0; return v; } void dataRadius(sphere* values) { int i = 0; char choice; do { cout << "Radius " <<i+1 <<": "; cin >> values->radius; // values->volume = dataVolume(); cout << "Press [Y] for next input: "; cin >> choice; i++; } while (choice == 'Y'); } void displayData(list<sphere>Record) { cout << "List of Existing Records:" << endl; list<int>::iterator i; int count = 0; for (auto i = Record.begin(); i != Record.end(); i++) { cout << "ID: " << count + 1 << ", Radius: " << i->radius << ", Volume: " << i->volume << endl; count = count + 1; } cout << "Total record: " << count << endl; } int main() { list<sphere>Record; sphere values; dataRadius(&values); displayData(Record); return 0; }
double dataVolume(double radius) { double v = (4 * 3.14 * radius * radius * radius) / 3.0; return v; } void dataRadius(sphere* values) { int i = 0; char choice; do { cout << "Radius " <<i+1 <<": "; cin >> values->radius; values->volume = dataVolume(values->radius); cout << "Press [Y] for next input: "; cin >> choice; i++; } while (choice == 'Y'); } besides, you should push sphere into list. I will rewirte like this. void dataRadius(list<sphere> & Record) { int i = 0; char choice; do { cout << "Radius " <<i+1 <<": "; sphere values; // construct a new sphere cin >> values.radius; values.volume = dataVolume(values.radius); Record.push_back(values); cout << "Press [Y] for next input: "; cin >> choice; i++; } while (choice == 'Y'); } int main() { list<sphere>Record; dataRadius(Record); displayData(Record); return 0; }
71,168,259
71,168,553
Number of ways to delete a binary tree if only leaves can be deleted
I am solving an algorithm question: You are given a binary tree root. In one operation you can delete one leaf node in the tree. Return the number of different ways there are to delete the whole tree. So, if the tree is: 1 / \ 2 3 / 4 The expected answer is 3: [2, 4, 3, 1],[4, 2, 3, 1] and [4, 3, 2, 1]. I have been thinking hard, but I don't know how to formulate the recursive function. Thinking along the lines of the Climbing Stairs problem in which we count "distinct ways can you climb to the top", I think I have to use DP, but I am unable to formulate the recursive relation. If you could provide some hints/guidance, I would appreciate it. Thanks! Edit: Given the following tree: 1 / \ 2 3 / \ 4 5 There are 2 ways in which we could delete the children of 3 (4, 5); but how to use this info to determine the number of ways for root node 1? (The expected answer is 8).
For a give node X, we want to know u(X) - the number of unique delete sequences. Assume this node has two children A, B with sizes |A|, |B| and known u(A) and u(B). How many delete sequences can you construct for X? You could take any two sequences from u(A) and u(B) and root and combine them together. The result will be a valid delete sequence for X if the following holds: The root X must be deleted last. Order of deletion of any two nodes from different subtrees is arbitrary. Order of deletion of any two nodes from the same subtree is fixed given its chosen delete sequence. This means you want to find out the number of ways you can interleave both sequences (and append X). Notice that the length of a delete sequence is the size of the tree, that's kind of trivial if you think about it. Also give some though to the fact that this way we can generate all the delete sequences for X, that might not be so trivial. So if I'm counting correctly, the formula you are looking for is u(X)= [|A|+|B| choose |A|] * u(A) * u(B). It holds for empty children too if we define u(empty)=1. Just be careful about overflow, the number of combinations will explode quite quickly.
71,168,275
71,168,501
openGL 3D Rectangle not overlapping properly in C++
You are given 3 rectangular strips whose vertex coordinates are as given below. Rectangle A (RED COLOR) (-0.5,0.6,-0.8), (-0.2,0.9,-0.8), (0.8,-0.1, 0.8), (0.5, -0.4, 0.8) Rectangle B (GREEN COLOR) (0.0, 0.8, 0.8), (0.3, 0.5, 0.8), (-0.7, -0.5, -0.8), (-1.0, -0.2, -0.8) Rectangle C (BLUE COLOR) (0.6, 0, -0.8), (0.6, -0.3, -0.8), (-0.9, -0.3, 0.8), (-0.9, 0, 0.8) Plot these strips on screen. Make the background black. Required Output: Output Image This is my C++ program: #include <iostream> #include <fstream> #include <GL/freeglut.h> #include <GL/gl.h> #include<bits/stdc++.h> using namespace std; void renderFunction(){ glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); // Red Polygon glColor3f(1.0, 0.0, 0.0); glBegin(GL_POLYGON); glVertex3f(-0.5,0.6,-0.8); glVertex3f(-0.2,0.9,-0.8); glVertex3f(0.8,-0.1, 0.8); glVertex3f(0.5, -0.4, 0.8); glEnd(); // Green Polygon glColor3f(0.0, 1.0, 0.0); glBegin(GL_POLYGON); glVertex3f(0.0, 0.8, 0.8); glVertex3f(0.3, 0.5, 0.8); glVertex3f(-0.7, -0.5, -0.8); glVertex3f(-1.0, -0.2, -0.8); glEnd(); // Blue Polygon glColor3f(0.0, 0.0, 1.0); glBegin(GL_POLYGON); glVertex3f(0.6, 0.0, -0.8); glVertex3f(0.6, -0.3, -0.8); glVertex3f(-0.9, -0.3, 0.8); glVertex3f(-0.9, 0.0, 0.8); glEnd(); glFlush(); } int main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE); glutInitWindowSize(1366, 768); glutInitWindowPosition(100, 100); glutCreateWindow("Q6 - 3D Polygon"); glutDisplayFunc(renderFunction); glutMainLoop(); return 0; } My Output: output based on above code Now the problem is that the right end of the blue rectagular part is on top of the red rectangle which is not the required output. The required output is blue's right end is below the red rectangle. I don't know what's the problem. I tried by clearing the GL_DEPTH_BUFFER_BIT. But it creates the same output. Please help me on this.
The reason why this was not working is because You initialized display mode as GLUT_SINGLE (Not including the GLUT_DEPTH). You did not enabled glEnable(GL_DEPTH_TEST). Those two are needed to enable the depth test, so, you have to put glEnable(GL_DEPTH_TEST); right after glClear, and change glutInitDisplayMode(GLUT_SINGLE) to glutInitDisplayMode(GLUT_SINGLE|GLUT_DEPTH).
71,168,355
71,168,536
Is writing to uninitialized memory allocated by allocator UB? And what about reading it afterwards?
struct Foo{ int i; int j; }; int main(){ std::allocator<Foo> bar; Foo* foo = bar.allocate(1); foo->i = 0; return foo->i; // ignore the memory leak, it's irrelevant to the question } I'm curious about whether there are undefined behaviors in the snippet above? Will the conclusion vary according to the type of Foo (e.g. not all members are POD type, or Foo has virtual functions)?
It is an error to use raw memory in which an object has not been constructed. We must construct objects in order to use memory returned by allocate. Using unconstructed memory in other ways is undefined. Source: C++ Primer, Fifth Edition Since you have not used construct the behavior of your program is undefined prior to C++20. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program. 1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
71,168,479
71,171,530
Quicksort not sorting one element in the list of strings
Could anyone tell me what is wrong with my code: int Partition(vector<string>& userIDs, int i, int k) { int pivot = (i + (k - i) / 2); string temp; while(i<k) { cout << "pivot:" << pivot << endl; while (userIDs.at(i).compare(userIDs.at(pivot))<0) { cout << "1. i:"<<i<<" UserIDs.at(i):" << userIDs.at(i) << " UserID.at(pivot): " << userIDs.at(pivot) << endl; i += 1; } while (userIDs.at(pivot).compare(userIDs.at(k))<0) { cout << "2. k:" << k << " UserIDs.at(k):" << userIDs.at(k) << " UserID.at(pivot): " << userIDs.at(pivot) << endl; k -= 1; } if(i<k){ cout << "3. i:" << i << " k:"<<k<<" UserIDs.at(i):" << userIDs.at(i) << " UserID.at(k) : " << userIDs.at(k) << endl; temp = userIDs.at(i); userIDs.at(i) = userIDs.at(k); userIDs.at(k) = temp; i++; k--; } cout << "4. i:" << i << " k:" << k << endl; } cout << " 5. k:" << k << endl; return k; } void Quicksort(vector<string>& userIDs, int i, int k) { cout << "Quicksort i:" << i << " k:" << k << endl; if (i >= k) { return; } int lowEndIndex = Partition(userIDs, i, k); cout << "Quicksort lowEndIndex:" << lowEndIndex << endl; Quicksort(userIDs, i, lowEndIndex); Quicksort(userIDs, lowEndIndex+1, k); } When I input this list: BigBen GardenHeart GreyMare TeenPunch WhiteSand LifeRacer Doom AlienBrain I get: AlienBrain BigBen GreyMare GardenHeart Doom LifeRacer TeenPunch WhiteSand Why is Doom not in the correct place?
#include <bits/stdc++.h> using namespace std; int Partition(vector<string>& userIDs, int i, int k) { int pivot = i; string pivotValue = userIDs[pivot]; string temp; int leftIndex = i; int rightIndex = k; while(i<k) { while (userIDs[i].compare(pivotValue)<=0) { i++; if(i >= rightIndex) break; } while (pivotValue.compare(userIDs[k])<=0) {; k--; if(k <= leftIndex) break; } if(i<k){ temp = userIDs[i]; userIDs[i] = userIDs[k]; userIDs[k] = temp; } } // swap userIDs[pivot] = userIDs[k]; userIDs[k] = pivotValue; return k; } void Quicksort(vector<string>& userIDs, int i, int k) { if (i >= k) { return; } int lowEndIndex = Partition(userIDs, i, k); Quicksort(userIDs, i, lowEndIndex - 1); Quicksort(userIDs, lowEndIndex + 1, k); } int main() { vector<string> userIDs = {"BigBen", "GardenHeart", "GreyMare", "TeenPunch", "WhiteSand", "LifeRacer", "Doom", "AlienBrain" }; Quicksort(userIDs, 0, userIDs.size() - 1); for(auto& c: userIDs) cout << c << " "; cout << endl; return 0; } Fixed the code and tested. Now it works. What were the problems? As far as I noticed, firstly you didn't put break() statements within the while loops in case i or k exceeds the boundaries of the vector. I've changed the pivot from middle element to first element, but it's just my preference, you can implement the quicksort algorithm with your pivot in the middle, not a big deal. I've called first Quicksort() with lowEndIndex - 1 rather than lowEndIndex. I've used [] operator rather than at(), but again it's my preference. I guess the main problems were that break stuff and calling the quicksort method with lowEndIndex rather than lowEndIndex - 1. Output: AlienBrain BigBen Doom GardenHeart GreyMare LifeRacer TeenPunch WhiteSand
71,168,723
71,168,865
How to find package and link library without cmake in simple cpp file?
file name: main.cpp #include<iostream> #include"boolector.h" using namespace std; int main() { Btor* btor=boolector_new(); cout<<"hello world"; boolector_delete(btor); } What if I don't want to make CMake project, just a C++ file and still wants to link library as in CMake? I want equivalent to following (in CmakeLists.txt) in g++. find_package(Boolector) target_link_library(project_name Boolector::boolector) Documentation can be found at Text. /usr/local/bin/boolector /usr/local/include/boolector /usr/local/include/boolector/boolector.h /usr/local/include/boolector/btortypes.h /usr/local/lib/libboolector.a /usr/local/lib/libboolector.so Result of locate boolector /usr/local/lib/cmake/Boolector /usr/local/lib/cmake/Boolector/BoolectorConfig.cmake /usr/local/lib/cmake/Boolector/BoolectorConfigVersion.cmake /usr/local/lib/cmake/Boolector/BoolectorTargets-release.cmake /usr/local/lib/cmake/Boolector/BoolectorTargets.cmake Result of locate Boolector I am using CentOS.
You can use -l, -L and -I options of g++ like: g++ -L /usr/local/lib/ -lboolector -I /usr/local/include/boolector main.cpp -o main -l option is for setting the name of the library to be linked -L option is for setting the path where the library to be linked has to be searched -I option is for setting the path where header files of the library are present To run the executable, you need to make sure that the libraries are there in the LD_LIBRARY_PATH environment variable. export LD_LIBRARY_PATH=$LD_LIBARY_PATH:/usr/local/lib ./main
71,168,884
71,169,188
How to push values and delete a record from a list in C++?
I'm new to data structures in C++, and I'm stuck at some points that I couldn't fix, I want to write a code using STL list to display the following: Input for data radius: Radius 1: 20 Press [Y] for next input: Y Radius 2: 12 Press [Y] for next input: N List of Existing Records: ID:1, Radius: 20, Volume: 33,514.67 ID:2, Radius: 12, Volume: 7,239.17 Total record: 2 Would you like to remove specific data [Press Y for Yes]: Y Enter record ID: 1 List of Existing Records: ID:2, Radius: 12, Volume: 7,239.17 Total record: 1 I wrote the code like this, I want to push sphere to the list and I want user to choose what record to delete but I'm not really sure on the accurate way to do it: #include <iostream> #include <list> using namespace std; struct sphere { int recordID; double radius, volume; }; double dataVolume(double r) { double v = (4 * 3.14 * r * r * r) / 3.0; return v; } void dataRadius(sphere* values) { int i = 0; char choice; do { cout << "Radius " <<i+1 <<": "; cin >> values->radius; values->volume = dataVolume(values->radius); cout << "Press [Y] for next input: "; cin >> choice; i++; } while (choice == 'Y'); Record.push_back(values); //why i cant push back the values to the list } void displayData(list<sphere>Record) { cout << "List of Existing Records:" << endl; list<int>::iterator i; int count = 0; for (auto i = Record.begin(); i != Record.end(); i++) { cout << "ID: " << count + 1 << ", Radius: " << i->radius << ", Volume: " << i->volume << endl; count = count + 1; } cout << "Total record: " << count << endl; } void deleteData(list<sphere>Record) { char cho; cout << "Would you like to remove specific data [Press Y for Yes]: "; cin >> cho; if (cho == 'Y') { int id; cout << "Enter record ID: "; cin >> id; Record.erase(id); // why it shows error } } int main() { list<sphere>Record; sphere values; dataRadius(&values); displayData(Record); deleteData(Record); displayData(Record); return 0; }
You were making some mistakes. In removing element, you cant just use integer index.U have to use iterator of the list type. then you were push_backing sphere element in record list after all choices which only inserts last choice of user. I have fixed that too. 3rd mistake was, you were push_backing pointer to sphere v but technically we have to push value of that pointer. I have fixed that too. now its working fine. #include <iostream> #include <list> using namespace std; struct sphere { int recordID; double radius, volume; }; list<sphere>Record; //Fixed:- made this global double dataVolume(double r) { double v = (4 * 3.14 * r * r * r) / 3.0; return v; } void dataRadius(sphere* values) { int i = 0; char choice; do { cout << "Radius " <<i+1 <<": "; cin >> values->radius; values->volume = dataVolume(values->radius); Record.push_back(*values);//Fixed:- inserting value not address and get it inside scope so that all values are inserted. cout << "Press [Y] for next input: "; cin >> choice; i++; } while (choice == 'Y'); } void displayData(list<sphere> &Record) {//Fixed:- passed as referemce cout << "List of Existing Records:" << endl; list<int>::iterator i; int count = 0; for (auto i = Record.begin(); i != Record.end(); i++) { cout << "ID: " << count + 1 << ", Radius: " << i->radius << ", Volume: " << i->volume << endl; count = count + 1; } cout << "Total record: " << count << endl; } void deleteData(list<sphere> &Record) { //Fixed:- passed as reference char cho; list<sphere>::iterator itr1, itr2; itr2 = Record.begin(); itr1 = Record.begin(); cout << "Would you like to remove specific data [Press Y for Yes]: "; cin >> cho; if (cho == 'Y') { int id; cout << "Enter record ID: "; cin >> id; advance(itr1, id-1); Record.erase(itr1);//Fixed:- using iterator of same type as list to erase element } } int main() { sphere values; dataRadius(&values); displayData(Record); deleteData(Record); displayData(Record); return 0; }
71,168,948
71,169,045
inline static variable in different translation units has different values(c++17)
I want to implement a source file that contains a global variable, and I want to do this through inline static. I can change a variable (e.g., i) within the context of a translation unit, but when I call the variable outside of that translation unit, the result will remain unchanged for the caller. It's like there is a copy for each unit. See the below example: header.h #ifndef UNTITLED1_TEST_H #define UNTITLED1_TEST_H namespace t { inline static int i{0}; void inc() ; void print_i() ; } #endif //UNTITLED1_TEST_H header.cpp #include "header.h" void t::inc() { t::i++; } void t::print_i() { std::cout << t::i << std::endl; } So let's see how the program performs: main.cpp #include "header.h" int main() { t::inc(); std::cout << t::i << std::endl; // -> output is: 0 t::print_i(); // -> output is : 1 } As you can see, the variable i has different values across different translation units, how can this be resolved? I cannot use classes or anything else since the client wants the code in this format. note I can do such things as below, but it isn't the main issue, I want a global variable: t::i++; //instead of t::inc(); std::cout << t::i << std::endl; // it's okay now, but it's not what I wanted Alternatively, I can use inline instead of inline static. It seems to be working, but my mentor said that I should use inline static instead.
static variables (as in your example) have internal linkage. There are 2 ways to achieve what you want, both of which are shown below. Also note that the static keyword has other meanings as well. Method 1: C++17 With C++17, we can use the inline keyword as shown below: header.h #ifndef UNTITLED1_TEST_H #define UNTITLED1_TEST_H namespace t { inline int i{0};//note the keyword inline here and initializer while keyword static has been removed void inc() ; void print_i() ; } #endif header.cpp #include "header.h" #include <iostream> //No need for initilaizing t::i here void t::inc() { t::i++; } void t::print_i() { std::cout << t::i << std::endl; } main.cpp #include <iostream> #include"header.h" int main() { t::inc(); std::cout << t::i << std::endl; // -> output is: 1 t::print_i(); // -> output is : 1 } The output of method 1 can be seen here. Method 2: Pre-C++17 Here we make use of the extern keyword so that the variable can have external linkage. main.cpp #include <iostream> #include"header.h" int main() { t::inc(); std::cout << t::i << std::endl; // -> output is: 1 t::print_i(); // -> output is : 1 } header.h #ifndef UNTITLED1_TEST_H #define UNTITLED1_TEST_H namespace t { extern int i;//note the keyword extern and no initializer here void inc() ; void print_i() ; } #endif Note I have removed added the static and inline keywords, and added the extern keyword. Now the variable has external linkage. Also, note that the initialization of t::i is done in header.cpp given below. header.cpp #include "header.h" #include <iostream> int t::i{}; //initialize t::i void t::inc() { t::i++; } void t::print_i() { std::cout << t::i << std::endl; } Output of the above program is: Demo 1 1 Also, do note that the keyword static has other meanings as well. But I have answered according to the given example code snippet.
71,169,533
71,169,600
Emplacing an std::pair of strings to an unordered map reusing the string's heap
I have an unordered map of string-pairs that i reference via a message id (key). Now I want to construct the string pair in place using the temporary string objects that the function receives, hence reusing the memory already allocated for the string on the heap. But I'm having difficulty wrapping my head around this construction. Here is what I came up with: std::unordered_map<int, std::pair<std::string, std::string>> data_map; void foo(int msg_id, std::string&& topic, std::string&& data) { data_map.emplace(std::piecewise_construct, std::forward_as_tuple(msg_id), std::forward_as_tuple(std::piecewise_construct, std::forward_as_tuple(topic), std::forward_as_tuple(data))); } My reasoning says that I need to construct a first pair for the map containing key and value of which the value must be created by another piecewise pair constructor to which I feed the r-value refs. It compiles but my gut feeling tells me something is off. Will I be able to reuse the allocated heap memory of the string like this?
Your construction is not using the move constructor to construct the new strings, thereby it is not reusing allocations. The names of variables are always lvalues. Therefore std::forward_as_tuple will forward topic and data as lvalue reference, causing use of the copy constructor for the strings. To pass rvalues, you need std::move. Also, since std::pair has a constructor which takes two arguments for the two pair elements, which are exactly the two strings you already have, you don't need the second piecewise construction: data_map.emplace(std::piecewise_construct, std::forward_as_tuple(msg_id), std::forward_as_tuple(std::move(topic), std::move(data)));
71,169,549
71,170,070
Getting wrong hex value from read function
Function gets valid data by 1 step, but when go to 2 step gets wrong hex data, what i`m doing wrong? stringstream getHexFromBuffer(char* buffer,short startFrom = 0, short to = 4) { int len = strlen(buffer); stringstream hexValue; for (size_t i = startFrom; i < to; i++) { hexValue << hex << (int)buffer[i]; } return hexValue; } bool big::openFile(std::string fName){ this->fileName = fName; ifstream file(fName.c_str(), ios::binary | ios::out | ios::ate); char* memblock; this->fileSize = file.tellg(); memblock = new char[16]; file.seekg(0, ios::beg); if (!file.is_open()) { file.close(); throw new exception("Файл не может быть открыт!"); } file.read(memblock, 16); string bigCheck = hexToASCII(getHexFromBuffer(memblock).str()); if (strcmp(bigCheck.c_str(), "BIGF") != 0) { throw new exception("Не .BIG архив!"); } this->fileType = bigCheck.c_str(); string bigSize = getHexFromBuffer(memblock, 4, 8).str(); //cout << getIntFromHexString(bigSize) << endl << this->fileSize ; file.close(); } First valid attempt Second not valid attempt Must be d0998100, but get ffffffd0ffffff99ffffff810 instead Full hex that i trying to get is 42 49 47 46 D0 99 81 00, maybe it helps
d0 is a negative 8 bit value in signed char. This is exact the same negative value ffffffd0 in int. For getting "d0" in output, cast the signed char to another unsigned type of the same size (1 byte) then cast the result to int: hexValue << hex << (int)(unsigned char)buffer[i]; hexValue << hex << (int)(uint8_t)buffer[i]; The first type cast keeps 8 bits in an unsigned type, a positive number, the second cast makes a positive int.
71,170,283
73,388,419
Creating two or more CEF browser windows
I have been suffering for two weeks, please help me: And I use the built-in CEF example - "cefsimple" - it works fine: https://bitbucket.org/chromiumembedded/cef/src/master/tests/cefsimple/?at=master The "cefsimple" example creates a browser window and opens the specified URL in it. But as soon as I add another browser window creation feature: CefBrowserHost::CreateBrowser(window_info, my_browser_handler_, "google.com", browser_settings, nullptr, nullptr); That's where the problems happen. The second browser window is being created, BUT a problem occurs - the two created windows seem to blink constantly, as if switching between each other very quickly. I tried the advice - install: window_info.ex_style = WS_EX_NOACTIVATE; But it doesn't help at all. Maybe someone has created more than one window browser in CEF ? What am I doing wrong ?
I've encounter this problem recently, and this may help you. In your native window proc, process WM_SETFOCUS with: if (!::GetFocus()) { // set cef focus; } Without call ::GetFocus(), two cef windows will blink constantly.
71,170,900
71,176,516
Display the whole file
I have an assessment about asking the user to enter his/her name and their desired score and display it. I have made progress but when I try to display all the text in the save file (I called scores.txt) it didn't print all out but instead just print the first line of the text file. Here the code: #include <iostream> #include <fstream> #include <string> #include <stdlib.h> using namespace std; int score; int highscore; string name; void menu() { cout << "1.Enter a score" << endl; cout << "2.Display scores" << endl; cout << "3.Exit" << endl; } void enterScore() { cout << "Enter your desired score: "; cin >> score; cout << "Please enter your name and seperate by a (_): "; cin.ignore(); getline(cin, name); } void displayScore() { cout << "Display scores: " << endl; } void exit() { } int main() { ofstream outFile("scores.txt", ios::app); ifstream inFile("scores.txt", ios::in); int choice; char yesOrNo; do { menu(); cout << "Enter your choice: "; cin >> choice; switch (choice) { case 1: enterScore(); outFile << name << ": " << score << endl; break; case 2: displayScore(); inFile >> name; inFile >> score; cout << name << " " << score << endl; break; case 3: exit(); break; default: cout << "Error!!!" << endl; break; } cout << "Would you like to try again? (y/n): "; cin >> yesOrNo; system("cls"); } while (yesOrNo == 'y'); return 0; } How can I display all the text in the file and is there a way to sort the score like a highscore board. Please help and I'm very thankful.
Try it like this: #include <iostream> #include <fstream> #include <string> #include <stdlib.h> using namespace std; int score; int highscore; string name; void menu() { cout << "1.Enter a score" << endl; cout << "2.Display scores" << endl; cout << "3.Exit" << endl; } void enterScore() { cout << "Enter your desired score: "; cin >> score; cout << "Please enter your name and seperate by a (_): "; cin.ignore(); getline(cin, name); } void displayScore() { cout << "Display scores: " << endl; } void exit() { } int main() { ofstream outFile("scores.txt", ios::app); ifstream inFile("scores.txt", ios::in); int choice; char yesOrNo; do { menu(); cout << "Enter your choice: "; cin >> choice; switch (choice) { case 1: enterScore(); outFile << name << ": " << score << endl; break; case 2: displayScore(); while(true){ inFile >> name; inFile >> score; cout << name << " " << score << endl; if(inFile.eof()) break; } break; case 3: exit(); break; default: cout << "Error!!!" << endl; break; } cout << "Would you like to try again? (y/n): "; cin >> yesOrNo; system("cls"); } while (yesOrNo == 'y'); return 0; }
71,171,613
71,221,231
C++ isdigit() Query for converting a char array to an int array
I am trying to convert an input character array, to an int array in c++. Inputs would be in a format like: 'M 911843 6', where the first value of the char array is a uppercase letter, which I convert to an ASCII value and -55. Edit: I should also mention I just want to use the iostream library The last value of the char array can be a letter or number also. I want to retain the exact number value of any input in the char array, which is why I convert to an ASCII value and -48, which retains the same number, but stored as an int value: I use the checkdigit() function to check if the char input is a number or not. The difficulty I am facing is that the input will always have a blank space at i[1] and i[8] (if we count i[0] as the first value) - so I try to give them an int value of 0 (int of a " " is 0) Upon several debugging attempts, I found that it is after the blank space is given a 0 value, the output in my for loop keeps outputting the wrong values, I suspect it has something to do with the isdigit() function in my for loop. If the spaces from M 911843 6 were removed, the int output is usually fine, e.g. a char input of M9118436 will return an int array of [22][9][1][1][8][4][3][6]. The output with spaces: [22][0][-183][-120][37][-118][-59][72][0][-55] Ideal output: [22][0][9][1][1][8][4][3][0][6] The code is listed below, any help or advice would be greatly appreciated, thanks!! #include <iostream> using namespace std; int main() { char a[10]; int z[10]; int i = 0; int r; //result of the isdigit check (0 or 1) cout << "in "; cin >> a; for (int i = 0; i < 10; i++) { r = isdigit(a[i]); if (r == 0) { if (i==1 || i==8) z[i] = 0; else z[i] = int(a[i]) - 55; } else { z[i] = int(a[i]) - 48; } } cout << z[0] << "\n" << z[1] << "\n"<< z[2]<< "\n" << z[3] << "\n"<< z[4] << "\n"<< z[5] << "\n"<< z[6] << "\n"<< z[7]<< "\n" << z[8] << "\n"<< z[9]; return 0; }
Just a follow on from Serge's answer which gave me a good understanding of how strings are read - I solved my problem using cin.getline() function.
71,171,739
71,185,780
Initialize nontrivial class members when created by PyObject_NEW
I have a Python object referring to a C++ object. Header: #define PY_SSIZE_T_CLEAN #include <Python.h> #include <structmember.h> typedef struct { PyObject_HEAD FrameBuffer frame_buffer; } PyFrameBuffer; extern PyTypeObject PyFrameBuffer_type; extern PyObject* PyFrameBuffer_NEW(size_t width, size_t height); The C++ FrameBuffer class is following: class FrameBuffer { public: explicit FrameBuffer(const size_t width, const size_t height); // ... private: size_t m_width; size_t m_height; std::vector<Pixel> m_pixels; }; Pixel is a simple class of few plain type elements. The PyFrameBuffer_NEW() function is following: PyObject* PyFrameBuffer_NEW(size_t width, size_t height) { auto* fb = (PyFrameBuffer*) PyObject_NEW(PyFrameBuffer, &PyFrameBuffer_type); if (fb != nullptr) { fb->frame_buffer = FrameBuffer(width, height); } return (PyObject*) fb; } This code crashs: fb->frame_buffer is allocated with undefined values (fb->frame_buffer.m_pixels.size() is undefined). During fb->frame_buffer assignment, there is a deallocation of an undefinied number of Pixel in m_pixels. And so, it crash. This code seems to works: /// ... if (fb != nullptr) { FrameBuffer fb_tmp(width, height); std::memcpy(&fb->frame_buffer, &fb_tmp, sizeof(FrameBuffer)); } // ... But I suspect this is not the proper way to solve this issue (I suspect Pixels in fb_tmp are desallocated outside the scope. What would the the proper way to solve this problem? Is there a commonly known approach on how to expose complex object in CPython?
I've successfully used code similar to typedef struct { PyObject_HEAD FrameBuffer *frame_buffer; } PyFrameBuffer; and then if (fb != nullptr) { fb->frame_buffer = new FrameBuffer( ... ); } But you have to account for deleting the object explicitly. You'll need to add a tp_dealloc() function to your PyFrameBuffer initialization that deletes the C++ FrameBuffer object: delete fb->frame_buffer; Also: When you use C++ to create a Python extension module, you're linking in your code's C++ runtime libraries. If more than one module uses C++, they all have to use the exact same C++ runtime libraries.
71,172,106
71,172,450
ifstream struct read (What's wrong with my code??)
I save struct array as binary. (fIn.write) and I read it using below code. std::ifstream fIn(LOG_PATH, std::ios::in|std::ios::binary); ... IAttackSave_t IAttackSave; while(fIn.read((char*)&IAttackSave, sizeof(IAttackSave_t))) { for(uint32 ulIdx = 0; ulIdx < ulCurLogCnt; ++ulIdx) { LIB_memcpy(Arr_IAttackSave[ulIdx], &IAttackSave, sizeof(IAttackSave_t)); } } But, (array) All of element in 'Arr_IAttackSave' has same struct !!!! What's wrong with my code?? Thanks ahead.
The outer loop reads elements one by one. The inner loop overwrites all elements of the array with the same element. After both loops finish, all elements have been overwritten with the element that was read last. Instead, you need something like this: for(uint32 ulIdx = 0; ulIdx < ulCurLogCnt; ++ulIdx) { if (!fIn.read((char*)&IAttackSave, sizeof(IAttackSave_t))) { break; } LIB_memcpy(Arr_IAttackSave[ulIdx], &IAttackSave, sizeof(IAttackSave_t)); }
71,172,147
71,172,643
How to create a folder with a dot in the name using std::filesystem?
There was a need to create a Windows directory with the name ".data". But when trying to create this path via std::filesystem:create_directory / create_directories, a folder is created in the directory above with an unclear name: E:\n¬6Љ P.S in the documentation for std::filesystem i found: dot: the file name consisting of a single dot character . is a directory name that refers to the current directory My code: ifstream Myfile; string line; char patht[MAX_PATH]; Myfile.open("dirs.lists"); if (Myfile.is_open()) { while (!Myfile.eof()) { while (std::getline(Myfile, line)) { sprintf(patht, "E:\\game\\%s", line); std::filesystem::create_directories(patht); } } } and dirs.lists contain: game\\modloader\\.data game\\modloader\\.profiles
You are passing the address of line to sprintf, not a string! Try sprintf(patht, "E:\\game\\%s", line.c_str());
71,172,554
71,177,196
How to Pass Vector of int into CUDA global function
I'm writing my first CUDA program and encounter a lot of issues, as my main programming language is not C++. In my console app I have a vector of int that holds a constant list of numbers. My code should create new vectors and check matches with the original constant vector. I don't know how to pass / copy pointers of a vector into the GPU device. I get this error message after I tries to convert my code from C# into C++ and work with the Kernel: "Error calling a host function("std::vector<int, ::std::allocator > ::vector()") from a global function("MagicSeedCUDA::bigCUDAJob") is not allowed" This is part of my code: std::vector<int> selectedList; FillA1(A1, "0152793281263155465283127699107744880041"); selectedList = A1; bigCUDAJob<< <640, 640, 640>> >(i, j, selectedList); __global__ void bigCUDAJob(int i, int j, std::vector<int> selectedList) { std::vector<int> tempList; // here comes code that adds numbers to tempList // code to find matches between tempList and the // parameter selectedList } How to modify my code so I won't get compiler errors? I can work with array of int as well.
I don't know how to pass / copy pointers of a vector into the GPU device First, remind yourself of how to pass memory that's not in an std::vector to a CUDA kernel. (Re)read the vectorAdd example program, part of NVIDIA's CUDA samples. cudaError_t status; std::vector<int> selectedList; // ... etc. ... int *selectedListOnDevice = NULL; std::size_t selectedListSizeInBytes = sizeof(int) * selectedList.size(); status = cudaMalloc((void **)&selectedListOnDevice, selectedListSizeInBytes); if (status != cudaSuccess) { /* handle error */ } cudaMemcpy(selectedListOnDevice, selectedList.data(), selectedListSizeInBytes); if (status != cudaSuccess) { /* handle error */ } // ... etc. ... // eventually: cudaFree(selectedListOnDevice); That's using the official CUDA runtime API. If, however, you use my CUDA API wrappers (which you absolutely don't have to), the above becomes: auto selectedListOnDevice = cuda::memory::make_unique<int[]>(selectedList.size()); cuda::memory::copy(selectedListOnDevice.get(), selectedList.data()); and you don't need to handle the errors yourself - on error, an exception will be thrown. Another alternative is to use NVIDIA's thrust library, which offers an std::vector-like class called a "device vector". This allows you to write: thrust::device_vector<int> selectedListOnDevice = selectedList; and it should "just work". I get this error message: Error calling a host function("std::vector<int, ::std::allocator > ::vector()") from a global function("MagicSeedCUDA::bigCUDAJob") is not allowed That issue is covered in Using std::vector in CUDA device code , as @paleonix mentioned. In a nutshell: You just cannot have std::vector appear in your __device__ or __global__ functions, at all, no matter how you try and write it. I'm writing my first CUDA program and encounter a lot of issues, as my main programming language is not C++. Then, regardless of your specific issue with an std::vector, you should take some time to study C++ programming. Alternatively, you could brush up on C programming, as you can write CUDA kernels which are C'ish rather than C++'ish; but C++'ish features are actually quite useful when writing kernels, not just on the host-side.
71,172,775
71,181,936
`glm::linearRand(-1.0f, 1.0f)`, gives more negative numbers than positive. Why is that? `rand` seems ok
I am using glm::linearRand(-1.0f, 1.0f) to generate random floating point numbers between -1 and 1. Afterwards, I output the percentage of numbers that are positive (0.0f or above). std::srand(time(0)); // Give glm a new seed uint32_t samples = 1000000000; uint32_t positive = 0; uint32_t negative = 0; for (uint32_t i = 0; i < samples; i++) { float rand = glm::linearRand(-1.0f, 1.0f); if (rand >= 0.0f) { positive++; } else { negative++; } } std::cout << "positive %: " << std::setprecision(6) << ((float)positive / samples) * 100 << std::endl; The percentage of positive numbers always ends up around 49.6%, no matter how often I run the program (with different seeds!). If I understand floating point numbers correctly, there are equally many between -1.0f and 0.0f as there are between 0.0f and 1.0f. So why does this program always generate more negative numbers than positive numbers? Note this test code provided by Bob__ (result of comments exchange between him, IkarusDeveloper and Marek R). This proves that rand is not problem this time, but there is some problem with floats rounding inside of glm::linearRand.
This is a bug in GLM. While the usual admonition about using % with rand is that the range doesn’t evenly divide RAND_MAX, this code opts for the more straightforward approach of reducing rand() modulo UINT8_MAX, so that 255 is never produced. Every random value is ultimately derived from combining several such bytes, so 127/255=49.8% of the values will be in the upper half (here, positive).
71,172,879
71,172,977
Misunderstanding with move constructor
I have such class, where I create a move constructor class Test { private: int m_a; public: Test(int val) { m_a = val; } Test (const Test &) {} // move constructor Test (Test && d) { std::cout << &m_a << std::endl; // Line X std::cout << &d.m_a << std::endl; } void print() { std::cout << m_a << std::endl; } }; I also create a function to test move constructor void fun(Test a) { return ; } Than in main function I create 2 objects of class above and call function to test move constructor int main() { Test a {50}; Test b {100}; fun(a); fun(std::move(a)); fun(b); fun(std::move(b)); return 0; } When I looked at the output, I was surprised, because the address of o m_a variable in line X has same address for both objects. 0x7ffc40d37bb4 // look at this 0x7ffc40d37bac 0x7ffc40d37bb4 // look at this 0x7ffc40d37bb0 How is it possible ? It's not static member, what is going on ? Compiler optimization or what ?
Each time fun(Test a) is invoked, an instance of Test is created on the stack. Each time fun() returns, the stack frame is freed. So when invoked twice in a row, the chance is great that you get an instance of Test created at exact same location on the stack. If you wanted to take Test by reference, it should be void fun(Test&& a).
71,174,313
71,174,348
How to have a templated function require its argument be passed by rvalue reference?
Because of the confusing syntax of forwarding references and rvalue references, it's not clear to me how I would write a function that takes some type, T, by rvalue reference. That is, while template <typename T> void foo(T x); takes x by value and template <typename T> void foo(T& x); by reference, and template <typename T> void foo(T* x); by pointer, when we say template <typename T> void foo(T&& x); suddenly it's taking x by forwarding reference not by rvalue reference. What's the Right Way to say foo takes x by forwarding reference? Like this? template <typename T> void foo(T&& x) { static_assert(std::is_rvalue_reference_v<T&&>, "x must be an rvalue reference.");
template<class T> void f(T &&) requires(!std::is_lvalue_reference_v<T>);
71,174,500
71,174,826
A more elegant way of writing repetitive code (template)?
I have a block of code in which there are multiple times the same kind of operations: void fn() { if (params[0].count("VARIABLE_1")) { STRUCT.VARIABLE_1= boost::lexical_cast<VARIABLE_1_TYPE>(params[0].at("VARIABLE_1")); } if (params[0].count("VARIABLE_2")) { STRUCT.VARIABLE_2 = boost::lexical_cast<VARIABLE_2_TYPE>(params[0].at("VARIABLE_2")); } // many times this kind of if (...) with different parameters } Pretty sure there's a more elegant way of writing this in modern C++ (11, 17, 20) using templates I assume. Any idea? Edit: only the VARIABLE_n and VARIABLE_n_TYPE change, params[0] stays as is.
Because you want something as both an identifier in code, and as a string literal, you either repeat yourself template<typename T, typename Map> void extract_param(T & t, const Map & map, std::string name) { if (auto it = params.find(name); it != params.end()) { t = boost::lexical_cast<T>(*it); } } void fn() { extract_param(STRUCT.VARIABLE, params[0], "VARIABLE"); // ... } or use a macro #define EXTRACT_PARAM(Key) if (auto it = params[0].find(#Key); it != params[0].end()) { \ STRUCT.Key = boost::lexical_cast<decltype(STRUCT.Key)>(*it); \ } void fn() { EXTRACT_PARAM(VARIABLE) // ... } #UNDEF EXTRACT_PARAM
71,175,636
71,189,318
What shell does std::system use?
TL;DR; I guess the shell that std::system use, is sh. But, I'm not sure. I tried to print the shell, using this code: std::system("echo $SHELL"), and the output was /bin/bash. It was weird for me. So, I wanted to see, what happens if I do that in sh? And, the same output: /bin/bash. Also, if I use a command like SHELL="/usr/bin/something", to set the SHELL variable to another string, it will print the new string that I set to it (/usr/bin/something), and it looks it's not a good way to see what shell it's using. Then, I tried to check it, using the ps command, and the output was: bash, a.out, ps. It was weird to see bash in this list. So, I created a custom shell, and change the shell in gnome-terminal to it: #include <iostream> int main() { std::string input; while (true) { std::string command; std::getline(std::cin, command); std::system(command.c_str()); } } Now, it's easier to test, and I think, the results is better. Then, I tried to test the ps command again, but in the custom shell, and the results was: test_shell, ps. It was weird again. How the shell isn't sh, nor bash? And, the final test I did was: echo $0. And, the results was sh, in both custom shell, and normal program. Edit It seems like /bin/sh is linked to /bin/bash (ll /bin/sh command's output is /bin/sh -> bash), and actually, it seems like the only difference between sh and bash is filename, and the files's contents are the same. I checked the difference between these files with diff command too: $ xxd /bin/sh > sh $ xxd /bin/bash > bash $ diff sh bash (+ Yes, $SHELL doesn't means the running shell (I didn't know that when I was testing, and I just wanted to see what happens))
The GNU sources (https://github.com/lattera/glibc/blob/master/sysdeps/posix/system.c) say /bin/sh So, whatever /bin/sh is hardlinked to is the shell invoked by std::system() on Linux. (This is correct, as /bin/sh is expected to be linked to a sane shell capable of doing things with the system.)
71,175,935
71,178,060
How to call function by given pointer using raw data (bytes) on runtime (instead of casting to compile-time defined function) in C/C++
Imagine we have an untyped raw function pointer void * my_func = ...; // get from DLL for example How to call my_func with specif data (and get return value), if the size of all parameters together and the size of return type could be known only on the runtime. For example I need to implement the following interface: void call_func(void * func, size_t return_type_size, size_t parameters_size, void * return_data, void * parameters_data){ // 1. put data from parameters_data onto the stack frame // 2. call func // 3. put data from function call into return_data } so if we have a function like double my_double_func(int a, char b) the usage of call_func will be the following // get from DLL for example void * my_func = <recived on runtime>; // with my_double_func should be sizeof(double) = 8 size_t return_data_size = <recived on runtime>; // with my_double_func should be sizeof(int) + sizeof(char) ~ 5 size_t parameters_data_size = <recived on runtime>; char * return_data = new char[return_data_size]; char * parameters_data = new char[parameters_data_size]; call_func(my_func, return_data_size, parameters_data_size, return_data, parameters_data); // so return_data now contains the value of double // and could be serialized for example It is prohibited to do the following! (as I cannot use exact type on compile time) double value = ( (double(*)(int,char)) my_func)(a, b); P.S. Also it is acceptable if parameters are not in a single block of memory
This is exactly what I searched for linux.die.net/man/3/ffi_call: The ffi_call function provides a simple mechanism for invoking a function without requiring knowledge of the function's interface at compile time. fn is called with the values retrieved from the pointers in the avalue array. The return value from fn is FFI library is cross-platform.
71,175,941
71,176,239
TI ARM CLANG wont resolve symbol even though objdump shows its there
I am trying to compile my code on CCS(Code composer studio) using TI ARM CLANG compiler. I am trying to implement Ethernet fucntionality which uses TI's enet SDK I call a fucntion in my main which is in the enet SDK but the comiler is throwing error unresolved symbol Enet_initOsalCfg(EnetOsal_Cfg_s, first referenced in *) I have added its library in the linker tab To confirm i am not doing something stuipd I use same compilers objdump to disassemble the library and I think if I am not mistaken the dump clearly shows the symbol is present. Function I called in main() has the declaration: void Enet_initOsalCfg(EnetOsal_Cfg *osalCfg); Following is a snippet from the objdump having same name as my function: Disassembly of section .text.Enet_initOsalCfg: 00000000 <Enet_initOsalCfg>: 0: 00 48 2d e9 push {r11, lr} 4: 08 d0 4d e2 sub sp, sp, #8 8: 04 00 8d e5 str r0, [sp, #4] c: 04 00 9d e5 ldr r0, [sp, #4] 10: fe ff ff eb bl #-8 <Enet_initOsalCfg+0x10> 14: 08 d0 8d e2 add sp, sp, #8 18: 00 88 bd e8 pop {r11, pc} Disassembly of section .rel.text.Enet_initOsalCfg: 00000000 <.rel.text.Enet_initOsalCfg>: 0: 10 00 00 00 andeq r0, r0, r0, lsl r0 4: 1c 9c 00 00 andeq r9, r0, r12, lsl r12 Disassembly of section .ARM.exidx.text.Enet_initOsalCfg: 00000000 <.ARM.exidx.text.Enet_initOsalCfg>: 0: 00 00 00 00 andeq r0, r0, r0 4: 01 00 00 00 andeq r0, r0, r1 Disassembly of section .rel.ARM.exidx.text.Enet_initOsalCfg: 00000000 <.rel.ARM.exidx.text.Enet_initOsalCfg>: 0: 00 00 00 00 andeq r0, r0, r0 4: 2a 72 00 00 andeq r7, r0, r10, lsr #4 What am I missing here? Excuse me if I am being stupid
Big oops our friend in the comments found my problem. I forgot extern "C" sorry for being stupid I was scratching my head on this since 4 hours, my aplologies :P
71,176,032
71,176,069
return type deduction of lambda function not working
Why does the following code not compile? Why do I have to tell the compiler that the passed function pointer returns a double? (It works if one explicitly calls call<double>()!) template<typename T> void call(T (*const _pF)(void)) { } int main(int, char**) { call( [](void) -> double { return 1.0; } ); }
Because the implicit conversion (from lambda to function pointer) won't be considered in template argument deduction, the template parameter T can't be deduced and the invocation fails. Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later. Except for specifying template argument double explicitly like call<double>(...);, you can convert the lambda to function pointer explicitly, e.g. call( static_cast<double(*)()>( [](void) -> double { return 1.0; }) ); or call( +[](void) -> double { return 1.0; } );
71,176,278
71,176,607
Create a copy on demand
Is there an idiomatic way to invoke the creation of a copy in an expression? For example say I have a function declared as: template <class T> void foo(T&& arg) { } Now I need to call foo with a copy of my object: MyType object; foo(object); As written above, I will have a call on void foo(MyType& arg), but I don't want to pass a reference to my object. I also want to avoid moving from my object in order to trigger deduction of void foo(MyType&& arg). What I want to do is create a copy of object at the call site of foo: foo(copy(object)); I have tried the following things: Creating a copy function myself, to generate objects: template <class T> T copy(T arg) { return arg; } Copy by means of forward casting: foo(std::forward<MyObject>(object)), but don't think it works in generic code Explicitly copying by creating a local variable to pass to foo: MyType copy(object); foo(std::move(copy)); Is there a standard library facility or a "generally accepted" way to do this? EDIT: As mentioned in the comments, foo(MyType(object)) is always a solution. I'm asking whether there is an idiomatic way because in general spelling out the type in this case can be less safe: // Converting constructors may create spurious problems: foo(AnotherType(object)); // This can compile even if decltype(object) != AnotherType whereas a solution that requires no attention in specifying the type is always safe: foo(copy(object));
You can build a decay-copy function yourself: template <class T> constexpr std::decay_t<T> decay_copy(T&& v) { return std::forward<T>(v); } then foo(decay_copy(object)); It's worth noting that you can also use auto(x) to get language-supported decay-copy in C++23: foo(auto(object)); Demo See P0849 for more details on auto(x).
71,176,442
71,205,709
How to remove the distance between the QTabBar scroller buttons?
Please tell me why there is a distance between the QTabBar scroller buttons with a small width of the scroller buttons and how can this be fixed? In this case, I have the following in the style sheet: QTabBar::scroller { width: 6px; } At the same time, the whole paradox is that in a pure example there is no distance between the buttons and I can't understand how this could have gone wrong in my example. Even the type of this indentation is unclear: it is neither a widget neither a layout, it is not clear what kind of object it is.
It's because of an outdated version of Qt.
71,176,554
71,226,982
PyTorch C++ Frontend: Registering New Modules and using them during Forward
I am creating a model that is empty like so: struct TestNet : torch::nn::Module { TestNet() { } torch::Tensor Forward(torch::Tensor x) { return x; } }; I then register new modules to the model: auto net = std::make_shared<TestNet>(); torch::nn::ModuleHolder<ConvLayer> conv(1, 1, 3, 1, 1); net->register_module("conv1", conv); Where ConvLayer is a Module with a convolutional layer: struct ConvLayer : torch::nn::Module { ConvLayer() {} ConvLayer(int in_ch, int out_ch, int kernel, int pad, int stride) : conv1(torch::nn::Conv2dOptions(in_ch, out_ch, kernel) .stride(stride) .padding(pad) .bias(false)) { register_module("Conv1", conv1); } torch::Tensor Forward(torch::Tensor x) { return conv1(x); } torch::nn::Conv2d conv1{ nullptr }; }; I can print out the parameters of TestNet now and see the convolutional layer, however I can not utilize it in a forward pass. What am I missing to do this?
I found a way to do this using torch::nn::Sequential, hope this helps anyone else: struct TestNet2 : torch::nn::Module { TestNet2() { layers = register_module("layers", torch::nn::Sequential()); } template <typename T> void sequentialLayer(T Layer) { layers->push_back(Layer); } torch::Tensor Forward(torch::Tensor x) { return layers->forward(x); } torch::nn::Sequential layers; }; ... auto net = std::unique_ptr<TestNet2>(); auto convLayer = torch::nn::Conv2d(torch::nn::Conv2dOptions(1, 1, 3) .stride(1) .padding(1) .bias(false)); net->sequentialLayer(convLayer);
71,176,946
71,177,140
C++ fmtlib: "Undefined reference" error after building and #include <> this library
I downloaded the library from https://github.com/fmtlib/fmt and then executed the following commands from official documentation https://fmt.dev/latest/usage.html: mkdir build cd build cmake .. sudo make install The commands were executed without errors. The final output of the sudo make install command: Install the project... -- Install configuration: "Release" -- Installing: /usr/local/lib/libfmt.a -- Installing: /usr/local/include/fmt/args.h -- Installing: /usr/local/include/fmt/chrono.h -- Installing: /usr/local/include/fmt/color.h -- Installing: /usr/local/include/fmt/compile.h -- Installing: /usr/local/include/fmt/core.h -- Installing: /usr/local/include/fmt/format.h -- Installing: /usr/local/include/fmt/format-inl.h -- Installing: /usr/local/include/fmt/locale.h -- Installing: /usr/local/include/fmt/os.h -- Installing: /usr/local/include/fmt/ostream.h -- Installing: /usr/local/include/fmt/printf.h -- Installing: /usr/local/include/fmt/ranges.h -- Installing: /usr/local/include/fmt/xchar.h -- Installing: /usr/local/lib/cmake/fmt/fmt-config.cmake -- Installing: /usr/local/lib/cmake/fmt/fmt-config-version.cmake -- Installing: /usr/local/lib/cmake/fmt/fmt-targets.cmake -- Installing: /usr/local/lib/cmake/fmt/fmt-targets-release.cmake -- Installing: /usr/local/lib/pkgconfig/fmt.pc I next created the file main.cpp with the following content: #include <fmt/core.h> int main() { fmt::print("Hello"); return 0; } And compiled it with the command g++ main.cpp -o main. However, the compilation results in the following error: /usr/bin/ld: /tmp/ccJ3FzHH.o: in the function «main»: main.cpp:(.text+0x8a): undefined reference to «fmt::v8::vprint(fmt::v8::basic_string_view<char>, fmt::v8::basic_format_args<fmt::v8::basic_format_context<fmt::v8::appender, char> >)» collect2: error: ld returned 1 exit status I am using Ubuntu 20.04
Adding the argument -lfmt to the compilation command solves the issue. -l<name> arguments generally stand for including the library <name> into the compilation (see GCC documentation) The command thus looks as follows: $ g++ main.cpp -lfmt -o main
71,177,591
71,177,780
Problem with IF condition and && OPERATOR
i have encountered a major problem in my code that, when i hits 1 and j is 5, although, the boolean function returns False, the IF statement still manage to operate. #include <iostream> using namespace std; #include <string> using namespace std; bool checkSym(string s, int left, int right) { if (left >= right) return true; else { if (int(s[left]) != int(s[right])) return false; else { checkSym(s, left + 1, right - 1); } } } int main() { // TODO string s, c, d; s = "babadad"; int max = 0; int n = s.length(); for (int i = 0; n - i >= max; i++) { c = ""; for (int j = max; j <= n - i; j++) { c = s.substr(i, j); if (checkSym(c, 0, j - 1) && j > max) { max = j; d = c; } } } cout << d; }
The code looks unreadable. Nevertheless at least this function bool checkSym(string s, int left, int right) { if (left >= right) return true; else { if (int(s[left]) != int(s[right])) return false; else { checkSym(s, left + 1, right - 1); } } } can invoke undefined behavior because it returns nothing in this code snippet else { checkSym(s, left + 1, right - 1); } You need to write else { return checkSym(s, left + 1, right - 1); } Also it is unclear why there is used explicit casting to the type int if (int(s[left]) != int(s[right])) instead of just writing if ( s[left] != s[right])
71,177,615
71,182,017
String timestamp give unrealistic date
I have a ridiculous problem but I can't figure out... I juste want to convert a timestamp string to a human readable date but the only date I have is completely wrong. #include <iostream> #include <string> #include <stdio.h> #include <ctime> int main() { char buf[80]; std::time_t epoch = std::atol("1645128077111"); strftime(buf, sizeof(buf), "%d-%m-%Y %H:%M:%S %Z", std::localtime(&epoch)); std::cout << buf << std::endl; // Wanted value is // GMT: Thursday 17 February 2022 20:01:17.111 // OR // Your time zone: Thursday 17 February 2022 21:01:17.111 GMT+01:00 } But my output is 13-01-54102 06:25:11 CET which is completely wrong ! I'm sure is something stupid... But I can't find it so if anybody has the answer I would be grateful. Thanks for all :)
Fwiw, in C++20: #include <chrono> #include <cstdlib> #include <format> #include <iostream> int main() { using namespace std; using namespace std::chrono; sys_time epoch{milliseconds{atoll("1645128077111")}}; cout << format("{:%Z: %A %e %B %Y %T}", epoch) << '\n'; } Output: UTC: Thursday 17 February 2022 20:01:17.111 Not available on all platforms yet. Encourage your vendor to catch up. :-)
71,177,711
71,178,356
How to read from a file that has numbers in the beginning of each line of the string and extract numbers as an idx then store in a vector. Using C++
Hello I'm working on a school project and I'm trying to read from a file with these contents: the idx of question, the corresponding concept 1 Arrays Hold Multiple Values 1 Pointer Variables 2 Arrays as Function Arguments 3 Comparing Pointers 4 Pointer Variables 5 Pointer Variables 6 Initializing Pointers 7 Pointers as Function Parameters 8 Arrays as Function Arguments 8 Pointer Variables 9 Arrays Hold Multiple Values 10 Pointer Variables The goal is to store the numbers on the beginning of the string into a vector container to hold its values along with the rest of the string as the corresponding concepts. Note: Each number represents a question in a quiz and it may include more than one concept, which is separated in a different line in the file. So mapping the two contents into a string with the same number 1 for example is totally fine. I tried 2d vector and 1d vector but my problem is I don't know how I can split the string and detect the integers in the beginning also with two or three digits integers the problem will be more complex. Please any help will be much appreciated!!!! Here what I tried: void MapQC::setMapQC() { string line; string idxString; fstream inFile; int numOfLines = 0; int idx; inFile.open("database/map-question-concept.txt", ios::in); if (inFile.is_open()) { while (!inFile.eof()) { getline(inFile, line); vector<string> row; for (int i = 0; i <= numOfLines; i++) { if (getline(inFile, line, ' ')) { // cout << line << endl; row.push_back(line); } } mapQCVec.push_back(row); numOfLines ++; cout <<"row at: " << row[1] << endl; } } inFile.close(); }
This is not the cleanest solution, but it should get you started. The following separates the numerals at the beginning of each line from other content: // for each line string string idxStr; string lineWithoutIdx; for (const char& c : line) { if (isdigit(c)) { idxStr.push_back(c); } else { lineWithoutIdx.push_back(c); } } const int idx = atoi(idxStr.c_str()); // numbers-string to int // use containers of your choice, e.g. std::vector lineIndices.push_back(idx); lineContents.push_back(lineWithoutIdx); Each line will have its own entry in each container, then you can filter/merge duplicates, or access a specific string in lineContents by a number in lineIndices. Note that this does NOT check if numbers are within the text, but assumes they are at the beginning of each line, as per your example.
71,177,855
71,179,360
Leetcode: Time limit exceeded, Longest palindromic substring
I am wondering how to optimize my solution to the LeetCode question: 5. Longest palindromic substring: Given a string s, return the longest palindromic substring in s. I get Time Limit exceeded on really long strings (up to 1000 characters), but on the other hand, using the same long string on my terminal gives me the correct answer instantly. Here is a string on which I get the error: "zudfweormatjycujjirzjpyrmaxurectxrtqedmmgergwdvjmjtstdhcihacqnothgttgqfywcpgnuvwglvfiuxteopoyizgehkwuvvkqxbnufkcbodlhdmbqyghkojrgokpwdhtdrwmvdegwycecrgjvuexlguayzcammupgeskrvpthrmwqaqsdcgycdupykppiyhwzwcplivjnnvwhqkkxildtyjltklcokcrgqnnwzzeuqioyahqpuskkpbxhvzvqyhlegmoviogzwuiqahiouhnecjwysmtarjjdjqdrkljawzasriouuiqkcwwqsxifbndjmyprdozhwaoibpqrthpcjphgsfbeqrqqoqiqqdicvybzxhklehzzapbvcyleljawowluqgxxwlrymzojshlwkmzwpixgfjljkmwdtjeabgyrpbqyyykmoaqdambpkyyvukalbrzoyoufjqeftniddsfqnilxlplselqatdgjziphvrbokofvuerpsvqmzakbyzxtxvyanvjpfyvyiivqusfrsufjanmfibgrkwtiuoykiavpbqeyfsuteuxxjiyxvlvgmehycdvxdorpepmsinvmyzeqeiikajopqedyopirmhymozernxzaueljjrhcsofwyddkpnvcvzixdjknikyhzmstvbducjcoyoeoaqruuewclzqqqxzpgykrkygxnmlsrjudoaejxkipkgmcoqtxhelvsizgdwdyjwuumazxfstoaxeqqxoqezakdqjwpkrbldpcbbxexquqrznavcrprnydufsidakvrpuzgfisdxreldbqfizngtrilnbqboxwmwienlkmmiuifrvytukcqcpeqdwwucymgvyrektsnfijdcdoawbcwkkjkqwzffnuqituihjaklvthulmcjrhqcyzvekzqlxgddjoir" Below you can find my solution to the problem where i use two functions. ispalindrome (boolean) to check wheather a given string is a palindrome. longestpalindrome(): The algorithm that uses sliding window to check wheather the string provdided is the longest palindrome. class Solution { public: bool ispalindrome(string s) { int i = 0, j = s.size() - 1; while(i <= j){ if(s[i] != s[j]){ return false; } i++; j--; } return true; } string longestPalindrome(string s) { int window_size = s.size() - 1; int left = 0, right = window_size; string tmp_str = ""; while (right < s.size()) { tmp_str.append(s.begin() + left, s.begin() + right + 1); if (ispalindrome(tmp_str)) { return tmp_str; } if((right + 1) < s.size()) { tmp_str = ""; right++; left++; } else { tmp_str = ""; window_size--; right = window_size; left = 0; } } return s; } };
The algorithm loses a lot of time by working from the outside inwards. Realise that a palindrome has a "center" (on, or between neighboring indexes), and your algorithm will often look for palindromes using the same center but with decreasing sizes. You could reduce work by working from the inside out, i.e. select all possible centers, and see what the largest palindrome is that has that center. This way you will only do one scan per center. So, iterate over all possible centers (both on indexes, and between two indexes), and see which is the largest palindrome you can find this way. You can then further optimise by starting with centers in the middle of the string (since they can potentially offer the largest strings), and then "fan" your center away from the middle of the string, until you come too close to an outer end of the string, making it impossible to improve on the longest palindrome that you had already found. Finally, avoid creating new strings, and just work with indexes (left, right, ...etc), and only really create a string when you already have identified the start/end index of the largest palindrome.
71,178,173
71,178,380
CMake: Create DLL including dependencies instead of separate dll's
Im writing a SDK for Windows and Mac OS in C++, and im using CMake. On windows, I'd like the compiled DLL to contain all necessary dependencies, instead of having separate DLLs for all third party libraries im using. Here are the relevant sections of the MakeFile: find_package(OpenSSL REQUIRED) find_package(CURL CONFIG REQUIRED) find_package(nlohmann_json 3.2.0 REQUIRED) find_package(spdlog REQUIRED) find_package(unofficial-sqlite3 CONFIG REQUIRED) .... add_library(${PROJECT_NAME} SHARED ${SRC_FILES}) ... target_link_libraries(${PROJECT_NAME} PRIVATE OpenSSL::Crypto CURL::libcurl nlohmann_json::nlohmann_json spdlog::spdlog_header_only unofficial::sqlite3::sqlite3) This generates the following separate DLLs: fmt.dll libcrypto-1_1.dll libcurl.dll sqlite3.dll zlib1.dll Is it possible to create a library containing all dependecies, like it is on Mac OS with the generated dylib?
I'm using Vcpkg for simplicity but you should compile your dependencies as static libraries instead of shared. If you're using vcpkg you can install the dependencies as static like such vcpkg.exe install openssl:x86-windows-static Make sure you run CMake with VCPKG_TARGET_TRIPLET set to x86-windows-static or whatever platform you're on. As you can see example.dll is now statically linked to OpenSSL. Cheers
71,178,599
71,178,823
C++Builder correct way to Load string from ressources
I am new in either c++, and c++builder(11 v-28), i have put in ressources a text file(via projet->Ressources and Images), but i can't find any method to retrieve my text from ressources, LoadStr(..) function reclaim a numeric identifier that i can't found or how to get it.
Using C++ Builder you can use functions in the RTL to help you. When you put the large text file into the resources you would have given it a type and Id. Normally for an embedded file the type would by RT_RCDATA. (I haven't checked this code at all so it probably won't compile, but should give you a pointer) TStream * function TMyForm::GetResourceStream(UnicodeString szResName); { TStream: rc; id: int; rc=nil; id=StrToIntDef(szResName, 0); if(id > 0) { rc = TResourceStream::CreateFromID(hInstance, id, RT_RCDATA); } return(rc); } Th hInstance is the Instance of your program that is passed to WinMain. Once you have the TStream you can read from it. You could populate a TStringList for example.
71,178,682
71,178,790
understand how char works in c++
I am a C++ newbie. Although many similar questions have been asked and answered, I still find these concepts confusing. I know char c='a' // declare a single char c and assign value 'a' to it char * str = "Test"; // declare a char pointer and pointing content str, // thus the content can't be modified via point str char str1[] = "Test"; // declare a char array str1 and assign "Test" to it // thus str1 owns the data and can modify it my first question is char * str creates a pointer, how does char * str = "Test"; work? assign a string literal to a pointer? It doesn't make sense to me although it is perfectly legal, I think we can only assign an address to a pointer, however "Test" is a string literal not an address. Second question is how come the following code prints out "Test" twice in a row? char str2[] = {'T','e','s','t'}; // is this line legal? // intializing a char array with initilizer list, seems to be okay to me cout<<str2<<endl; // prints out "TestTest" why cout<<str2<<endl; prints out "TestTest"?
char * str = "Test"; is not allowed in C++. A string literal can only be pointed to by a pointer to const. You would need const char * str = "Test";. If your compiler accepts char * str = "Test"; it is likely outdated. This conversion has not been allowed since C++11 (which came out over 10 years ago). how does char * str = "Test"; work? String literals are implicitly convertible to a pointer to the start of the literal. In C++ arrays are implicitly convertible to pointer to their first element. For example int x[10] is implicitly convertible to int*, the conversion results in &(x[0]). This applies to string literals, their type is a const array of characters (const char[]). how come the following code prints out "Test" twice in a row? In C++ most features related to character strings assume the string is null terminated, which is implied in string literals. You would need {'T','e','s','t','\0'} to be equivalent to "Test".
71,178,849
71,178,949
fmt linking for dummies
I'd like to make a python-like dynamic integer class in C++ as an experiment. It requires me to change many integers to string types. As in here: https://www.zverovich.net/2013/09/07/integer-to-string-conversion-in-cplusplus.html it states that fmt format_int will be best for that kind of job. So I installed fmt with command sudo apt-get install libfmt-dev I added a header #include <fmt/format.h> Used it in a simple test main int main() { std::cout<<fmt::format_int(124236695253045068).str(); } And tried to compile with g++ -lfmt -std=c++17 dynamic\ mem.cc Output of the compiler is as follows: /usr/bin/ld: /tmp/ccLBcSNm.o: in function `fmt::v6::format_int::format_decimal(unsigned long long)': dynamic mem.cc:(.text._ZN3fmt2v610format_int14format_decimalEy[_ZN3fmt2v610format_int14format_decimalEy]+0x94): undefined reference to `fmt::v6::internal::basic_data<void>::digits' /usr/bin/ld: dynamic mem.cc:(.text._ZN3fmt2v610format_int14format_decimalEy[_ZN3fmt2v610format_int14format_decimalEy]+0xad): undefined reference to `fmt::v6::internal::basic_data<void>::digits' /usr/bin/ld: dynamic mem.cc:(.text._ZN3fmt2v610format_int14format_decimalEy[_ZN3fmt2v610format_int14format_decimalEy]+0xfa): undefined reference to `fmt::v6::internal::basic_data<void>::digits' /usr/bin/ld: dynamic mem.cc:(.text._ZN3fmt2v610format_int14format_decimalEy[_ZN3fmt2v610format_int14format_decimalEy]+0x113): undefined reference to `fmt::v6::internal::basic_data<void>::digits' /usr/bin/ld: /tmp/ccLBcSNm.o: in function `std::make_unsigned<long>::type fmt::v6::internal::to_unsigned<long>(long)': dynamic mem.cc:(.text._ZN3fmt2v68internal11to_unsignedIlEENSt13make_unsignedIT_E4typeES4_[_ZN3fmt2v68internal11to_unsignedIlEENSt13make_unsignedIT_E4typeES4_]+0x2b): undefined reference to `fmt::v6::internal::assert_fail(char const*, int, char const*)' collect2: error: ld returned 1 exit status Do you have any ideas what went wrong? I don't usually link non-standard libraries so I don't have any idea what to do about it.
Use $ g++ -std=c++17 dynamic\ mem.cc -lfmt fmt is provided as a static library (.a). With those, the order is important as the linker takes out of a library only the objects which are needed to provide symbols to other objects or libraries which precede them in the command line. If you start with a library, there is only main which is missing and usually libraries don't provide main, so they are ignored. When putting the library after your source code, the symbols missing in your code are searched in the library. (In case of circular dependencies, you may even have to provide a library several times)
71,179,122
71,180,892
Running pip install twice to see changes ("developer mode") -- second install fails but first works
I am wondering how to use pip to develop a Python package which is going through many revisions rapidly. My work flow is to write C++ code, compile and install with pip install and test my code. Then, I would like to change some underlying C++ code, recompile and reinstall with pip, test the new feature, change something else, go back etc. until my package is ready. Why did pip install ./cmake_example work well the first time but when making changes to the code, reinstalling with recompiling produced an error? I just re-ran the command pip install ./cmake_example. I changed a single line of C++ code in an innocuous way (adding +1 in the 'add' function just to see if I can change code and recompile) and the code compiled fine in my IDE without pip. My basic idea was to use pip following this method to avoid having to hackishly insert my shared object into some python directory each time I make a change. I used the cmake_example from pybind here and followed the steps and did pip install ./cmake_example and it worked very well. I ran the example fine in a Python console. Then, I changed some code (just added +1 to the adding function), so nothing substantial and wanted to re-install the package. I then got this error: Building wheels for collected packages: cmake-example Building wheel for cmake-example (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for cmake-example (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [65 lines of output] running bdist_wheel running build running build_ext CMake Error at CMakeLists.txt:2 (project): Running '/tmp/pip-build-env-q_8_pyjk/overlay/bin/ninja' '--version' failed with: No such file or directory and ERROR: Could not build wheels for cmake-example, which is required to install pyproject.toml-based projects I have tried pip uninstall cmake_example and then reinstall but to no avail. The upgrade function did not work either. Does pip change something in the project folder? PS: The makers of pybind11 also provide a scikit example here where removing the cache for repeated builds is not necessary. The cmake_example seems to be intended for legacy projects that do not use the cmake extension scikit. So if the structure of the cmake_example is essential to the project, removal of the cache is the only way to go.
I found that deleting the build directory inside the cmake_example directory resolved the problem and pip install ./cmake_example worked again as it did the first time. You can combine the two commands: rm -rf ./cmake_example/build && pip install ./cmake_example Looking a little closer, (for me) it was sufficient to delete cmake_example/temp.linux-x86_64-3.8/CMakeCache.txt. I suspect the lines //Program used to build from build.ninja files. CMAKE_MAKE_PROGRAM:FILEPATH=/tmp/pip-build-env-yqopewjn/overlay/bin/ninja inside CMakeCache.txt mean that cmake caches the path to the ninja executable, but the second time around the temporary path is different, so it can no longer be found where cmake expects it.
71,180,130
71,180,230
Why don't I have to specify that the result of a fortran function is being passed by value to my C++ program?
I am learning about fortran C++ interoperability. In this case I was trying to write a 'wrapper' function (f_mult_wrapper) to interface between my 'pure' fortran function (f_mult) and C++. The function is defined in my C code as double f_mult_by_wrapper(double i, double j); and called like double u=f_mult_by_wrapper(w,r); I know I must specify that the input arguments in f_mult_wrapper are being passed by value from C, and that fortran usually passes by reference. But the compiler gives me an error when I try to specify that the result is being passed by value: A dummy argument name is required in this context. The code works together as written, but I don't exactly understand why. module type_example use :: iso_c_binding function f_mult(i,j) result(k) ! use fortran intrinsic types real:: i,j,k k = i*j; end function function f_mult_wrapper(aw,bw) result(cw) bind(c,name="f_mult_by_wrapper"); real(c_double), VALUE :: aw ! use c binding types. passed by value real(c_double), VALUE :: bw real(c_double) :: cw real :: a,b,c a = aw b = bw c = cw c = f_mult(a,b) cw = c end function end module
Function results are simply not function arguments/parameters. They are passed differently and the exact mechanism depends on the ABI (calling conventions) and their type. In some ABIs, results are passed on the stack. In other ABIs, they are passed using registers. That concerns simple types that can actually fit into registers. More complex objects may be passed using pointers (on the stack or in registers). The by value/by reference distinction distinguishes, whether the value of the argument is passed on the stack/in the register directly, or indirectly using a pointer. It does not concern function return values. There are simpler functions that can be C-interoperable and other Fortran functions that cannot be interoperable, e.g. functions returning arrays. Such Fortran-specific functions are implemented in a compiler-specific way. Often, a hidden argument is being passed. Such a hidden argument may contain a pointer and may be passed using a register or using the stack. The details are again dependent on the specific ABI. For the calling conventions to the most common x86 architecture, see https://en.wikipedia.org/wiki/X86_calling_conventions There are several different variations for 32 bit and for 64 bit.
71,180,394
71,182,035
Armadillo: Inefficient chaining of .t()
consider the following two ways of doing the same thing. arma::Mat<double> B(5000,5000,arma::fill::randu); arma::Mat<double> C(5000,500, arma::fill::randu); Okay two dense matrices in memory. Now I want to multiply them to a new matrix, but with B transposed. Method 1: arma::Mat<double> A = B.t() * C; Method 2: arma::Mat<double> Bt = B.t() arma::Mat<double> A = Bt * C; Which one is faster? Method 2! By a factor of about 2.5x! Now if we allocate A before we do the multiplication, it doesn't change the time for method 2. It speeds up Method 1, but it is still 2x as slow as Method 2. This seems bizarre to me, since I would have thought if there was no templating stuff going on at compile time that the machine code would be almost identical. So why would they have templated it in such a way that actually made it worse? Or am I missing something major? Storing B.t() in memory as Bt and doing arma::inplace_trans(B) are about equally expensive from a time perspective. Obviously Bt = B.t() takes more memory, but you have the advantage of keeping both. I made B square so the number of multiplications is the same as A = B * C. A = B * C --> 6.98 seconds Bt = B.t(); A = Bt * C --> 7.02 seconds A = B.t() * C --> 18.6124 seconds, or 14.56 seconds when A is pre-allocated (??) I went down this rabbit-hole to see how I should store B to be more efficient, as I can construct it the other way. Especially once I start extracting rows or columns. But the difference between extracting a row and a column is actually unobservable at this scale! To be clear: A = B.rows(0, 499) * C is much faster than A = B.cols(0, 499).t() * C. I know they aren't the same mathematically, but if I had constructed B the other way round I was hoping for some performance benefit by accessing contiguous blocks of memory. Even A = B.rows(0,499) and A = B.cols(0, 499) are almost identical in terms of cost, which came as a surprise to me, but the scope of the question is starting to get too big. PS: I am using OpenBLAS
Hi all I'm going to answer my own question here might be useful to others. The answer for me is that it was because I was using a generic OpenBLAS, not an Intel processor-specific version of BLAS, and running in debug mode. With optimization at compile time and using an Intel processor-specific version of BLAS: Bt = B.t() and then A = Bt * C is definitely slower than A = B.t() * C, as we would expect due to the storing of the intermediate step. A = B.t() * C is faster than A = B * C, if B is square (I know this isn't the same number), but the difference is small, maybe 0-20% for the numbers I am using. Along a similar line, A = B.rows(0, 499) * C is slower than A = B.cols(0, 499).t() * C. The explanation is I believe that column access is faster than row access. B.t() * C uses columns of both B and C, whereas B * C uses rows of B and columns of C. All of this is much faster than loops. So use BLAS over C++ manual loops -- this is way more important than worrying about rows vs columns. One anomaly: A = B.rows(0, 499) is still faster than A = B.cols(0, 499). Any ideas on why would be appreciated! P.S. also tips on handing tensors higher than 2D in C++ would be appreciated. I hate arma::Cubes although I do use them.
71,180,794
71,180,882
C++ std:format not available in VS2022 /std:c++latest
I'm trying to use C++ std::format in Visual Studio 2022. I've selected C++ Language Standard: "Preview - Features from the Latest C++ Working Draft (/std:c++latest)" after initially trying "ISO C++20 Standard (/std:c++20)" The post below seems to indicate that selecting the Preview standard should work, but I don't have enough status to comment on that post directly. C++20 support in Visual Studio Should std::format work in VS2022 with the #include statement?
Should std::format work in VS2022 with the #include statement? Yes, but it currently only works in /std:c++latest (Preview) mode which you can set in Project\Properties\Configuration\Properties\C++ Language Standard. Demo
71,181,223
71,181,242
Allocating Sufficient Memory for a Known Number of Structs
First time implementing a graph where the total number of nodes is known when the constructor is called and performance is the highest priority. Never allocated memory before, so the process is a little hazy. The number of nodes required is (n*(n+1))/2 where n is the length of the string passed to the constructor. #include <string> struct ColorNode { ColorNode* lParent; ColorNode* rParent; char color; }; class ParentGraph { std::string base; int len, nodes; ParentGraph(std::string b): base(b) { len = base.length(); nodes = (len * (len + 1)) / 2; // how to allocate enough memory for number of copies of "ColorNode" equal to "nodes"? } }; What is the best practice for allocating memory in this instance? Will allocating the memory beforehand make a significant difference in performance? It may turn out that an array or vector is a better choice, but really need the practice in both data structures and memory allocation. Thanks for the consideration.
use std::vector<ColorNode> nodes; life will be very simple after that. You can be helpful to std::vector if you know the size you want auto nodes = std::vector<ColorNode>(size); This will allocate a contiguous array on the heap for you, manage its growth, allocation, deallocation etc. You will basically get the same in memory structure if you do new ColorNode[size] (or even malloc(....) if some evil person tried to persuade you that raw malloc will be faster). But you have to do all the nasty management yourself. You only need to diverge from this advice if you have too many objects to fit into one contiguous memory block. If thats the case say so
71,181,442
71,186,277
v8 - how to debug Map.prototype.set and OrderedHashTable?
I'm learning more about v8 internals as a hobby project. For this example, I'm trying to debug and understand how Javascript Map.prototype.set actually works under-the-hood. I'm using v8 tag 9.9.99. I first create a new Map object in: V8 version 9.9.99 d8> x = new Map() [object Map] d8> x.set(10,-10) [object Map] d8> %DebugPrint(x) DebugPrint: 0x346c0804ad25: [JSMap] - map: 0x346c08202771 <Map(HOLEY_ELEMENTS)> [FastProperties] - prototype: 0x346c081c592d <Object map = 0x346c08202799> - elements: 0x346c08002249 <FixedArray[0]> [HOLEY_ELEMENTS] - table: 0x346c0804ad35 <OrderedHashMap[17]> - properties: 0x346c08002249 <FixedArray[0]> - All own properties (excluding elements): {} When I break out of d8 into gdb, I look into the table attribute gef➤ job 0x346c0804ad35 0x346c0804ad35: [OrderedHashMap] - FixedArray length: 17 - elements: 1 - deleted: 0 - buckets: 2 - capacity: 4 - buckets: { 0: -1 1: 0 } - elements: { 0: 10 -> -10 } Poking around the v8 source, I find what I think to be the code related to OrderedHashTable and OrderedHashMap in src/objects/ordered-hash-table.cc. Specifically, line 368: MaybeHandle<OrderedHashMap> OrderedHashMap::Add(Isolate* isolate, Handle<OrderedHashMap> table, Handle<Object> key, Handle<Object> value) { ... After reading the code, my assumption is that OrderedHashMap::Add() will get triggered when you do Map.Prototype.Set (i.e., adding a new element). So I set a breakpoint here in and continue gef➤ b v8::internal::OrderedHashMap::Add(v8::internal::Isolate*, v8::internal::Handle<v8::internal::OrderedHashMap>, v8::internal::Handle<v8::internal::Object>, v8::internal::Handle<v8::internal::Object>) Breakpoint 1 at 0x557eb3b491e4 gef➤ c Continuing. I then attempt to set a new element, but the breakpoint does not trigger d8> x.set(11,-11) [object Map] Breaking out into gdb again, it appears the element has been added gef➤ job 0x346c0804ad35 0x346c0804ad35: [OrderedHashMap] - FixedArray length: 17 - elements: 2 - deleted: 0 - buckets: 2 - capacity: 4 - buckets: { 0: 1 1: 0 } - elements: { 0: 10 -> -10 1: 11 -> -11 } Do I have the breakpoint set up in the wrong spot? And if so, would anyone have any recommendations for efficiently finding the JS equivalents in v8?
(V8 developer here.) Many things in V8 have more than one implementation, for various reasons: in this case, there's the C++ way of adding an entry to an OrderedHashMap (which you've found), and there's also a generated-code way of doing it. If you grep for MapPrototypeSet, you'll find TF_BUILTIN(MapPrototypeSet, ... in builtins-collections-gen.cc, which is the canonical implementation of Map.prototype.set. Since that's a piece of code that runs at V8 build time to generate a "stub" which is then embedded into the binary, there's no direct way of setting a breakpoint into that stub. One way to do it is to insert a DebugBreak() call into the stub-generating code, and recompile. Not all builtins are implemented in the same way: some (like M.p.set) are generated "CSA builtins" in src/builtins/*-gen.cc some are regular C++ in src/builtins/*.cc some are written in Torque (src/builtins/*.tq) which is V8's own DSL that translates to CSA some have fast paths directly in the compiler(s) some have their meat in "runtime functions" (src/runtime/*.cc) Many have more than one implementation (typically a fully spec-compliant "slow" fallback, often but not always in C++, and then one or more fast paths that take shortcuts for common situations, often but not always in various forms of generated code). There are probably also a few special cases I'm forgetting right now; and as this post ages over the years, the enumeration above will become outdated (e.g. there used to be builtins in handwritten assembly, but we got rid of (almost all) of them; there used to be builtins generated by the old Crankshaft compiler, but we replaced that; there used to be builtins written in JavaScript, but we got rid of them; CSA was new at some point; Torque was new at some point; who knows what'll come next). One consequence of all this is that questions like "how exactly does JavaScript's feature X work under the hood?" often don't have a concise answer. Have fun with your investigation!
71,181,566
71,181,912
-Wconversion diagnostic from gcc-trunk when -fsanitize=undefined is passed
This is about the correct diagnostics when short ints get promoted during "usual arithmetic conversions". During operation / a diagnostic could be reasonably emitted, but during /= none should be emitted. Behaviour for gcc-trunk and clang-trunk seems OK (neither emits diagnostic for first or second case below)... until... we add the entirely unrelated -fsanitize=undefined ... after which, completely bizarrely: gcc-trunk emits a diagnostic for both cases. It really shouldn't for the 2nd case, at least. Is this a bug in gcc? Godbolt link Godbolt link with -O3 - same result int main() { short sum = 50; short count = 10; // sum and count get promoted to int for the "usual arithmetic conversions" // then the assignment could result in a reasonable -Wconversion diagnostic for reduction back // to short // However clang-trunk and gcc-trunk choose NOT TO issue a diagnostic with -Wconversion enabled short avg1 = sum / count; // we should be able to prevent promotion to int by using /= assignment operator. // Both clang-trunk and gcc-trunk, correctly, DON'T issue a diagnostic with -Wconversion enabled auto tmp = sum; tmp /= count; short avg2 = tmp; // HOWEVER if we add -fsanitize=undefined for both compilers // then, bizarrly, gcc-trunk issues a diagnostic for both cases above and clang-trunk still for // neither // none of these ever issue a diagnostic (nor should they) tmp += count; // all tmp -= count; // are tmp *= count; // silent return (avg1 + avg2) & 0xff; // prevent "unused" diagnostics } EDIT Here is the bug I filed for GCC: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104616
For a built-in compound assignment operator $= the expression A $= B behaves identical to an expression A = A $ B, except that A is evaluated only once. All promotions and other usual arithmetic conversions and converting back to the original type still happen. Therefore it shouldn't be expected that the warnings differ between short avg1 = sum / count; and tmp /= count;. A conversion from int to short happens in each case. So a conversion warning would be appropriate in either case. However, the documentation of GCC warning flags says specifically that conversions back from arithmetic on small types which are promoted is excluded from the -Wconversion flag. GCC offers the -Warith-conversion flag to include such cases nonetheless. With it all arithmetic in your examples generates a warning. Also note that this exception to -Wconversion has been introduced only with GCC 10. For some more context on it, the bug report from which it was introduced is here. It seems that Clang has always been more lenient on these cases than GCC. See for example this issue and this issue. For / in GCC -fsanitize=undefined seems to break the exception that -Wconversion is supposed to have. It seems to me that this is related to the undefined behavior sanitizer adding a null-value check specifically for division. Maybe, after this transformation, the warning flag logic doesn't recognize it as direct arithmetic on the smaller type anymore. If my understanding of the intended behavior of the warning flags is correct, I would say that this looks unintended and thus is a bug.
71,181,896
71,181,946
how can i declare a C++ array of 10 pointers to objects of a class?
Assume a circle class has been implemented. how can I declare an array of 10 pointers to objects of the circle class?
how can I declare an array of 10 pointers to objects of the circle class? Like this: circle* myArray[10]; It is then your responsibility to assign those pointers to point at valid circle objects. But how you do that exactly is outside the scope of your question, as you did not explain how you intend to use the circle class or this array.
71,182,029
71,182,044
How to pop a string from one stack and push onto another?
Code snippet: string token; token = mystack.pop(); This gives "operator=" error. It is my understanding this is due to the fact that strings do not have the = operator, and that strcpy() is the proper method. However, when I use: strcpy(token, mystack.pop()); I receive "error: ‘strcpy’ is not a member of ‘std’; did you mean ‘strcpy’?". I am quite confused by this. I am new to C++. My overall goal is to pop, check if it is an operand, then push to the operand stack or the operator stack, if that context helps at all. Thanks
This gives "operator=" error. Assuming you are using std::stack then its pop() method has a void return type, ie it does not return anything, so you can't assign it to your string. You need to instead read from its top() method before calling pop(), eg: string token; token = mystack.top(); mystack.pop(); It is my understanding this is due to the fact that strings do not have the = operator Then your understanding is wrong, because they do. and that strcpy() is the proper method. That is true for C-style char*/char[] strings, but not for C++-style std::strings.
71,182,056
71,182,096
c++ SFINAE - fallback overload with ellipsis does not work
I'm writing function working with STL containers that have iterator. And I'm trying to handle container that doesn't. my template function: template <typename T> void easyfind(...) { throw std::invalid_argument("No iterator"); } template <typename T> typename T::iterator easyfind(T& cont, int tofind) { typename T::iterator iter; iter = std::find(cont.begin(), cont.end(), tofind); if (iter == cont.end()) throw std::out_of_range("Cannot find"); return iter; } main.cpp: // @ list { std::list<int> L; std::list<int>::iterator iter; L.push_back(5); L.push_back(6); L.push_back(7); try { iter = easyfind(L, 7); std::cout << "found " << *iter << std::endl; } catch (std::exception& e) { std::cout << e.what() << std::endl; } } // @ stack ( no iterator ) { std::stack<int> S; S.push(10); S.push(11); S.push(12); try { easyfind(S, 12); // expect fallback case } catch (std::exception& e) { std::cout << e.what() << std::endl; } } I thought easyfind with stack would call void easyfind(...), but: main.cpp:88:4: error: no matching function for call to 'easyfind' easyfind(S, 12); ^~~~~~~~ ./easyfind.hpp:21:6: note: candidate template ignored: couldn't infer template argument 'T' void easyfind(...); ^ ./easyfind.hpp:27:22: note: candidate template ignored: substitution failure [with T = std::stack<int>]: no type named 'iterator' in 'std::stack<int>' typename T::iterator easyfind(T& cont, int tofind); The second ignore is what I expected, but i don't understand why it cannot call fallback function. What am I missing?
T is not used as a function argument so it can't deduce what T should be. In this case you could replace the varargs function with a variadic template: template <class... Args> void easyfind(Args&&...) // Now Args... can be deduced { throw std::invalid_argument("No iterator"); } However, your current check excludes plain arrays, like int A[3];, and it also throws an exception in runtime instead of generating a clear error message at compile time. You could add a type trait to check if std::begin(container) is valid. #include <iterator> #include <type_traits> template<class T> struct has_iterator { static std::false_type test(...); // fallback template<class U> // matches if std::begin() is valid static auto test(const U& u) -> decltype(std::begin(u), std::true_type{}); static constexpr bool value = decltype(test(std::declval<T>()))::value; }; template<class T> inline constexpr bool has_iterator_v = has_iterator<T>::value; Your easyfind could then use that type trait in a static_assert instead of adding a template overload and throwing in runtime. template <class T, class F> auto easyfind(T&& cont, F&& tofind) { // emit a clear compile time error message about the problem: static_assert(has_iterator_v<T>, "No iterator"); auto iter = std::find(std::begin(cont), std::end(cont), std::forward<F>(tofind)); if (iter == std::end(cont)) throw std::out_of_range("Cannot find"); return iter; } Demo
71,182,070
71,182,211
Getting last value printed twice when reading file in c++
I'm new to c++. Currently I'm learning how to read and write to a file. I've created a file "nb.txt" with content like this: 1 2 3 4 5 6 7 2 3 4 5 6 7 9 I'm using a simple program to read this file, looping until reached EOF. #include <iostream> #include <fstream> using namespace std; int main() { ifstream in("nb.txt"); while (in) { int current; in >> current; cout << current << " "; } } What I'm expecting is the program will output all of the values. But what I'm really getting is this: 1 2 3 4 5 6 7 2 3 4 5 6 7 9 9 There's a multiple "9" in the output. I don't understand what's happening! Is it because of the while loop? Can anyone help me to figure out why there is another "9"? Thanks!
The problem is that after you read the last value(which is 9 in this case) in is not yet set to end of file. So the program enters the while loop one more time, then reads in(which now sets it to end of file) and no changes are made to the variable current and it is printed with its current value(which is 9). To solve this problem, you can do the following: int main() { ifstream in("nb.txt"); int current=0; while (in >> current) { //note the in >> curent cout << current << " "; } } The output of the above program can be seen here: 1 2 3 4 5 6 7 2 3 4 5 6 7 9
71,182,090
71,182,120
How can I store the digits of two numbers in an array like in the code below, without using a string?
I need a program to read two numbers and store these number's digits in an array with a ';' in between them. I tried it using a char array but it didn't seem to work for me, and I also tried, as you can see below, by storing the numbers in a string first and putting a ';' in between then storing them in the array. How can I do that without the string? #include <iostream> #include <string> using namespace std; int main() { int a,b; char v[99999]; string numTotal; cin>>a>>b; numTotal=to_string(a)+';'+to_string(b); for(int i=0;i<numTotal.length();i++){ v[i]=numTotal[i]; cout<<v[i]; } }
You may want to use a function that's called getline(std::cin,) ( as long as you don't press a specific keyword like: Enter or sth) it will take your string all at once ( you can write 3;4 or sth and it will store it word-by-word). getline(cin,numTotal);
71,182,761
71,183,097
How to erase the inner map's key and then erase outer map element in C++
I have a map like this: std::map<int, std::map<float, char>> m; In this I need to delete the inner map's key, which is a float value. And after erasing that, if the inner map is empty then erase that element from the outer map also. One example. std::map<int, std::map<float, char>> m; std::map<float, char> m1; m1[2.5] = 'c'; m[5] = m1; Key to erase from the inner map is 2.5. After erasing this key from the inner map, it becomes empty. Now the outer map needs to check that after each erase if the inner map is empty then erase the element from the outer loop also. Now key 2.5 from the inner map has to be erased first.
As you stated in comments, you only know the key in the inner map (why do you not know the key in the outer map?), in which case you have no choice but to iterate the entire outer map until you find an element whose inner map contains that key. Then you will know which outer element you can erase. For example: std::map<int, std::map<float, char>> m; m[5][2.5] = 'c'; ... for(auto m_iter = m.begin(); m_iter != m.end(); ++m_iter) { auto &m2 = m_iter->second; auto m2_iter = m2.find(2.5); if (m2_iter != m2.end()) { m2.erase(m2_iter); if (m2.empty()) m.erase(m_iter); break; } }
71,182,775
71,186,268
How to register QObject class in CMake with qt_add_qml_module?
I have a QObject derived class Expense that I use in QML like this. // main.qml Expense { id: expenseManager onExpenseCreated: { // Do something } } The expense class has no UI components, it has some basic Signal and Slots for API communications. // expense.h #ifndef EXPENSE_H #define EXPENSE_H #include <QObject> #include <QString> #include "service.h" class Expense : public QObject { Q_OBJECT private: Service service; void networkError(); bool buttonLock = false; public: explicit Expense(QObject *parent = nullptr); public slots: void createInvoice(QString item, float amount); signals: void expenseCreated(); }; #endif // EXPENSE_H I have used qmlRegisterType() for registering Expense type in QML. Below is how my main() looks like. int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); ...... qmlRegisterType<Expense>("com.kadbyte.expense", 1, 0, "Expense"); ........ return app.exec(); } Everything working perfectly as it used to. But recently I have upgraded my project to QT6 with CMake as the build tool instead of QMake. In the docs I saw that we can use qt_add_qml_module command in CMakeList.txt to register C++ Classes instead of qmlRegisterType(), by adding QML_ELEMENT macro to the QObject class. But I can't understand how to do this, the documentation doesn't make sense as it uses qmake example (Link to docs) instead of CMake. Below is my CMakeLists.txt file cmake_minimum_required(VERSION 3.16) project(Udyan VERSION 0.1 LANGUAGES CXX) set(CMAKE_AUTOMOC ON) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(Qt6 6.2 COMPONENTS Quick REQUIRED) qt_add_executable(appUdyan main.cpp expense.h expense.cpp ) qt_add_qml_module(appUdyan URI Udyan VERSION 1.0 QML_FILES qml/main.qml ) set_target_properties(appUdyan PROPERTIES MACOSX_BUNDLE_GUI_IDENTIFIER my.example.com MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION} MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR} MACOSX_BUNDLE TRUE WIN32_EXECUTABLE TRUE ) target_compile_definitions(appUdyan PRIVATE $<$<OR:$<CONFIG:Debug>,$<CONFIG:RelWithDebInfo>>:QT_QML_DEBUG>) target_link_libraries(appUdyan PRIVATE Qt6::Quick) So how to use qt_add_qml_module to registering QObject class to use in QML? Note: All the example I have given above is just an MRE and not my complete code.
You just need to add QML_ELEMENT to your QObject-derived Expense class's header and make sure you have moc enabled in your CMakeLists.txt. In application case it doesn't matter if the expense.h/cpp sources are included via qt_add_executable or qt_add_qml_module. I think it's clearer to add them to qt_add_qml_module SOURCES. Then you just import module URI in you QML file. In the example below I'm printing out property value from Expense object in QML. CMakeLists.txt set(CMAKE_AUTOMOC ON) qt_add_qml_module(appUdyan URI udyan VERSION 1.0 QML_FILES main.qml SOURCES expense.h expense.cpp ) C++ #include <QObject> #include <QtQml/qqmlregistration.h> class Expense : public QObject { Q_OBJECT QML_ELEMENT Q_PROPERTY(int value READ value NOTIFY valueChanged) public: explicit Expense(QObject *parent = nullptr); int value() const; signals: void valueChanged(); private: int m_value {5}; }; QML: import QtQuick import udyan Window { width: 640 height: 480 visible: true title: qsTr("Hello World") Expense { id: expense Component.onCompleted: console.log(expense.value) } }
71,183,145
71,186,841
Create std::chrono::time_point from string
A program like this int main() { using namespace date; std::cout << std::chrono::system_clock::now() << '\n'; } prints something like 2017-09-15 13:11:34.356648. Assume I have a string literal "2017-09-15 13:11:34.356648" in my code. What is the right way to create std::chrono::time_point from it in C++20?
Just to be clear, there is no namespace date in C++20. So the code in the question should look like: #include <chrono> #include <iostream> int main() { std::cout << std::chrono::system_clock::now() << '\n'; } The inverse of this is std::chrono::parse which operates on streams. You can also use std::chrono::from_stream if desired. parse is a stream manipulator that makes the syntax a little nicer. istringstream in{"2017-09-15 13:11:34.356648"}; system_clock::time_point tp; in >> parse("%F %T", tp); (I've dropped the namespaces just to keep the verbosity down) The locale used is the global locale in effect at the time the istringstream is constructed. If you prefer another locale use the imbue member function to set the desired locale. The locale will only impact the decimal point character in this example. The %T will read up to whatever precision the input time_point has (which varies with platform from microseconds to nanoseconds). If you want to be sure you can parse nanoseconds even if system_clock::time_point is coarser than that, then you can parse into a sys_time<nanoseconds> which is a type alias for time_point<system_clock, nanoseconds>. sys_time<nanoseconds> tp; in >> parse("%F %T", tp); If the input stream has precision less than the input time_point, there is no problem. What the stream has will be read, and no more. If the input stream has precision finer than the input time_point, then the parse stops at the precision of the time_point, and the remaining digits are left unparsed in the stream. Other strptime-like parsing flags are supported.
71,183,352
71,195,287
Merging Tables in Apache Arrow
I have two arrow:Tables where table 1 is: colA colB 1 2 3 4 and table 2 is, colC colD i j k l where both table 1 and 2 have the same number of rows. I would like to join them side-by-side as colA colB colC coldD 1 2 i j 3 4 k l I'm trying to use arrow::ConcatenateTables as follows, but I'm getting a bunch of nulls in my output (not shown) t1 = ... \\ std::shared_ptr<arrow::Table> t2 = ... \\ std::shared_ptr<arrow::Table> arrow::ConcatenateTablesOptions options; options.unify_schemas = true; options.field_merge_options.promote_nullability = true; auto merged = arrow::ConcatenateTables({t1, t2}, options); How do I obtain the expected output?
arrow::ConcatenateTables only does row-wise concatenation. There is no builtin helper method for column-wise concatenation but it is easy enough to create one yourself (apologies if this is not quite right, I'm not in front of a compiler at the moment): std::shared_ptr<arrow::Table> CombineTables(const Table& left, const Table& right) { std::vector<std::shared_ptr<arrow::ChunkedArray>> columns = left.columns(); const std::vector<std::shared_ptr<arrow::ChunkedArray>>& right_columns = right.columns(); columns.insert(columns.end(), right_columns.begin(), right_columns.end()); std::vector<std::shared_ptr<arrow::Field>> fields = left.fields(); const std::vector<std::shared_ptr<arrow::Field>>& right_fields = right.fields(); fields.insert(fields.end(), right_fields.begin(), right_fields.end()); return arrow::Table::Make(arrow::schema(std::move(fields)), std::move(columns)); }
71,183,490
71,183,532
How to get the address of an array pointer?
I have the following c code: int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8}; int **pp = &arr; The compiler complains and I don't know why. Isn't arr a pointer points to an int array? I should be able to assign the address of it to a int**. Are there any other way to do it?
Isn't arr a pointer points to an int array? No, arr isn't a pointer at all. arr is an array. If you take the address of arr, what you get is a pointer to an array, not a pointer to a pointer. This would work: int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8}; int (*pp)[8] = &arr; // cleaner by using a type alias: using Arr8 = int[8]; Arr8* pp = &arr; If you want a pointer to pointer, then you must first create a pointer to which you could point at: int* p = arr; // same as = &arr[0] int** pp = &p; But when I do printf("arr: %x\n", arr);. It actually prints out the starting address of arr. Doesn't that mean it is a variable stores the address of the array? It does not mean that. arr is the array; it doesn't store the address of the array, and the type of the variabe isn't a pointer. When you pass an array as a variadic argument, it will implicitly convert to a pointer to first element. That is the same implicit conversion that happens in the example above: int* p = arr;. Note that %x format specifier requires that the argument is of type int (or smimilar). int* (which is the resulting type of the implicit conversion) is the wrong type, and hence the behaviour of the program will be undefined.
71,183,642
71,183,765
MobaXterm does not display the whole image received from WSL
I am using WSL1 in Windows 10 with Ubuntu 18.04 LTS. Configured everything fine to use OpenCV with C++, but when I wanted to display an image, I always received the below error. terminate called after throwing an instance of 'cv::Exception' what(): OpenCV(4.5.5-dev) /opt/opencv/modules/highgui/src/window_gtk.cpp:635: error: (-2:Unspecified error) Can't initialize GTK backend in function 'cvInitSystem' After searching on the internet, I've found that I should use some kind of X Server to display the images, so I've installed MobaXterm to try it out. I have also added the export DISPLAY=:0.0 to the ~/.bashrc file. Now, when I try to display my image, a window pops up, but only a part of the image is displayed. Does anyone have any idea what should be the problem, why is only a part displayed of the image? Thank's for everything in advance!
Maybe you can try with another option such as gWSL or XShell? If these are working, then it would be probably an issue related with MobaXterm and you can contact with the developer of this application. If the problem continues, then it should be further investigated.
71,183,782
71,186,465
Rewrite template names when debugging with lldb
When debugging a c++ program using templates, the output can quickly become unreadable. For this reason it would be convenient, during a debugging session, to rewrite shorten specific type names. For example void std::__1::vector<std::__1::tuple<unsigned long, state_change_t, some::namespace::Board<some::namespace::Tile, unsigned long, 42ul>, some::namespace::Path<unsigned int, unsigned int>>, std::__1::allocator<std::__1::tuple<unsigned long, state_change_t, some::namespace::Board<some::namespace::Tile, unsigned long, 42ul>, some::namepsace::Path<unsigned int, unsigned int> > > >::some_interesting_method Such an entry can appear multiple times in a single line in a backtrace; This quickly becomes unmanageable. It would therefore be convenient to shorten it to something along the lines of void void std::__1::vector<my_known_type, std::__1::allocator<my_known_type> >::some_interesting_method How can this be done?
Clang have an attribute called preferred_name that can be used to create template aliases for compile-time diagnostics. It requires a bit of forward declaring, like this: template<typename T> struct Heap; using IntHeap = Heap<int>; template<typename T> struct [[clang::preferred_name(IntHeap)] Heap; // Possibly add implementation, don't have to yet. Unfortunately, since September 2021, clang won't use this when writing debug symbols. There is a mailing list thread discussing this change and the diff is here. Clang versions 12 and 13 should still use preferred name in debug symbols, but that's a pretty narrow version window. Opening a ticket asking to add a flag that enables preferred names in debug symbols might be worthwhile - it seems like a very trivial feature to implement and pretty useful.
71,184,408
71,184,577
How can I avoid `#pragma once in main file` in GCC when using precompiled headers?
Here is a minimal example: // pch.h #pragma once #include <iostream> And I run: g++ -x c++-header -o pch.h.gch -c pch.hpp When I run the command, I get pch.h:1:9: warning: #pragma once in main file 1 | #pragma once | From my understanding, this behavior is intended by GCC after reading their bugzilla bug tracker; so, this is not a bug but a feature. How can I disable this warning? Is there a warning number or name that I can suppress by adding it as a pragma statement: #pragma GCC diagnostic ignored "-Wcan-i-set-something-here"
From my understanding, this behavior is intended by GCC As far as I can tell, it's a bug. How can I disable this warning? Unfortunately, it appears that you cannot since the warning cannot be controlled by an option. In my opinion, this is a bug as well. You can circumvent the issue by using a header guard instead of #pragma once.
71,184,455
71,184,710
How to define a template function that only accepts a base class with parameter T of type its subclass?
It is not specific to casting. My scenario is how to define a template function that only accepts a base class for parameter T of type subclass. template<typename T> // T must be a subclass T* DoSomething(<I don't know> parent) // parent must be a base class { // here the specified subclass of type T is produced. // return object of type T which is a subclass. } A contrived usage: Parent* p = new Child(); Child* c = DoSomething<Child>(p); delete p;
One way could be by using std::is_base_of or std::is_base_of_v in combination with a static_assert: template<typename Derived, typename Base> Derived* CastChecked(Base* parent) { static_assert(std::is_base_of_v<Base,Derived>); return dynamic_cast<Derived*>(parent); }
71,184,990
71,185,187
Where is std::this_thread for jthread?
Can't figure out where is std::this_thread for jthread? I have a function that theoretically makes a jthread sleep until a cancellation is requested: template<typename Rep, typename Period> void sleep_for(const std::chrono::duration<Rep, Period>& d, const std::stop_token& token) { std::condition_variable cv; std::mutex mutex; std::unique_lock<std::mutex> lock{ mutex }; std::stop_callback stop_wait{ token, [&cv]() { cv.notify_one(); } }; cv.wait_for(lock, d, [&token]() { return token.stop_requested(); }); } How do I call it on jthread? Theoretically the program below exits within 1 second: int main() { std::jthread t([]() { //where do I get `stop_token`? sleep_for(std::chrono::seconds(5), std::this_jthread::get_stop_token()); }); std::this_thread::sleep_for(std::chrono::seconds(1)); t.request_stop(); return 0; }
The jthread constructor accepts a function that takes a std::stop_token as its first argument, which will be passed in by the jthread from its internal stop_source. Here is an example: std::jthread t([](std::stop_token stop_token) { while(!stop_token.stop_requested()) { //Process data... std::this_thread::sleep_for(std::chrono::seconds(5)); } }); std::this_thread::sleep_for(std::chrono::seconds(1)); t.request_stop(); live on Godbolt.
71,185,030
71,185,259
C++ concept that checks a value for requirements
Is there a way to use c++20s concepts to check that a value meets some requirements? Lets say I am writing some sort of container that uses paging and i want to make the page size a template parameter. template<typename Type, std::size_t PageSize> class container; I could use a static assert with a constexpr function to check if PageSize is a power of two inside the class body. But is there a way to use the new concepts to restrain PageSize?
C++20 introduced std::has_single_bit to check if x is an integral power of two, so you can use requires expression to constrain PageSize. #include <bit> template<typename Type, std::size_t PageSize> requires (std::has_single_bit(PageSize)) class container { }; Demo
71,185,376
71,185,655
std::visit with passing pointer fails to compile under clang 13
The following code compiles properly under x64 msvc x19.30 and gcc 11 but fails to compile under clang 13.0.1: "error: cannot pass object of non-trivial type 'std::shared_ptr<std::pair<int, std::variant<Struct1, Struct2, UnsupportedStruct>>>' through variadic function;" Does anyone know what the problem is? The following code produces different outputs depending on passing object: #include <iostream> #include <variant> #include <memory> struct Struct1{}; struct Struct2{}; struct UnsupportedStruct{}; using VarTypeData = std::variant<Struct1, Struct2, UnsupportedStruct>; using VarType = std::pair<int, VarTypeData>; namespace { void print(Struct1&, std::shared_ptr<VarType> v) {std::cout << v->first << ": Struct1\n";} void print(Struct2&, std::shared_ptr<VarType> v) {std::cout << v->first << ": Struct2\n";} void print(...) {std::cout << "no implementation";} } int main() { VarType data1 = std::make_pair(100, UnsupportedStruct{}); auto pointerData = std::make_shared<VarType>(data1); std::visit([&pointerData](auto& c) {print(c, pointerData);}, pointerData->second); std::cout << std::endl; pointerData->second = Struct1{}; std::visit([&pointerData](auto& c) {print(c, pointerData);}, pointerData->second); } This code works fine for clang after dereferencing: #include <iostream> #include <variant> #include <memory> struct Struct1{}; struct Struct2{}; struct UnsupportedStruct{}; using VarTypeData = std::variant<Struct1, Struct2, UnsupportedStruct>; using VarType = std::pair<int, VarTypeData>; namespace { void print(const Struct1&, const VarType& v) {std::cout << v.first << ": Struct1\n";} void print(const Struct2&, const VarType& v) {std::cout << v.first << ": Struct2\n";} void print(...) {std::cout << "no implementation";} } int main() { VarType data1 = std::make_pair(100, UnsupportedStruct{}); auto pointerData = std::make_shared<VarType>(data1); std::visit([&pointerData](auto& c) {print(c, *pointerData);}, pointerData->second); std::cout << std::endl; pointerData->second = Struct1{}; std::visit([&pointerData](auto& c) {print(c, *pointerData);}, pointerData->second); }
thanks to @康桓瑋 for the answer. this code does not work for clang, because of void print(...) {std::cout << "no implementation";} answer: void print(...) is a C function, where variadic actually means the 's parameter. It accepts only trivial types, which std::shared_ptr is not. So the behavior is undefined or only conditionally supported So, the following changes fix the problem: template<class... Args> void print(Args&&...) {std::cout << "no implementation";}
71,186,447
71,186,727
How to inspect pop up windows/tool tips/hover effects which are designed to hide/close on mouse move with tools like WinSpy++ or Spy++?
Essentially I'm trying to learn more about the Win32 api, how certain classes/elements are created, destroyed, what items make them up etc.. Dissecting windows if you will for a project of mine. I'm very curious at the moment what popups/tool tips/hover effects ubiquities to all windows applications are made up of. My main goal is to grab text from any tooltip/hover thingy/WS_POPUP? If someone knows that is great but I'd also like to have the tools to research it myself. I'm not even sure what to google to be honest to get me on the right path. I've tried some C++ code to print class names and fetch the text from what I think might be a msgbox but no dice so far.
The MiniSpy tool on Codeproject comes in handy in situations like this because it uses the corner of the spy window as the location, not the mouse.
71,186,547
71,414,421
How to read the length of audio files using Juce "C++." Without playing the file
I'm trying to display the length of audio files in a Playlist component for an application. I've not used Juce or C++ before, and I can't understand how to do that from Juce documentation. I want to make a function that takes an audio file's URL and returns the length in seconds of that audio without playing that file or doing anything else with that file. I've tried a lot of things, and all of them didn't work, and this is the last thing I've tried: void PlaylistComponent::trackStats(URL audioURL) { AudioFormatManager formatManager; std::unique_ptr<AudioFormatReaderSource> readerSource; AudioTransportSource transportSource; auto* reader = formatManager.createReaderFor(audioURL.createInputStream(false)); if (reader != nullptr) { std::unique_ptr<AudioFormatReaderSource> newSource(new AudioFormatReaderSource(reader, true)); transportSource.setSource(newSource.get(), 0, nullptr, reader->sampleRate); readerSource.reset(newSource.release()); DBG("PlaylistComponent::trackStats(URL audioURL): " << transportSource.getLengthInSeconds()); } else { DBG("Something went wrong loading the file"); } } And this is the PlaylistComponent header file: class PlaylistComponent : public juce::Component, public juce::TableListBoxModel, public Button::Listener, public FileDragAndDropTarget { ... }
juce::AudioFormatReaderSource has a method called getTotalLength() which returns the total amount of samples. Divide that by the sample rate of the file and you have the total length in seconds. Something like this: if (auto* reader = audioFormatReaderSource->getAudioFormatReader()) double lengthInSeconds = static_cast<double> (audioFormatReaderSource->getTotalLength()) / reader->sampleRate;
71,186,795
71,195,766
How to override emacs-projectile default configuration for project?
I try to use emacs with projectile to configure and than build C++ CMake project. By default projectile use next configuration: (defconst projectile--cmake-manual-command-alist '((:configure-command . "cmake -S . -B build") (:compile-command . "cmake --build build") (:test-command . "cmake --build build --target test"))) How can I override this settings for my project(only for my project)? Suppose I want to make something like: (defconst projectile--cmake-manual-command-alist '((:configure-command . "cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -S . -B .build") (:compile-command . "cmake --build .build") (:test-command . "cmake --build .build --target unit-tests"))) I search throw documentation but can't find some simple solution. I expect to see modification for .dir-locals.el file with some new variables. Maybe am I doing something completely wrong and I should use it in different way? Thanks in advance.
Have you tried put this .dir-locals.el in the root dir of your project? ;;; Directory Local Variables ;;; For more information see (info "(emacs) Directory Variables") ((c++-mode . ((projectile--cmake-manual-command-alist . ((:configure-command . "cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -S . -B .build") (:compile-command . "cmake --build .build") (:test-command . "cmake --build .build --target unit-tests"))))))
71,186,902
71,186,995
Using has_include with variables in a loop to check libraries
I'm trying to check if a library is available using __has_include from this post. Since I want to check each one I'm using a loop /* Array of Strings */ const char* libraries[5] = { "iostream", "unistd.h", "stdlib.h", "Windows.h", "winaaasock2.h"}; /* Getting the length of the array */ int librariesSize = sizeof(libraries)/sizeof(libraries[0]); /* Looping through them (5 Times) */ for (int i = 0; i < librariesSize; i++) { #if __has_include(<\"libraries[i]"\>) #include <\"libraries[i]"\> cout << "Ok"; #else cout << "Error"; #endif } It compiles but it's still telling me that all of them exist even for winaaasock2, which is made up from the original, winasock2. It requires to be inside <> signs and quotes so I used back slashes Using the same code without the loop works #if __has_include("winaaasock2.h") #include "winaaasock2.h" cout << "Ok"; #else cout << "Error"; #endif The output here is Error, with a library like unistd.h the output is ok since it exists What I'm missing? Thanks in advance
It compiles It shouldn't. The C++ language doesn't allow expression statements such as loops in the namespace scope. The example program is ill-formed. Besides that, pre-processor has no knowledge of your loops. There are two possible ways that your program may be processed: // if the header \"libraries[i]"\ exists for (int i = 0; i < librariesSize; i++) { // content from header \"libraries[i]"\ cout << "Ok"; } // OR if the header \"libraries[i]"\ doesn't exist for (int i = 0; i < librariesSize; i++) { cout << "Error"; } If all that you want to do is to check whether all headers exist, and produce an error otherwise, then __has_include won't offer anything of use for you. You should simply include them. If a header is missing, there will be an error message that explains the issue.
71,186,966
71,187,631
Max Heap built with pimpl in c++ not working properly
I have a class built using the pimpl idiom that represents a binary max Heap and it is not working properly: the program compiles and prints the content of the array but the array is not sorted correctly. In the examples I used in the main I should see the array sorted as: 100->19->36->17->3->25->1->2->7. I checked multiple times the correctness of the heapify algorithm and I suspect that the problem lies in the constructor. I'm looking for help to understand what is wrong with the code. Regarding the way the pimpl idiom has been used, it comes from the first basic example explained in the book: "Effective Modern C++" of Scott Meyers. I know there are more efficient ways to use the pimpl idiom but that is not the purpose of this post. #include <vector> #include <cstddef> class MaxHeap{ public: MaxHeap(); MaxHeap(const std::vector<int>& arr); ~MaxHeap(); void maxHeapify(size_t i); void printHeap(); private: struct Impl; Impl* pimpl; }; #include "binaryHeap.hpp" #include <iostream> using namespace std; struct MaxHeap::Impl{ vector<int> elements; size_t heapsize; }; void MaxHeap::maxHeapify(size_t i){ size_t size = pimpl->heapsize; size_t largest = i; size_t l = 2 * i + 1; size_t r = 2 * i + 2; if (l < size && pimpl->elements[l] > pimpl->elements[largest]) largest = l; if (r < size && pimpl->elements[r] > pimpl->elements[largest]) largest = r; if (largest != i) { swap(pimpl->elements[i], pimpl->elements[largest]); maxHeapify(largest); } } MaxHeap::MaxHeap() :pimpl(new Impl){ pimpl->heapsize = 0; } MaxHeap::MaxHeap(const vector<int>& arr) :pimpl(new Impl{vector<int> (arr),arr.size()}){ for (size_t i = (pimpl->heapsize/2)-1; i>-1; i--) { maxHeapify(i); } } MaxHeap::~MaxHeap(){ delete pimpl; pimpl=nullptr; } void MaxHeap::printHeap(){ for(size_t i=0;i<pimpl->heapsize;i++){ cout <<pimpl->elements[i]<<" "; } } #include <iostream> #include "binaryHeapImpl.cpp" using namespace std; int main() { vector<int> arr; arr.push_back(100); arr.push_back(25); arr.push_back(1); arr.push_back(36); arr.push_back(3); arr.push_back(19); arr.push_back(17); arr.push_back(7); arr.push_back(2); MaxHeap testheap(arr); testheap.printHeap(); return 0; }
I should see the array sorted as: 10->19->36->17->3->25->1->2->7 That can't be, because in main() function you don't even put 25 in :-) But anyway, here: for (size_t i = (pimpl->heapsize/2)/-1; i>-1; i--) { If you read compilation warnings (because you compile with warnings enabled, right? :-) ) you would see: warning: comparison of integer expressions of different signedness: ‘size_t’ {aka ‘long unsigned int’} and ‘int’ which should trigger alarm bells. heapsize is of type size_t, which is unsigned. Why do you divide it by -1? -1 converted to unsigned is the max value and the result of anything unsigned divided by max unsigned will be always 0. Similarly with the comparison, no value will be bigger than the max value. As a result, this loop does not execute even once. Iterating downward to 0 over unsigned value is a bit tricky. Some options are iterating until we reach max value: for (size_t i = pimpl->heapsize/2; i != (size_t)-1; i--) { or goes to "operator" (notice + 1): for (size_t i = pimpl->heapsize/2 + 1; i-- > 0; ) { or use signed: for (int i = pimpl->heapsize/2; i >= 0; i--) { Then the output is: 100 19 36 3 1 17 7 2 which I believe is what is expected from the numbers put in in the main().
71,187,113
71,187,166
Constrain non-type/value template parameter using requires in an ad-hoc fashion
My goal for this code is to constrain a function parameter's passed value to a select few possibilities, being checked at compile time in C++20. My original broken first attempt looked something like this: template<GLenum shader_type> requires requires { shader_type == GL_VERTEX_SHADER || shader_type == GL_FRAGMENT_SHADER || shader_type == GL_COMPUTE_SHADER; } GLuint create_shader(std::filesystem::path const& shader_path, GLenum shader_type) This would not work, and I'm not going to argue with the compiler, but I'm including it here to help illustrate my aims for this declaration. My spec: Constrain a single passed GLenum to a set of three currently supported types. Preferably in an ad-hoc way, e.g. not requiring much boilerplate. For a user, be able to call this function like so: create_shader("my/path", GL_FRAGMENT_SHADER). No templates in sight. The main issues with this code were: declaration of 'shader_type' shadows a template parameter. I can see this is because of the specification of GLenum shader_type in both the template parameters and function arguments, but I was hoping that somehow have the compiler might infer the type from function args. shader_type == GL_VERTEX_SHADER || shader_type == GL_FRAGMENT_SHADER || shader_type == GL_COMPUTE_SHADER is not doing it's job at all. I could pass GL_GEOMETRY_SHADER in with no compile-time issue. (I wish I could say the same for run-time) After looking at this Question I came up with this next: template<GLenum shader_type> requires requires { requires shader_type == GL_VERTEX_SHADER || shader_type == GL_FRAGMENT_SHADER || shader_type == GL_COMPUTE_SHADER; } GLuint create_shader(std::filesystem::path const& shader_path) This seems to work as I desire when it comes to constraining the passed value to those values, however, it does require shader_type being passed in as a template parameter. This is fine really, but it leads me to my questions: Is there a way to do as I've done in terms of constraints but without having the user pass in shader_type as a template parameter explicitly, instead preferring a function argument? Is there a way of writing this declaration with fewer requires? I suspect not, but it would be nice if I can cut one out. Generally, does anyone know any alternatives which are "better" on the whole. Perhaps referring to my spec at the top of this question for what "better" might be. Appendix: I'm aware of constexpr and that I could probably do the check inside the function, but doing it through constraints and concepts is also a bit of exploration for me, as a learner. In case people are confused by GLenum or any of the other non-standard code: typedef unsigned int GLenum; typedef unsigned int GLuint; #define GL_FRAGMENT_SHADER 0x8B30 #define GL_VERTEX_SHADER 0x8B31 #define GL_COMPUTE_SHADER 0x91B9
If you wanted to constrain a template parameter, a single requires is enough: template <GLenum shader_type> requires(shader_type == GL_VERTEX_SHADER || shader_type == GL_FRAGMENT_SHADER) void foo() {} A function parameter can be constrained like this, at the cost of requiring it to be a compile-time constant: struct ShaderType { GLenum value; consteval ShaderType(GLenum value) : value(value) { if (shader_type != GL_VERTEX_SHADER && shader_type != GL_FRAGMENT_SHADER) throw "Invalid value!"; // Normally it's not a good idea to throw pointers, // but here it just used to stop the compilation. } }; void foo(ShaderType type) {}