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
65,923,586
65,926,530
Which pattern to generify instantiation of objects that have different Ctor arguments
I would like to construct a robot with or without a tool, a mobile base, and other parts. As I want to automatize the configuration of the parts, I have a class Robot with the parts as template arguments For instance, in the code below, the code will build as long as we use tools that have the same constructor signatur...
You could also use tuple instead of struct, not ideal but this works as well: #include <iostream> #include <string> #include <tuple> class BaseRobot { public: BaseRobot() {}; }; class ToolInterface { public: ToolInterface(std::string _name) :name{ _name } {/*register _base*/ }; std::string name; bool...
65,923,989
65,924,206
How to define a vector of two dimensional array?
How to define a vector that will contain two-dimensional arrays. eg: vector<array[16][16]> vec; // where the two dimensional array have string elements which will contain vec ={array_1[16][16],array_2[16][16],array_3[16][16],....}; I have tried: vector<array<array<string,16>,16>> vec; but it does not work when I use ...
You shouldn't name a variable like a type. You are shadowing std::array. You should rename the variable and use std::array instead of C-arrays: #include <array> #include <string> #include <vector> using StrArr2D = std::array<std::array<std::string, 16>, 16>; int main() { StrArr2D arr; std::vector<StrArr2D> ve...
65,924,119
65,924,235
How to use a template member function as an argument to another template member function?
So I'm experimenting with templates and probably I have a syntax problem somewhere. I'm trying to write a class, which takes a vector of selected items, converts their properties to boolean arrays, and then generates object which represent the state of the whole selection> This object is sent to the UI view and shown o...
Well, you really are missing & and the names have to be prepended with the class name. Try this: models.general = getCheckStateFromAnyStatus(selectedItems, &CheckModelGenerator::getGeneralStatus); models.surface = getCheckStateFromAnyStatus(selectedItems, &CheckModelGenerator::getSurfaceStatus); models.other = getCheck...
65,924,397
65,927,809
Rules regarding using declarations c++
After reading the accepted answer from this question, I thought I understood why the program failed, since the using directive does not actually declare the entity i in the region. However names introduced by a using declaration can be used just like any other name and acts like a declaration. With GCC, this fails #inc...
Technically, the example you've given does compile, but it fails to link. The issue is the line extern int i; What you're telling the compiler/linker here is "there will be a variable i defined somewhere else in the program, so, compiler, don't worry if you can't find the definition. Linker, I expect you to find the d...
65,924,443
65,925,919
C++ URLDownloadToFile to executable directory in CLR forum
I'm trying to figure out how I can fix two issues that I've been having with the URLDownloadToFile function in C++. The first is that when attempting to download the file in question, the download doesn't actually appear until the CLR C++ window is closed. The second is that as shown on the image below, the resulting f...
LPTSTR currentDirectoryLPTSTR = new TCHAR[currentDirectory.size() + 1]; allocates memory, but does not fill it with any data. std::string(currentDirectoryLPTSTR) creates a new string object and tries to copy data from currentDirectoryLPTSTR into the string. Which is undefined behavior since currentDirectoryLPTSTR is n...
65,924,650
65,925,418
How to build PythonQt in ubutnu
I want to embed the python script in my c++ Qt application, By searching on the net I found that PythonQt is exactly what I am looking for but when I went to it's github repo there is build description given for windows system but not for ubuntu system so after cloning the repo if I include it's src in my Qt .pro file ...
First clone the repo by using the following command https://github.com/MeVisLab/pythonqt.git After that cd into the clone folder and execute the below command to build it into your system. qmake This command will generate the MakeFile into your current directory run the following command to completely build the Python...
65,925,200
65,925,681
ADL not working outside (even of structure)
If I have a structure the overloads begin, end, etc. like the following: #include <array> template<typename T> struct Array10 { private: std::array<T, 10> m_array; public: constexpr auto begin() { return std::begin(m_array); // #1 } constexpr auto end() { return std::end(m_arra...
ADL doesn't find members. It finds free functions. You have a member foo.begin(), not a free function begin(foo). friend constexpr auto begin(Array10&) { return std::begin(m_array); // #1 } friend constexpr auto begin(Array10 const&) { return std::begin(m_array); // #1 } those are non-member begin functions t...
65,925,425
65,925,608
Does declaring local method variables for error handling come at memory or performance cost in C++?
I want to ensure my application takes care of error handling. I am using a driver API to communicate with some hardware device - for this I have implemented both getter and setter methods to read and assign certain parameter values. The getter functions are marked as const, since they are not intended to change anythin...
Allocating memory (stack or heap) is not a good idea in a tight loop. This is because allocation is anyway a little costly (specially heap allocation). In your method, you can ditch the error variable and insert the function right into the if condition so that you wont allocate extra variables: if (getParameterAPI(obje...
65,925,572
65,927,341
C++ How does implicit construction work, struct initialization?
I have a question about implicit constructors. So let's say I have the following scenario: struct MyStruct1 { bool myBool1 = false; bool myBool2 = false; MyStruct1() = default; MyStruct1(bool val) : myBool1(val) , myBool2(val) {} }; struct MyStruct2 { MyStruct1 myStruct1; }; ...
Yes, that is part of how it works, but there is more to it. It isn't only one-parameter constructors that can be explicit. You can do it for any constructor regardless of number of parameters, better explained by code: #include <memory> struct MyStruct1 { bool myBool1 = false; bool myBool2 = false; ex...
65,925,592
65,925,846
Hangman game - how to do a "wrong guess" in c++?
My game works but not the "wrong guess" part, that "error" means "it says I'm wrong even if my guess is right or it says wrong several times, not just once". So, in my beginner program, that's where I'm stuck. char u_recherche; std::string mot_secret(choisi_ton_mot.length(), '-'); std::string choisi_ton_mot; int ...
apart from that your code is not complete, the actual errors are easy to spot: You have two loops. The outer "while" loop and the inner "for" loop. Those both use "i" as index, so the inner "i" hides the outer. This is not a bug in itself, but easily leads to other errors, like in your program. Your second "if", the ...
65,925,849
65,926,303
Object array copy constructor
I have an object PointArray with a field Point *array. I want to make a copy constructor: PointArray::PointArray(const PointArray &pv) { size = pv.size; array = new Point[size]; for (int i=0;i<size;i++){ Point toAdd = Point(pv.array[i].getX(), pv.array[i].getY()); array[i] = toAdd; } } ...
Is this correct? It depends. How is the copy constructor that you designed supposed to behave? How does your constructor behave? Does it behave as you intended? What are the invariants of your class? Are those invariants maintained as the post condition of the constructor? Some issues: Are you sure that the loop wh...
65,925,974
65,930,834
How to output a HashMap element in GDB?
All I have is a binary file and a coredump, and I need to return the value of the vector element in hashmap[8888][1] using a gdb script at the time of the program crash. While the program was running, the container was damaged, but it is claimed that the necessary data can be obtained. The question is how to use pointe...
Normally, print hashmap should produce all the output you need. For example, compiling this program: #include <unordered_map> #include <vector> int main(int arch, char *argv[]) { std::unordered_map<int, std::vector<int>> hm; hm[7777].push_back(42); hm[7777].push_back(24); hm[8888].push_back(42); return 0; } ...
65,926,172
65,926,433
list of base class pointers, get different return values for function member
Imagine the following situation You have a pointer to a variable: fooVar * You can get the type of the variable with a function like this: get_type(fooVar* foo) which is returning a int value bar You can then lookup in an enum to which type the returned value bar belongs, e.g. 1 -> type_int Depending on the type, you ...
It seems like you have gotten yourself into the corner of trying to re-implement virtual functions and dynamic inheritance. So, perhaps the most straightforward thing you could do is have a virtual BaseType::getValue() function, which is overridden by the subclass-specific getValue(). But these days, we try to avoid ar...
65,926,648
65,926,833
Code with pointers gives out 1 no matter what I tried c++
So I'm doing a code which sums up all elements of field but I have to use pointers :( No matter what I tried I get 1 as output. Tried same code with multiplication but still nothing... Code: #include <iostream> #include <cmath> using namespace std; float vrat=0; int suma (int pok2, int vel22){ for(int z=0; z<vel2...
I think you meant to do something like this #include <iostream> #include <cmath> using namespace std; float vrat=0; int suma (int *pok2, int vel22){ for(int z=0; z<vel22; z++, pok2++){ vrat+=*pok2; } return vrat; } int main() { /// 2. zadatak int vel2; int *vel22=&vel2; c...
65,927,262
65,927,532
How to instantiate abstract child class with parent class
I'm trying to make a Chess game, and I'm having difficulties with creating the objects. My thought process went something like this: Create a game board with 64 tiles, the tiles would have their own position and a pointer to a piece, thus I would be able to "easily" load in and unload a piece. Tile class: class Tile { ...
The Tile don't know which Piece type to instantiate, this is the fundamental problem. What about something like this? (Disclaim, I just implemented some ideas, the code need probably lot of improvements until to get to sufficient quality) #include <array> #include <cassert> #include <memory> #include <vector> using na...
65,927,281
65,927,328
Why doesn't STL "officially" support std::string to std::wstring conversions?
I am aware that std::string and std::wstring come from the same base type std::basic_string<>. But there isn't an "official" way to convert std::string data to std::wstring using the C++ STL? I mean Windows provide MultiByteToWideChar() to convert but why cant the STL provide one? I used std::codecvt before to get it d...
The character encoding of std::string is not defined by the C++ standard, a std::string can hold any encoding that can be represented using 1-byte char elements, which includes UTF-7/8, ISO-8859-x, Windows-125x, etc. Also, the size of wchar_t is implementation-defined, not defined by the standard, so even the encoding ...
65,927,423
65,927,823
Read access violation in tree structure
I'm working on this assignment and I can't seem to stop this read access violation error. I am new to C++ and I think part of my issue is using pointers when they aren't necessary (I think), but I've also looked at this code and traced through it so many times with the debugger that I think I'm missing something obviou...
I found your problem: After you delete the root, remember to set it to nullptr. // Helper HuffmanTree::Node* HuffmanTree::treeRemovalHelper(Node* root) { if (root == nullptr) { return nullptr; } else { treeRemovalHelper(root->rightChild); // THIS IS WHERE I GET THE ERROR treeRemovalHelper(root->le...
65,927,798
65,928,051
Do c++ concepts cause template instantiations to be written to build output?
For libraries with many large and complex template instantiations, it seems to me that one of the major considerations in deciding whether to use concepts would be whether or not the build output is smaller in size. With SFINAE, my understanding is that the following code will cause the template instantiations std::is_...
It seems you are worried about code size. Classes, and here I include instantiations of class templates, are just abstract pieces of information that the compiler knows about. They do not contribute to the code size. Only functions, including member functions, contribute to code size. Member functions of class template...
65,927,984
65,931,719
Adding preprocessor to CL in command line and build *.sln by MSBuild
I need to compile and build c++ project in command-line using MSBiuld without using vs2019 IDE, some preprocessors must be added by command-line! for example, how to define PO preprocessor and run MSBuild to compile below code? #include <iostream> using namespace std; int main() { #ifdef PO cout << "PO is defined...
Based on CL environment variables any prepossessor can be defined by /D for example set CL=/DPO MSBuild project.sln To make sure that the last definition of prepossessors will applied without restarting cmd or commandline tool, use /t:Clean;Rebuild set CL=/DPO MSBuild Project1.sln /t:Clean;Rebuild
65,928,269
65,929,271
Templating ordered vector and std::set
So I want an interface that stores some numbers in order and efficiently perform some operations on them. In practise, a sorted vector performs very well for small sizes, but for theoretical performance and performance on larger instances, I need also a variant that uses something like std::set to perform inserts and e...
You may not need to implement all of the member functions multiple times, but for some, you need to do it in different ways. First, a type trait to check the existance of a lower_bound member function template<class T> struct has_lower_bound_member_func { struct no {}; template<class U = T> // on SFINAE match...
65,928,392
65,928,448
How do I change a value of a 2D-vector?
Thats how I created the 2D-Vector that I want to use as a storing unit for a bunch of letters(font): 62 Letters and 56 int variables for them each('0' and '1' used to simulate a pixel at the point where a '1' is): std::vector<std::vector<int>> letters(62, std::vector<int>(56, 0)); But how do I change a value of it? (f...
#include <vector> #include <iostream> int main() { std::vector<std::vector<int>> letters(62, std::vector<int>(56, 0)); letters[0][0]=1; std::cout<<letters[0][0]; } This compiles and outputs 1 as wanted, so your problem seems to be somewhere else.
65,928,514
65,928,617
How could map::erase know if the interval is valid?
I'm writing a simple program which makes use of std::map::erase. The program is fine, but there is something I do not understand. If I pass to the erase function an interval in which the first iterator is beyond the second one, the function does not erase anything. And it is good. On the other side, if I use std::dista...
From std::distance's specification: The behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first. There's an immaterial exception post-C++11 for random access iterators, but this does not apply to maps. This is undefined behavior, so a "failure", or even a crash is what yo...
65,929,270
66,036,043
_ctermid.h: No such file or directory error on mac without Xcode
I was trying to compile my code using gcc 10.2.8 and I got this error: scons: *** [S.os] Error 1 In file included from /usr/local/Cellar/gcc/10.2.0_2/include/c++/10.2.0/cstdio:42, from Public_Library/C.h:10, from Public_Library/D.h:11, from Public_Library/RS.h:10, ...
I'm just gonna add this in case it might help others. I updated my OSX to big sure and installed Xcode but that did not help. What solved the problem for me was getting an unshallow version of brew with this command: git -C /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core fetch --unshallow and then updating and ...
65,929,478
65,952,859
Loading image but nothing stored in its array (C++, stbi_load)
I want to display the values in the loaded 8 bit image for code analysis purpose and find that the loaded image has no values? I have the following primary lines to help me: #define CHANNEL_NUM 1 int width, height, bpp; uint8_t* image = stbi_load("FTTESTGS.bmp", &width, &height, &bpp, CHANNEL_NUM); if (image == NULL)...
stb_image is written in C and so it relies on C arrays instead of the handy standard containers of C++. It looks like you don't have much experience with C arrays, so I suggest you read up on them. As for the problem at hand, @paddy already mentioned that sizeof doesn't exactly do what you think it does. stbi_load all...
65,929,613
65,947,088
nvJPEG: encode packed BGR
Well, my goal is simple -- trying to create a JPEG encoded image from buffer with packed/interleaved BGR data (could be RGB as well). The NVidia docs contain an example, the proper image input is essentially described here. So I tried the following: #include <nvjpeg.h> // very simple typedef struct { int width; ...
Okaaay, that's strange a bit, but after some time spent on trial and error it occured that NVidia docs lack an essential detail: nvjpegCreateSimple(&nv_handle); nvjpegEncoderStateCreate(nv_handle, &nv_enc_state, stream); nvjpegEncoderParamsCreate(nv_handle, &nv_enc_params, stream); // This has to be do...
65,931,686
65,932,910
find minimum sum of non-neighbouring K entries inside an array
Given an integer array A of size N, find minimum sum of K non-neighboring entries (entries cant be adjacent to one another, for example, if K was 2, you cant add A[2], A[3] and call it minimum sum, even if it was, because those are adjacent/neighboring to one another), example: A[] = {355, 46, 203, 140, 28}, k = 2, res...
This line: if (i < 0 || !k) return 0; If k is 0, you should probably return return 0. But if i < 0 or if the effective length of the array is less than k, you probably need to return a VERY LARGE value such that the summed result goes higher than any valid solution. In my solution, I have the recursion return INT_MAX...
65,931,743
65,932,423
implement stl vector constructor using iterator
I'm trying to implement std::vector with C++98. And, I referred https://www.cplusplus.com/reference/vector/vector/vector/ So, in constructor, I coded the vector like following. explicit vector (size_type n, const value_type& val = value_type(), const allocator_type& alloc = allocator_type()) { ... } t...
The implementation will normally use some kind of type traits to enable/disable iterator version, depending on if the iterator type is really an iterator or not. For example, it would conceptually be something like: template <class InputIterator, typename = enable_if_t<IsIterator_v<InputIterator>> vector(InputIterator ...
65,931,995
65,932,080
Not output is coming when below code is executed in C++ for function overloading
Below is the code, when I am executing. No output in the console. Not sure why. I am testing one example of function overloading in C++. Function Overloading. Created 2 functions of the same name with different arguments. When tried to pass integer value in main during the function call. It worked fine. But when passe...
First you are not outputting the result of the function and 2nd your function is not being called because you are using using namespace stdso when you call max std::max is being called. To call your version ofmax you have to access the global scope. Like this ::max(x, y).
65,932,098
65,933,586
create thread but process shows up?
#include <unistd.h> #include <stdio.h> #include <cstring> #include <thread> void test_cpu() { printf("thread: test_cpu start\n"); int total = 0; while (1) { ++total; } } void test_mem() { printf("thread: test_mem start\n"); int step = 20; int size = 10 * 1024 * 1024; // 10Mb fo...
Linux does not implement threads. It only has Light Weight Processes (LWP) while pthread library wraps them to provide POSIX-compatible thread interface. The main LWP creates its own address space while each subsequent thread LWP shares address space with main LWP. Many utils, such as HTOP (which seems to be on the scr...
65,932,678
65,932,735
Forwarding arguments with auto in C++20?
In C++20, is the following function not ill-formed: void f(auto&&... args) { /*...*/ } and, if not ill-formed, is there a way to forward arguments in the body (without modifying the signature) in exactly the same fashion as the following function: template<typename... Args> void f(Args&&... args) { g(std::forward<...
You can do it with the help of decltype. void f(auto&&... args) { g(std::forward<decltype(args)>(args)...); } When being passed lvalues, decltype(args) yields type T&, std::forward would forward them as lvalues. When being passed rvalues, decltype(args) yields type T&&, std::forward would forward them as rvalues. ...
65,932,926
65,933,457
Explicit instantiation of templated lambda
I just came across a problem to explicit instantiate a templated lambda. The below code does not compile, but I can't figure out what's wrong in this case: [&]<auto... II>(std::index_sequence<II...>) { auto check = [&]<auto I>(){ }; (check<II>(),...); }(std::make_inde...
check itself is not a template. It is an object, of an unspecified closure type, that contains template<auto I> void operator()(); The member function is the template. The error is due to the attempt at supplying template arguments to check. Which is not a template itself, again. The template parameters of a lambda's ...
65,933,498
65,934,163
Qt : Can't update QQuickWidget from outside MainWindow
I have been trying to fix this issue for 2 days now.I have a gmaps QML project , which I've Integrated into my Qt widgets project using the following code: gmap locator; ui->quickWidget->setSource(QUrl::fromLocalFile("/maps/main.qml")); ui->quickWidget->rootContext()->setContextProperty("gmap",&locator); ui->quickWidg...
AFAIK your connect syntax is wrong. Store locator as a member somewhere, in MainWindow for example: public: void setLocator(gmap* loc) { m_locator = loc; } private: gmap* m_locator; Add a slot to MainWindow: private slot: plotmapFromLineEdits() { plotmap(ui->lineEdit_3->text(), ui->lineEdit_4->text(), m_l...
65,933,744
65,934,527
Is using the result of an std::atomic fetch_add to index an array still atomic?
So I wanted to try implementing a fixed sized, wait free stack with the fetch_add and fetch_sub atomic instructions. Say that I have a basic stack, with two operations, push and pop. struct WaitFreeStack { std::atomic<size_t> cur; std::atomic<int>* buf; void push(int i) { buf[cur.fetch_add(1)].stor...
B[X] is not atomic. But if it even would be atomic, it wouldn't help much. The problem is that you have expression of multiple atomic operations. Although operations are atomic, the whole expression is not atomic. Or: an expression containing of multiple atomic operations does not need to be atomic. The class invariant...
65,933,771
65,933,837
Extract first template parameter from a template template parameter and using it inside the class?
I have the following problem: a class template A with several template parameters, I want to build a class B that takes A as template parameter and extract the first template parameter of A in order to use it in some method(think of extracting int from std::vector<int> and returning the default int{}). #include <iostre...
You can't name the template parameter of a template template parameter directly. Even though it looks like you can name it, as you noticed that name can't actually be used. However, you can use explicit specializations for a type that takes a single template parameter. template<typename... Ts> struct B; // incomplete ...
65,934,048
65,946,059
extern template declaration with alias payload
Consider this. There is a class Derived that inherits from some instantiation of a heavy templated class Base, and there are many uses of Derived in various source files. So it is reasonable to have only one Derived-specific instantiation of Base. C++11 allows this via extern template, but the problem here is that I wa...
An explicit instantiation declaration of a specialization of a class template doesn’t prevent instantiating that specialization. After all, you still need to be able to refer to members of the resulting class, which means knowing everything about its layout. What it does do is prevent instantiation of its (non-inline...
65,934,224
65,952,031
Detection of small fast objects with using of Simd::Motion::Detector
I try to use motion detector to detect shooting star in the video with the example of code UseMotionDetector.cpp. If I use the motion detector with default options than nothing works. I think that may be connected with small object size, its fast speed, or big noise. The motions detector has a big amount of parameters ...
I have analysed your video and there are some troubles which don allow to work Simd::Motion::Detector properly with default settings. And you have already listed most of them above: The object (shooting star) has small size. It moves too fast. Time of its existance is short. There is a big noise on the video. In orde...
65,934,459
65,952,043
Why clang-tidy readability-isolate-declaration not fixing code?
I tried to use readability-isolate-declaration check in clang-tidy, but nothing fixed. Example of code from test.cpp file: void f() { int a = 0, b = 1, c = 2; } What I've done: clang-tidy -checks='readability-isolate-declaration' -fix test.cpp Output: Error while trying to load a compilation database: Could not a...
There are several problems here: readability-isolate-declaration check didn't exist in clang-tidy 6. Upgrade to a more recent version If you don't have a compilation database, you can use --(double dash) to specify compilation options. Even if you specify none, this will tell clang-tidy to compile the file. See the do...
65,934,697
65,934,887
Incrementing a uint8_t variable, strange outcome
In a C++ class I've the following code/while loop: uint8_t len = 0; while (*s != ',') { len = (uint8_t)(len + 1u); ++s; } return (len); The outcome should be a value between 0 and max 20. As I receive a strange outcome, and started debugging. When I step through this I get the following values for the variabl...
The values are correct, but your debugger interprets them as char type, not an integer type. You can see escape sequences used in C++ here (and the corresponding values in ASCII). \01 - 1 in octal, 1 in decimal \02 - 2 in octal, 2 in decimal ... \06 - 6 in octal, 6 in decimal \a - equivalent to \07, the ASCII code to u...
65,935,185
65,939,977
Adding additional template arguments to a method of a class which is already templated when defining out-of-line
template <typename T> struct S { T myValue; S(T&); template <typename... Ts> S(Ts&&...); }; Suppose I wanted to define methods out-of-line to be called like S(some, arguments, of, various, types), how would I define the methods? For S(T&), I just do template <typename T> S<T>::S(T&){ /* code */ } , ...
Per cppreference, If the enclosing class declaration is, in turn, a class template, when a member template is defined outside of the class body, it takes two sets of template parameters: one for the enclosing class, and another one for itself: template<typename T1> struct string { // member template function ...
65,935,446
65,935,693
Include implementation file inside namespace to avoid name clashing
I am making a C++ wrapper around a C library. Let's say that the library (let's call it Clib) defines a function like this: // clib.h const char* clib_foo(clib_obj_t* obj); In my wrapper I have the following: // clibpp.h #include <clib.h> namespace clib { std::string_view foo(const clib::obj_t& obj) { ret...
Is this a good idea or possible to do? No, that won't work because the C library - for obvious reasons - doesn't define the functions etc. within that namespace. Why doesn't anybody seem to do it? Because it doesn't work. If you give up the desire to have a header-only wrapper library, then you can avoid "leaking"...
65,935,789
65,936,823
Pass a function as a parameter. C++
I know this question may have been repeated many times, but I didn't understand their answers. So here we go: I have an array of type double* and it is passed as a pointer named arr and the size of the array is passed as int arrsize parameter. Now, here is where I get confused, I want to perform the operation that is s...
Here is an example of the usage with your example. I may call the function fnOper with a pointer to the local function operSum or operSubstract like the following : // call with sum fnOper(arrList, arrListSize, operSum, 15.3); // call with substract fnOper(arrList, arrListSize, operSubstract, 15.3); H...
65,936,284
65,940,143
Performance of std::vector::emplace_back vs. assignment for POD struct
In the below example I see a performance benefit of element assignment (given a vector of the correct size) versus emplace_back (given a vector with reserved storage) for a plain old data (POD) struct. Could someone elaborate where this difference comes from? Thank you very much in advance! Notes This question came up...
First of all, two observations: The index access version is missing a negation of the y argument: compare vec.emplace_back(i, -i); vs. vec[i] = Data(i, i); The times you're printing are microseconds, or "µs" ("ms" usually means milliseconds). Given that 1,000,000 iterations take 864 us, one iteration takes 0.8 ns, or ...
65,936,434
65,936,474
Is there a way to combine these two regex?
Right now I'm processing the following two regex replacements and I'm combining the substitution like this. Is there a way to process the replacement calling regex_replace one time only? std::string test_string = "whatever"; std::regex reg_num("\\\"([0-9]+\\.{0,1}[0-9]*)\\\""); std::regex reg_newline("\n+"); re...
You can use std::string test_string = "\"1\" \"1.50\"\nNew line"; std::regex reg_combined("\"([0-9]+\\.?[0-9]*)\"|\n"); std::cout << std::regex_replace(test_string, reg_combined, "$1"); See the C++ demo. The $1 backreference is initialized with an empty string if Group 1 did not participate in the match, so it is safe...
65,936,511
65,938,509
Can this boost ptree block be shorter (and smarter)?
I'm creating a JSON string exploiting boost ptree library but I'm finding it tedious just by doing the following. I need to add a simple array like "metric.name" : [A, B] to the metrics ptree. Can I do better than this? Or at least write this in a cleaner way. pt::ptree metric_avg; metric_avg.put("", 9999);...
I'd write some helper functions template<typename T> pt::ptree scalar(const T & value) { pt::ptree tree; tree.put("", value); return tree; } template<typename T> pt::ptree array(std::initialiser_list<T> container) { pt::ptree tree; for (auto & v : container) { tree.push_back(scalar(v))...
65,936,856
65,937,431
Getting input on number of rows then drawing a star in the console
I am currently in week 3 of a c++ college course. We are working on for loops. I am having an issue with the homework. We are using nested for loops to draw a diamond out to the console made of *s. The homework part of this was to get the user input for the number of rows in the diamond, then print that diamond. I can ...
I had to do 2 changes in your code to make it work: Replace all 10 with rowNum Second outer loop should be for (x = rowNum; x >= 1; x--) //outer loop Note: It works fine only for an even number of rows. You will need to handle the case of an odd number of rows. Updated code: std::cout << " Enter the Numbers of rows...
65,937,243
65,954,667
Problem getting native code to work in a module in Android Studio
I'm trying to build an Android library that has a combo of native code and Java code calling the C++ code. The C++ is stictly limited to the library. I managed to get a project compiling, but when I launch the unit testing, I get an exception that it cannot find the library. I checked and the code does generate the .so...
Turns out, as mentioned by Michael, that the test environment doesn't support the loading of a native library. I tested the same code by sending it to a phone bundled in an app and it worked fine. Therefore in this case, the unit testing cannot be used to test the library unfortunately.
65,937,611
65,938,648
Implicit conversion to pointer
I have this chunk of code: struct A { operator int*() { return nullptr; } }; int main() { A x; x[42] = 42; int z = x[42]; } To my surprise, the following compiles. The implicit conversion takes place and conditionally converts A to int* and accesses the memory given by the pointer (I returned nullptr j...
These automatic conversions are not applied before calling a member function. A nice example for this is the following struct A { bool operator<(int) const { return true; } }; bool operator>(const A &, int) { return false; } struct B { operator A() { return A(); } }; int main() { ...
65,937,628
65,938,873
Serializing/ deserializing generic objects to string
I am trying to implement a generic serialization method, that I would like to use to serialize/ de-serialize generic custom structures with the following code: #include <string> #include <iostream> class MessageSerializer { public: MessageSerializer(){} ~MessageSerializer(){} template <typename Data> ...
One problem I can think of, is the fact that sizeof(testStruct) is actually almost equal to the size of each element type it contains, ie: sizeof(int) + sizeof(double) + sizeof(std::string) + sizeof(char) The resulting size does not contain the whole actual contents of the std::string object (which are "this is a test...
65,937,647
65,937,697
What is the motivation to decline C rule "a conditional expression does not yield an lvalue"?
What is the motivation to decline C rule a conditional expression does not yield an lvalue? In other words: in C it was a motivation (which exactly?) to not yield an lvalue. Why in C++ this motivation was declined (or reconsidered)?
C++ has references; C does not. You wouldn't be able to bind [mutable] references from an invocation of the conditional operator if not for the following rule: [expr.cond/5]: If the second and third operands are glvalues of the same value category and have the same type, the result is of that type and value category a...
65,937,785
65,937,870
Why isn't it possible to make a tuple which contains a tuple and a unique_ptr as values in C++?
Putting an std::unique_ptr inside an std::tuple works without any issues, but when the tuple contains another tuple together with a unique_ptr as elements, then the compiler throws an error. Example: std::tuple<int, std::unique_ptr<Entity>> tupleA {1, std::move(new Entity)}; //this line throws an error! st...
TL;DR Change your code so it reads std::tuple<std::tuple<int, int>, std::unique_ptr<Derived>> tupleB{std::make_tuple(1,1), std::move(new Derived)}; Details Your compiler tells you what is wrong. It says (MSVC in this case) error C2440: 'initializing': cannot convert from 'initializer list' to 'std::tuplestd::tuple<in...
65,937,925
65,938,103
doubly linked lists initiallisation
Hello so i'm something new to linked lists and data structrs generally so i want to creat two functions one initiallise the doubly linked list and the other one print it but when i compile it it doesnt print anything where did i miss exactly (i heard that i should use the debugger but i didnt understand how to use it o...
Just change while(current->next!=NULL) to while(current!=NULL) Your version stops printing the list too early. (But please learn how to use a debugger, you would have found this error very quickly with a debugger). EDIT You also need to remove this if (head==NULL || first_node==NULL) exit(EXIT_FAILURE); head==NU...
65,937,942
65,938,029
Templated class syntax errors
I have these tree classes. A ListTraits.h , a List.h and main.cpp List.h is a templated implementation of list, and it inherits from ListTraits.h While I believe that my setup for the templated class is correct, I get several syntax errors, that do not seem like they should be there: Specifically, for the Listh.h I get...
typename is a keyword, not the actual name of a type. In List.h when you derived from ListTraitsExtended<typename> and ListTraitsExtended<typename>, and use Node<typename>, you are causing syntax errors since these template expect the name of a type to be passed to it, and you're passing it a keyword. You should give a...
65,938,085
65,941,109
My QOpenGLWidget is being created, but it doesn't work
I have a simple form in which I add an OpenGLWidget, and then set my "MyOpenGLWidget" class to the Promoted Class, it is successfully created, but is not displayed. Its constructor is called, but the initializeGL, resizeGL, and paintGL functions are not called. Here is all my code: main.cpp #include "mainwindow.h" #...
#include "gl/GLU.h" This is not portable and, in particular, doesn't compile on Linux. The proper include is <GL/glu.h>. MyOpenGLWidget::MyOpenGLWidget(QWidget* parent) { qInfo() << "MyOpenGLWidget called"; } You ignore the parent parameter, thus leaving your widget a window, rather than a child of its parent....
65,938,353
65,938,449
Which part of GCC is still involved when building with Clang++ and LLD?
I built a very simple program using Clang++/LLD: clang++ -fuse-ld=lld -o test test.cpp I than ran readelf to confirm that LLD was indeed used as the linker, as mentioned on https://releases.llvm.org/11.0.0/tools/lld/docs/index.html: $ readelf --string-dump .comment test String dump of section '.comment': [ 0] ...
Depending on how you built libc++, you may still be using libgcc and libsupc++ to provide some routines otherwise provided by libc++abi and libcxxrt (and even then, there may still be some parts of libgcc required to make everything work). Depending on the platform, there may still be some startup files or libc bits li...
65,938,898
66,608,139
Library not loaded libpng16.16.dylib Because of incompatible version
I'm trying to display an image on the screen, so I installed SDL2 image. I can successfully compile my code, but when I try to run the resulting executable it gives me this error: dyld: Library not loaded: /usr/local/opt/libpng/lib/libpng16.16.dylib Referenced from: /usr/local/opt/sdl2_image/lib/libSDL2_image-2.0.0.d...
I managed to fix this by deleting the libpng folder in /usr/local/Cellar and installing it with brew install libpng all over again.
65,939,198
65,939,289
Code giving Run Time Error for the problem Maximum XOR pair in a given Range
I am trying to solve a well known problem called the Maximum XOR pair ina given range. If you are unaware about the probelm here is the prompt given to me: You are given an array and Q queries of two types. Type 0: Given a number x , insert the number at the last of the array. Type 1: Given a number X and two integers...
See: https://www.learncpp.com/cpp-tutorial/null-pointers Just like normal variables, pointers are not initialized when they are instantiated. Initialize your pointers to NULL.
65,939,204
65,939,487
C++ Template based get()
I have a class with several members of "similar" type like: class Container { C1 c1; C2 c2; C3 c3; .... template <typename T> const T& get() { ???? } }; The class has a templated method get<T>() which can be used to get a reference to the member of type T - i.e. Container cont; c...
Is there an elegant way to achieve the same without manually implementing the specializations? Starting from C++17, if constexpr template <typename T> T const & get() const { if constexpr ( std::is_same_v<T, C1> ) return c1; else if constexpr ( std::is_same_v<T, C2> ) return c2; else if constexp...
65,939,314
65,939,545
How to enforce type in function params and avoid implicit conversion?
I have a function template<typename T> static inline bool Contains(T container, const typename T::value_type& value) { return std::find(container.begin(), container.end(), value) != container.end(); } Is there an option to disallow implicit conversions for this function? This code should fail compilation: std::vec...
You could add a second template parameter and a static_assert in the function to make sure that second parameter is exactly of the same type as the container's value type. template<typename T, typename U> static inline bool Contains(const T& container, const U& value) { static_assert(std::is_same_v<typename T::v...
65,939,450
65,939,728
Accessing a widget created in a .ui file from code
I'm using Qt5.12.10 inside Visual Studio using Qt VS Tools. I added a QTextEdit widget inside Qt Designer as shown in the image below. I also connected a button to a custom slot named "slot2()" and I want to edit the text inside text box based on what the user typed inside textBox at the time of pressing the "submit" ...
In Qt UI, layout are not use in "compoment code path", you don't have to write centralWidget If you try to use QtCreator, you will have a ton of auto-completion that will help you a lot (at least for the begining) try to write ui.textEdit->setText("HelloWorld");
65,939,711
65,939,996
Setting and checking with a float constant
I know there are a lot of questions on here about why float equality comparison is usually a bad idea. I understand float representation issues, rounding issues, silent promotion of floats to doubles, the dangers in relying upon arithmetic at the bit level, etc. But it seems to me that this should be fine, and no quest...
As long as you're confident MARKER and its copies won't be altered by arithmetic functions or something, there's no issue doing a simple comparison. Maybe consider not using -Wfloat-equal globally but disable warnings locally: #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" /* you...
65,939,939
65,940,954
QNetworkReply error signal cant emits continuously
I need to get xml information from a web page and I can. I do it with a timer for getting information continuously. My problem is, I couldnt catch the error signals continuosly. I only catch it once. I tried examples on QT help page, I read a lot but there is no succes. Here are my codes; mainwindow.h #ifndef MAINWINDO...
In your UpdateDB, you create a new reply: reply = manager->get(request); But you never connect its signals. The very first one gets its signals connected in the constructor, which is why it works for the first one. The fix is easy: move your signal connection for the reply from the constructor to the UpdateDB function...
65,940,116
65,940,452
Returning a pair type in C++ function prevents complation
I have a function in C++ with the following header: int DECLSPEC __cdecl HandleUpdate(uint8_t* MessageBuffer, uint32_t MessageLength ); However, I do not want this function to return an int, I now need it to return a std::pair<uint8_t*, uint32_t>*. Changing literally only the return type (and adding the return value i...
Remove __decslspec(dllexport) from definition in .cpp. And put it in the beginning of the line. Exporting from a DLL Using __declspec(dllexport)
65,940,834
65,945,637
Enforce that all virtual functions from parent class are overridden, from the child class
We are wrapping an object implementing an abstract class IFunctionality, in a class we are writing that also implements IFunctionality. IFunctionality interface is defined in third party code and at the moment it only consists of virtual functions, most of them being pure virtual. Non-pure virtual functions usually hav...
The only solution that won't require runtime overhead or veritable hacks and similar mayhem is to write a libclang analysis pass that verifies that all base virtual methods got overridden, and then run this pass as a part of the build. There are numerous online examples of various static analyses implemented with libcl...
65,940,862
65,941,177
What is the order of control flow while compiling the code for a class in C++?
I am compiling a class, the complete program to which is given below: #include<iostream> using namespace std; class Test{ public: Test() { cout<<"Test variable created...\n"; // accessing width variable in constructor cout<<"Width is "<<width<<".\n"; } ...
Think of inline definitions in a class as just syntactic sugar for declaring the function, and then defining outside of the class. Manually doing that would transform the code to class Test{ public: Test(); void setHeight(int h); void printHeight(); int width = 6; protected: ...
65,940,894
65,941,916
Different results in asio client application when passing a variable or putting an ip string with the same content
There's something I'm unable to figure out. Below is a part of the code from the chat client example from boost asio: https://www.boost.org/doc/libs/1_70_0/doc/html/boost_asio/example/cpp11/chat/chat_client.cpp int Tcp::client(std::string peer_ip) { try { boost::asio::io_context io_context; tcp...
What is the value of the peer_ip variable? If it's also "13.58.174.105" then it would be weird. Otherwise it simply means that the host name cannot be resolved to the IP address. If peer_ip is known to always contain an IP address, there is no need to resolve anything anyways and you can just parse the address instead:...
65,941,215
65,941,275
Do you have to deallocate a const int if you declared it inside a function?
void func() { const int intAge = 24; } What happens with intAge after you run func()? Do you have to deallocate it, or does the C++ compiler do this?
The storage of variables with automatic storage duration is deallocated automatically when the variable goes out of scope. This is handled by the language implementation. In fact, there is no need and no way to manually deallocate memory of any variable. Only dynamic memory can be deallocated manually.
65,941,433
65,941,627
Return type of template method in C++
I have these two header files, List.h and ListTraits.h List.h inherits from ListTraits.h, and it is meant to be a template class implementation of std::list. Now it all works fine but the insert() method implementation. I am obliged to use ListTraits.h, in List.h, and while the std::list insert method returns an iterat...
Change return it; } to return *this; } this permits a technique known as "method chaining". list.insert(a).insert(b).insert(c);
65,941,613
65,941,885
Query about member initialization
while I was doing hackerrank c++ exercises I stumbled upon this code in the discussions section: class BadLengthException : public std::runtime_error { public: BadLengthException(int length) : std::runtime_error{std::to_string(length)} { } }; I don't really understand what is going on after the member initiali...
You are inheriting from the standard exception class std::runtime_error. In this code: class BadLengthException : public std::runtime_error { public: BadLengthException(int length) std::runtime_error{std::to_string(length)} { } }; You are defining a new exception class in terms of std::runtime_error. s...
65,941,918
65,942,403
How to translate C file pointers into generic C++ streams?
Consider the following C code: void openFile(const char *mode, char *filename, FILE **fileptr) { ... *fileptr = fopen(filename, mode); ... } FILE *logstream; if (LOG_FILE_ENABLED) { openFile("w", "mylogfile.txt", logstream); } else { logstream = stderr; } fprintf(logstream, "[DEBUG] Some debug message...\n"...
C++ stream library has pretty ancient design. Nevertheless - its basic idea is that ostream or istream are just wrapper objects over stream-buffers. So you might try something like in this code: std::ostream get_log(bool str) { if (str) return std::ostream(new std::stringbuf()); // else std::filebuf* f = n...
65,942,451
65,942,615
No return value from function with if statment
How can I return from a function if a condition is not met. I'm trying to make a division function and it will return the result of dividing 2 numbers, but if its division by zero how do I return nothing. int div(int n1, int n2) { if (n2 > 0) { return n1 / n2; } } I get this warning when compiling:...
If a function has a return type, it MUST return something. So, you can either: Return a sentinel value that the function and caller agree on to represent a "non-value", eg: int div(int n1, int n2) { if (n2 != 0) { return n1 / n2; } else { return -1; // or whatever makes sense for yo...
65,942,724
65,942,931
Why I'm getting "invalid use of incomplete type" error when I change raw pointer to unique_pointer?
I'm making some SDL2 wrappers in C++. Like this: /* header file */ #include <SDL_mixer.h> #include <memory> class SDL2_Music { public: ~SDL2_Music() { free(); } bool loadMusic(const std::string& path); bool play(int loops = -1); // more methods private: void free(); Mix_Music* music_ = nullptr; }; /* cp...
It seems that Mix_Music is an incomplete type and the correct way to free a Mix_Music object is to call the Mix_FreeMusic function. You cannot dispose of it the way you would a C++ object, namely by using delete. delete would attempt to call the destructor (which cannot be done in this context, since the type is incomp...
65,943,019
65,944,415
g++10, C++20, boost 1.75.0 :: error: 'awaitable' has not been declared in 'boost::asio'
I tried to compile the example: echo_server_with_as_single_default.cpp from boost examples on an: ubuntu 18.04 boost 1.75.0 g++ 10.1.0 Using the following commands to compile&link (I know it's not optimal, I reused the makefile from another project I am working on): g++ -MT bin/.o/src/main.o -MD -MP -MF bin/.d/src/ma...
Currently, coroutines are not enabled by default in gcc. You need to pass the -fcoroutines compiler switch in order to enable them. This will probably change soon as it already works with the current gcc trunk version. See here (I had to comment out the code in main due to the execution time cap in godbolt.org).
65,943,580
65,943,782
CMake shared dll not working after compiling
I've just recently switched from using Visual Studio to CLion as I find it much easier to work in. My biggest problem is that I know nothing about how CMake works and why a very simple project doesn't work for me. I've have a very small project that makes a .dll file for windows - it's only a few lines plus a link to a...
Making DLL in cmake is similar to creating executable! You must call add_library by SHARED flag and list of code files! as you done! And next you must call target_link_libraries after add_library command and introduce libraries to link! I see no target_link_libraries in your post! If you do both, check logs carefully a...
65,943,921
65,943,976
Program wont print out amount of characters that are in a file
Hello all I have to make a program that counts all the characters that are in a given text file I have no errors when I compile it. But when I run it it prompts and takes the name of my file but then ends. Here is my code. #include <string> #include <iostream> #include"counterType.h" #include <fstream> #define MAX 1000...
The line return 0; makes it return from the function and prevents executing lines after that. You should remove that to execute countchar(intchar, indata); and intchar.displayCounter();.
65,944,941
65,944,991
looping through a std::deque and remove entries
I am trying to iterate through a std::deque and remove all of its content. I can do it along the way: for(auto & x: myDeque) { // do something myDeque.pop_front(); } Or I can do myDeque.clear() at the end after the loop. I am wondering which way I should be using? Thanks!
It's almost certainly preferable to do the loop to process the data first, then separately do a myDeque.clear(); to empty it. From a purely theoretical viewpoint, it's O(n) either way, but from a practical viewpoint, clear is almost always going to be at least as fast, and usually faster. The possible exception would b...
65,945,183
65,946,068
How to transform this memcpy into a for?
What is the difference between these two? for (int i = 0; i < numSamples; i++) { mData[sampleIndex++] = *buffer++ * (1.0f / 32768); } and memcpy(&mData[sampleIndex], buffer, (numSamples * sizeof(float))); If I understood correct, the first copies numSamples float values to mData, one by one. The second one, cop...
What is the difference between these two? for (int i = 0; i < numSamples; i++) { mData[sampleIndex++] = *buffer++ * (1.0f / 32768); } // and memcpy(&mData[sampleIndex], buffer, (numSamples * sizeof(float))); These are quite different given the * (1.0f / 32768);. I assume the code compare is setting the scaling di...
65,945,216
65,945,526
Why do std range algorithms return std::ranges::dangling for rvalue arguments instead of... well, just working?
Here is my (simplified) attempt to implement a ranges::min_element version that would work for both lvalue and rvalue arguments: #include <iterator> #include <algorithm> #include <type_traits> #include <utility> namespace better_std_ranges { template<typename Range> constexpr auto min_element(Range& range) ...
There are two problems with this approach. First, it breaks the semantics of the algorithm. The point of min_element (and any other algorithm that returns an iterator) is to return an iterator into the range. You're not doing that - you're returning an iterator into a different range. That really confuses the notion of...
65,945,454
65,948,104
Is it possible to specialize a method of a template class on another templated class?
I have a class A that is a template, and I want to specialize the method foo() if the class is a std::vector<T> with T generic, I am getting the error: invalid use of incomplete type. I'd like to avoid writing all specializations for all possible vectors. #include <iostream> #include <vector> template<typename V> stru...
Just using c++20 contrians: template <typename V> struct A { void foo() { std::cout << "A<V>\n"; } void foo() requires (std::same_as<V, std::vector<typename V::value_type>>) { std::cout << "A<V<T>>\n"; } }; Then this works: A<int>{}.foo(); // call normal one A<std::vector<int>>{}.foo(); // call specialized ...
65,945,504
65,945,950
Is there a way to use QCommandLineParser with an option followed by multiple values?
I need to make my app scan for a number of ports given as command line arguments and so far I have this: QCommandLineOption portScanOption(QStringList() << "p" << "target-port", QCoreApplication::translate("main", "Scan <port> for other instances"), QCoreApplication::translate("main"...
This is already handled - the syntax you propose doesn't quite fit QCommandLineParser. Either use -p 5000,7000,8000 or -p "5000 7000 8000". All those ports will be the value of the port option, and you can then separate them with split(QRegularExpression("[, ]"), Qt::SkipEmptyParts) (that's QString::split). E.g.: auto ...
65,945,619
65,946,043
Improving a variadic template function using new c++14 / c++17 features
I am newbie to variadic templates, still I managed to program some code in c++11 using it, but I still feel sour about result because it lacks expressivity. The issue is to implement a function that accept several bool conditions (from 1 to whatever) and returns an integer code indicating in what place is the first "fa...
C++17 with folding: template<class... Bools> constexpr unsigned error_code(Bools... Bs) { unsigned rv = 1; (void) ((rv += Bs, !Bs) || ...); return rv % (sizeof...(Bs) + 1); } Unasked for so it's just a bonus - the same idea, C++20: constexpr unsigned error_code(auto... Bs) { unsigned rv = 1; (void...
65,945,941
65,946,061
Calling and initializing static member function of class
I have the following code: #include <stdint.h> #include <inttypes.h> #include <stdio.h> class A { public: int f(); int (A::*x)(); }; int A::f() { return 1; } int main() { A a; a.x = &A::f; printf("%d\n",(a.*(a.x))()); } Where I can initialize the function pointer correctly. But I want to make the function poi...
A static pointer-to-member-function (I guess you already know this is different from a pointer to a static member function) is a kind of static member data, so you have to provide a definition outside the class like you would do with other static member data. class A { public: int f(); static int (A::*x)(); }; /...
65,946,053
65,946,250
C++ primer 5 th ed. matching flag type
I have this exercise from C++ primer 5th ed. Exercise 17.26: Rewrite your phone program so that it writes only the second and subsequent phone numbers for people with more than one phone number. my solution for the previous exercise: A program for finding the first match and format it using the formatting string fmt ...
It is a bit tricky: you need to get rid off the first match then apply the matching flag: std::regex_constants::format_no_copyinto std::regex_replace: std::sregex_iterator is your choice because it can be initialized to denote the first match then we use its member: suffix().str() passing it to std::regex_replace: i...
65,946,626
65,946,670
Why does this std::function and operator cause a segmentation fault?
I don't see anything wrong with this code but it gives me a seg fault. Changing the std::function to a normal function solves the problem. Also removing the addition in the overloaded operator solves the problem. Also changing the Point constructor from const int& to int solves the problem. But I don't understand why. ...
std::function<const Point&()> fn = []{ return p1; }; Because you didn't specify the return value of the lambda, it defaults to returning it by value. So fn is trying to return a reference to a temporary, which is undefined behavior. Do this instead: std::function<const Point&()> fn = []() -> const Point& { return p1; ...
65,946,885
65,947,070
What causes an MFC app menu-bar to be greyed out?
I'm working on a legacy MFC project. The project includes an SDI application which has a menu-bar. After launch, the menu-bar for the application is entirely greyed out: I've read through the following questions, but they don't seem to address my situation: MFC Menu Item remains grayed Menu items are being enabled or ...
The "grayed out" means that the widget is disabled. You'll need to EnableWindow on the widget. Specifying EnableWindow(FALSE) will disable the widget (window). The tough part is to find out where or how this function is called. The state may be specified in a resource file. It may also be stated in an initialization me...
65,946,930
65,947,030
Ambiguous Overloaded Operator C++20
I'm trying to test my project in the latest Visual Studio and Clang versions. One of the errors that pops up is related to an ambiguous operator (with reversed parameter order). This does not seem to pop up in C++17. For example: (https://godbolt.org/z/Gazbbo) struct A { bool operator==(const A& other) const { retu...
In C++17, yes, the only viable candidate was b.operator==(B(a)). But in C++20, comparison operators have more functionality. Equality can now consider reversed and rewritten candidates as well. So when consider the expression b == a we also consider the expression a == b. As a result, we have two candidates: bool B::o...
65,947,287
65,947,335
why is std::string causing a memory leak in a class even after deleting
I am building a class that uses void* as a storage method. I am aware that it is not a good idea to use void*. But I don't know what value it will hold at compile time, so I thought it was the best solution. It works perfectly with everything, including C strings, but doesn't work with std::string. It causes a really b...
If you allocate a string, cast the pointer to a void *, then delete that, you will be trying to delete a void thing, not a string thing. For example, any class that allocates secondary storage (above and beyond the actual object being created with new) will most likely run into trouble: #include <iostream> class Y { p...
65,947,587
65,947,689
to get the real type information of a pointer in c++
class myclass1 { public: virtual ~myclass1() { } }; class myclass2 : public myclass1 { }; int main() { myclass1 obj1; myclass2 obj2; myclass1 *p1 = &obj2; myclass2 *p2 = static_cast<myclass2 *>(&obj1); if( p1 && p2){ cout << typeid(p1).name() << endl; cout << typeid(p2...
typeid(p1) will give you the type of the pointer p1, which will always be myclass1 * (the string P8myclass1 is the mangled name for the type myclass1 *). If you want the type of the pointed-at object, you want typeid(*p1), which should be myclass2 in this case. With p2, typeid(p2) will be myclass2 *, while typeid(*p2)...
65,947,589
65,947,601
Counting the number of certain characters in a string
I'm new to C++, and since my first computer language is Python, I don't really understand what I did wrong here. The purpose of this code is to find out how many certain alphabets are included in a string of length 8, but I keep getting the following error: ISO C++ forbids comparison between pointer and integer [-fper...
if (temp[i] == "F") { should be if (temp[i] == 'F') {. 'F' is a character (char) "F" is a C-string (const char[2] which decays to const char*).
65,947,612
65,948,635
Why does introducing std::mutex to member class generate this compile error?
In the code below, class B contains an array of member class class A. B::A has one member bool and one member std::thread. The code below compiles fine: // main.cpp #include <mutex> #include <thread> class B { public: B(); private: class A { public: A( const bool& b ) : b_( b ) {} bool b_; ...
The apparent, likely cause of the bug is a subtle difference between copy-initialization and copy-list-initialization: struct A { A(int); A(A&&)=delete; } a=1, // error: not movable b=A(1), // error c={1}, // OK, no temporary constructed d[]={1}, // error e[]={A{1}}, // error f[]={...
65,948,493
65,948,548
Why I get Error "No such file or directory", when I try to include a header file?
I have main.cpp and add.cpp add.h files When I try to include add.h I get following compilation error main.cpp:2:10: fatal error: add.h: No such file or directory 2 | #include <add.h> | ^~~~~~~ compilation terminated. Here is the code: main.cpp #include <iostream> #include <add.h> using namespace st...
#include <add.h> causes the compiler to search the system include directories for the file add.h, but not the current directory. If you want to include a file add.h which is in the current directory, use: #include "add.h"
65,948,520
65,948,634
How to use print() to print the linked list
I wrote the print() in my code and try to use it to print out the data in the list. Also the text file below. Thank you for any suggestions. Try to print but it gave me the error :"undefined reference to `print(dbl_linked_list_t const*)'" Also, can you check my read()? I didn't know if I was read in the data into my pr...
The definition of print function is missing const. print is declared as void print(const dbl_linked_list_t*); but defined as (missing const) void print(dbl_linked_list_t* lPtr){ ... }
65,949,048
65,949,230
Is it reasonable to consider the interface in C++ is for the communication between "the data" and "the program"?
On page 557, the book "C++ Primer Plus by Stephen Prata" says OOP emphasizes how a program represents data.The first step toward solving a programming problem by using the OOP approach is to describe the data in terms of its interface with the program, specifying how the data is used. Next, you need to design a class ...
Yes, "its" means "the data's interface" in that context. Another way to look at it is an object is intermediate between data local to a function, and global to the entire program. Sometimes it's convenient for a group of functions to share data, and so those functions and data are grouped into an object. To ensure the ...
65,949,104
65,949,539
C++: How to use a 'for' loop to multiply 2D arrays?
I'm writing a program to populate two multidimensional arrays and multiply their elements using for loops only. The code's pretty simple yet I'm stuck with a host of errors from the multiplication loop. I can't wrap my head around this one. Is there a problem with my loop syntax? I'll attach the code below. Lines 48 a...
You can not declare two variables in the for loop as you are doing it. You can check this thread for ways to achieve it. On the snippet you share, certain variables are not declared, numRows, numCols, myNums1. indexCols2 is not initialized, even though the for loop is not correct as it is. As @cigien mentioned in the c...
65,949,122
65,949,151
What is the life cycle of a class instance returned by function?
Here's a program: #include <cstring> #include <iostream> #include <string> std::string fun(){ return "this is a string"; } int main(){ const char *str = fun().c_str(); if(strcmp(str, "this is a string1") == 0){ std::cout << "ok" << std::endl; } } When I compiled with AddressSanitizer, I got: ==...
In this statement: const char *str = fun().c_str(); // oops, str is invalid, since the temporary has been destroyed fun returns a temporary std::string, and you're taking a pointer to that with c_str. However, that temporary dies at the end of the full expression, in this case at the ;. So you're left with a pointer t...
65,949,241
65,949,503
Count all possible paths from top left to bottom right of a mXn matrix
I should return number of possible paths from top left to bottom right in an n*m matrix. here is my code. class Solution { public: map<pair<int,int>,long long int>mp; long long int numberOfPaths(int m, int n){ if(n==1 || m==1) { return 1; } if(mp[make_pair(n,m)]!=0) r...
Short answer: Your expected answer is wrong. The correct answer for input 19 and 71 is indeed 2418561960739869780. Long answer: Firstly, always keep code formatted - it helps yourself and the reader of such questions gather some motivation to read the question. Here is a slightly better formatted version: class Solutio...
65,949,894
65,949,945
Can I overload function templates based on properties?
I want to get a common property from different families of classes. For some, I can just use a member, for some I need to call a function. Can I overload template functions in a way so that the compiler chooses the fitting template function based on whether the class has functionA, functionB or member? Currently I get ...
You can overload them with SFINAE. e.g. template<class TypeWithFunctionA> auto doSomething(const TypeWithFunctionA & h) -> decltype(h.functionA()) { return h.functionA(); } template<class TypeWithFunctionB> auto doSomething(const TypeWithFunctionB & h) -> decltype(h.functionB()) { return h.functionB(); } template...
65,950,064
65,950,132
Assignment of function template instantiation to function pointer?
Please consider the following C++20 program: void (*p)(int x); void f(auto x) { p = f; } int main() { f(4.2); } Is this ill-formed? What I would have expected to happen is that f(4.2) instantiates f as void(double), and so the assignment of p to f should be a type mismatch. But, g++ accepts this without wa...
so the assignment of p to f should be a type mismatch No, p = f; causes the instantiation of void(int), then it's assigned to p.
65,950,288
65,950,333
Accessing a string by its index elements and trying to Print it
I am trying to create a string by accessing its individual index positions and trying to print it. #include<iostream> #include<string> using namespace std; int main() { string s=""; s[0]='a'; s[1]='b'; s[2]='c'; s[3]='d'; cout << s << endl; for(int i = 0; i < 4; i++) cout << s[i]...
Strings don't grow automatically This string has zero size string s=""; This code is an error because s[0] does not exist (since the string has zero size). s[0]='a'; Because this is an error your program has undefined behaviour, which means any output is possible, including the strange behaviour you see. ...
65,950,290
65,950,932
What is the best practice when defining const& and && version of a set method?
If I want to define a method like a setter for a std::vector member (or movable object) I can do it like this: void set(const std::vector<int>& v) { _v = v; } But also I need to add void set(std::vector<int>&& v) { _v = std::move(v); } Right? Is it always best to define both in order to handle temporaries that can ...
If you know the type has an efficient move constructor (which std::vector<int> does), then you can just take by value and move from the argument: void set(std::vector<int> v) { _v = std::move(v); } That way, when called with an lvalue it will be copied, but when called with an rvalue it will be moved.
65,950,473
65,950,829
Can I run any c or c++ spesific commands at linux terminal without excecute?
I want to test as fast as C/C++ functions how works. Assume I don't know how printf works. Kind newbie I glanced man pages and learned this prints out what I want, but I need to try how it's work immediately. Or I need a try a math.h function like pow(2,3) I need to ensure which term powered 23 or 32 so on... Can I ge...
Can I get output of specific command without compile, debug, execute? No. You have to compile and then execute a C or a C++ program. Is there any way to do on Linux terminal? You can write a small script that creates a temporary file, compiles the code, runs it and then removes the temporary file. Save the followin...