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
63,130,211
63,130,438
Expand variadic arguments in initializer list fails
I try to create a simple program in which I want to create vector of future arguments. I created a wrapper function which is used to submit lambda functions and stores internally in a vector the future objects I use an intermediate step in which I create an initiliazer_list using variadic arguments . But fails to comp...
Yes, they are of different types so cannot be in the same init-list easily. Your best options should probably be: Either push them all into asyncVec in the same fold-expression. template<typename... TemplatePtr> void submit(TemplatePtr... pFunc) { (asyncVec.emplace_back(async(launch::async, std::move(pFunc), 4, 5))...
63,130,256
63,130,427
Simplest fix for "error: taking the address of a temporary object"?
struct context* ctx = &(struct context){ 0 }; I am trying to use clang++ C++ compiler to compile C code, possibly with minimal code changes. For the above code I get error: error: taking the address of a temporary object of type 'struct context' [-Waddress-of-temporary] Is there a compiler switch to make it tolerate ...
Is there a compiler switch to make it tolerate such constructs?` -Wno-address-of-temporary... But that would be just wrong. Compiling such code in C++ will result in a dangling pointer pointing to a memory of an object whose lifetime ended. The lifetime of temporary ends on ; in that code - after the assignment, the ...
63,130,488
63,130,733
c++ auto_ptr destroyed when passed into a function
Suppose that we have void UsePointer (auto_ptr <CSomeClass> spObj) { spObj->DoSomething(); } and we have a main function: int main() { auto_ptr <CSomeClass> spObject (new CSomeClass ()); UsePointer (spObject); // spObject->DoSomthing (); would be invalid. } The book says "the object was destroyed when...
Is the pointer copied when passed into UsePointer function? Hence the owernship is transferred? Yes. Unless the function parameter is reference qualified, arguments pass by value. For auto_ptr that involves copying, and thus passing ownership. What do I need to if want spObject not be destroyed? Do I need to pass th...
63,130,629
63,131,802
c++ call python script failed, when the called scipt import another script
I want to call a python scipt sayhello.py which located at D:/semantic_segmentation/scripts in my c++ program, here is my c++ code: Py_Initialize(); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('D:/semantic_segmentation/scripts')"); PyObject* pModule = PyImport_ImportModule("sayhello"); the co...
It looks like your python code assumes the current working directory of the process is the D:/semantic_segmentation/scripts directory, which is not necessarily the case. Here are two solutions: change the working directory of your c++ program with chdir or the windows equivalent, or change the python code to compute a...
63,131,101
63,131,675
How to structure the inheritance from generic tree to a-b tree
I am trying to implement an a-b tree, as a derived class from a generic tree. The generic tree node is as follows: template<typename T> struct TreeNode { T value; std::vector<TreeNode*> children; //Some other trivial stuff }; The structure of the a-b node is as follows: template<typename T> struct ABTreeNo...
Sharing code by inheritance is a bad design. Better is to use Composition - see https://en.wikipedia.org/wiki/Composition_over_inheritance To share code between different implementations of various trees I would extract common fields into a struct. template <class T, class ChildT> struct TreeNodeCommons { T nodeValue...
63,131,370
63,131,622
Why does this happen ? (reasks user) C++
Hello so I'm trying to make a game (Pokémon based) using C++ and i'm getting weird results. Basically you input your name and it says are you called that . If yes , you get asked what type you prefer. However if you input N then Y , for some reason it asks the user more than once what type they prefer. My code : Animal...
That's because you are using recurrence for validation. It's going to give you hard time if you continue doing that. Let's examine your call stack (number near function name is recursion depth): main() calls startGame1 startGame1 asks for input, you enter N, startGame2 is called. startGame2 calls askType askType does ...
63,131,511
63,132,926
Issue of 'Uncaught TypeError: Callback must be a function' using C++ in Atom editor
I'm using Atom to compile and run C++ code on Mac, however I'm getting this error on simple program. I am new to C++. Please help! Note: I was able to run this in Xcode. main.cpp file: #include "Cube.h" #include <iostream> int main() { Cube c; c.setLength(3.48); double volume = c.getVolume(); std::cout << "V...
You need a real build system. Atom-gpp is only suitable for single .cpp files. I suggest you invest some time into CMake, which is a modern build system (primarily) for C and C++. Given your project, put the following in CMakeLists.txt next to your .cpp files: cmake_minimum_required(VERSION 3.10) project(course1) add_...
63,131,747
63,131,914
Problem with converting map to priority queue
Help me please, why it is not work? I want to convert map<int, int> to priority queue of pairs, which which will be sorted by the second argument. auto cmp = [](pair<int, int>& p1, pair<int, int>& p2) {return p1.second > p2.second;}; priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> q; map<int, in...
Change your code to this priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> q(cmp); Lambda functions don't have default constructors (at least in some versions of C++) the true situation seems to be complicated. https://en.cppreference.com/w/cpp/language/lambda
63,132,229
63,145,329
How to hide dependencies of implementation of template class?
In regular C++ classes, we can have a class A as follows: in A.h: class A { public: void method(); // rest of class declaration }; in A.cpp: #include "A.h" #include "implementation_dependencies.h" void A::method(){ // use dependencies to implement method } But if A is a template class, this isn't...
From c++20, you can do this with modules: // A.cpp export module A; export template <typename> class A { // ... }; #include "implementation_dependencies.h" export template <typename T> void A<T>::method() { // use dependencies, but don't export them from this module }
63,132,255
63,132,454
g++10 get the c++20 removed features back?
I'd like to compile my project along with grpc using c++20. The problem is grpc have a dependency on abseil-cpp. And abseil-cpp failed to compile because it uses some features removed from c++20, like std::result_of and member typedefs of std::allocator. When compiled under MSVC, its easy to get those features back. Bu...
It looks like C++20 support is underway, e.g. removing result_of and uses of allocator have been fixed if you build in C++20 mode. I would suggest waiting for grpc / abseil to be updated, perhaps applying those fixes yourself in the mean time.
63,132,268
63,132,504
While trying to use SFINAE to disable functions, have I created undefined behavior?
I am trying to use SFINAE to disable certain functions of a class based on some non-templated enum arguments. The following code does NOT compile with gcc, but appears to compile and work as expected when using the msvc compiler. #include <iostream> #include <type_traits> enum class B { VARIANT1, VARIANT2 }; template...
GCC is right. And it's because you aren't using SFINAE for your function. It may appear that you do because you employ utilities for SFINAE from the standard library, but there is a crucial ingredient missing here. The 'S' in "SFINAE" stands for substitution. The substitution of template arguments into the parameters o...
63,132,398
63,132,857
Can I implement a push_back method for linked list in that way?
I've already been doing push_back methods for link lists like that: #include <iostream> using namespace std; class Node{ public: int data; Node* next; Node(int data, Node* next = nullptr){ this->data = data; this->next = next; } }; Node* head = nullptr; void push_back(int data){ ...
You could do something like that, by taking a pointer to the pointer you wish to change. void push_back(int data){ Node** current = &head; while(*current != nullptr) { current = &(*current)->next; } *current = new Node(data); } As a bonus, you don't have a special case for empty lists anymore.
63,133,115
63,133,156
value turned const in lambda capture?
I have this simple code: std::shared_ptr<std::string> s; auto bla = [s]() { s.reset(); }; What I meant this to do is that the shared_ptr be captured by the lambda and then reset once the lambda is called. Compiling this with VS yields the following error: error C2662: 'void std::shared_ptr<std::string>::reset(voi...
When capturing by copy, all captured objects are implicitly const. You have to explicitly mark lambda as mutable to disable that: auto bla = [s]() mutable { s.reset(); }; Also, if you want to reset actual s and not a copy, you want to capture by reference. You don't need mutable when capturing by reference, in thi...
63,133,137
63,133,828
taking string input as parameter in constructor in OOP
This code is showing error when I make an instance of the class website. The instance has to use the explicit constructor which I have defined in the class definition. So I am passing a string value in it. This value is being received by an array of character type in the constructor which then initializes a pointer poi...
String literals are 'const', try this: class Website { private: const char *name; Webpage webpage1{24.5,37.2}; Webpage webpage2; Webpage webpage3{10,18.7}; Webpage webpage4; public: Website() { cout << "Website default constructor called." << endl; }; Website(const char* n):n...
63,133,185
63,133,915
Double free or corruption (fasttop) error when trying to use setter
I have created a basic class object with setter and getters based on the text book. The code work fine but when I attempt to change the data in name from Square to Circle, I get error : double free or corruption (fasttop). Can someone enlighten me what is happening here? Is this due to some kind of memory allocation er...
Your setName and setContains functions don't have any return statements while their return types are not void. Therefore, executing these functions invokes undefined behavior. N3337 6.6.3 The return statement says: Flowing off the end of a function is equivalent to a return with no value; this results in undefined beh...
63,133,364
63,144,312
boost::regex_constants::error_type to string
I have a function checks if an expression matches a regex, and returns a boost::regex_constants::error_type, it logs the error in case of exception: boost::regex_constants::error_type RegexMatch(const std::string& p_expression, const std::string& p_pattern) { boost::regex_constants::error_type returnValue = boost::...
First off, the reason that because when returning a const char*, for some error types, for example error_ok, "et*)" is returned instead of "Success". was happening was because you were returning a stale pointer (what() points to member data inside a runtime_error instance, and it would be destructed after returning f...
63,134,044
63,189,508
Is it possible to disable p2p and only use HTTPSeed in libtorrent
I'm doing some research for a project and was wondering if it's possible to disable p2p using the libtorrent C++ library. When I say disable I mean make it so the client will only download from the HTTPSeeds, basically, I'm hoping to make a checkbox for use p2p to speed up downloads, so if people choose to turn it off,...
You could set enable_outgoing_utp, enable_incoming_utp, enable_outgoing_tcp and enable_incoming_tcp settings all to false. Documentation here.
63,134,299
63,154,105
How to increase max stack size in c++ using vscode
In many dynamic programming and graph problems it is required to do long depth recursion. I am currently using vscode and mingw in windows for my c++ programs. But in default,as per my knowledge windows has 1MB max stack size .So I gets segmentation fault / stackoverflow problems. I know pretty well that I can change e...
VSCode uses powershell as its shell and commas are special characters for powershell. You need to put them inside quotes. g++ -O2 -std=c++11 -Wall "-Wl,--stack=268435456" Untitled1.cpp -o a.exe should work.
63,134,443
63,134,580
How can I initilize a variable of a type which is wrapped around another type?
I can do this class Draw { public: Draw(); static const Shape_f32 shape; } But what if I want to initilize the inner types of shape to a certain value? Like shape.side.value = 5.0; I tried to do these different solutions: 1. class Draw { public: Draw(); static const Shape_f32 shape.shape.value = 5....
You can use list initialisation: inline static const Shape_f32 shape { .side { .value = 5.0, }, }; Prior to C++20 however, you cannot use designated initialisers, and you need to initialise the members in order of their declaration instead. P.S. If you define the static variable in a header, you should...
63,135,099
63,136,031
Type conversion and type casting of pointers in C++
I have been trying to wrap my head around the differences between type casting and type conversion. What i've learnt is that essentially when the underlying value or bit representation of one type is changed to another value, we have performed a conversion. While in pure type casting we simply tell the compiler to trea...
It's important to understand that, as far as the C++ language is concerned, the distinction you're talking about does not exist. All "*_casts" (and their C equivalents) are all just (explicit) conversions. And for the language, all conversions create a new object (or a new reference to an existing object if the convers...
63,135,687
63,144,272
boost::interprocess message queue timed_receive() internal procedure
im currently using the timed_receive() method from the boost::interprocess library for receiving data. Since the timing of the received messages will vary I used this method over the receive() method. msgque->timed_receive((void*) &message,sizeof(int),recvd_size,priority, boost::posix_time::ptime(microsec_c...
The library doesn't need to document how it works, because that's an implementation detail. You ideally do not need to know, which is why you use a library in the first place. You can expect the library to implement it in terms of more primitive library building blocks: shared_memory_object + mapped_region mutex, + co...
63,135,764
63,137,030
Strange lua push/pop behavior with the C API
I noticed that pushing and popping values onto/off the stack in lua using the C API on my target platform (32-bit PowerPC architecture) behaves very oddly. Consider the following test function: void test_pushing_and_popping(lua_State *lua) { printf("### STARTING PUSHING/POPPING TEST ###\n"); lua_dump_stack(lua)...
The initial compliation error I got was worded as follows: #error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \ or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)" It turns out I used the -DLUA_32BITS compilation flag which causes the data type sizes to be too small: #define LUA_INTEGER ...
63,136,333
63,160,358
Parsing XML's with Boost PTree w/o tags
I would like to know if Boost Ptree allows parsing .xml files without having the attribute tags known. I have an XML file that will regularly be updated with new tags, new data, and even remove certain tags. These regular changes prompted me to look into parsing the file without hardcoding the attribute name. Is there ...
Ptrees aren't ideal for parsing XML but Boost is so integrated into the rest of my project that it would be incredibly taxing to use libxml2 or another parser Sorry, that makes no sense. There are header-only options, and a good number of very light-weight options. See What XML parser should I use in C++? Since Boost...
63,136,602
63,142,976
Combine two sentences with some words missing in both or any one
Input 1 - 'My name is Mayank' Input 2 - 'My will name not Mayank' Output - 'My will name is not Mayank' or 'My will name not is Mayank' I want to combine two string, both of them may contain some extra words (which is missing in the other). If there are multiple outputs, then please give any. Please provide any hint...
If you keep note of the set of words preceding every word in each sentence you get {'My': set(), 'name': {'My', 'will'}, 'is': {'My', 'name'}, 'Mayank': {'My', 'is', 'name', 'not', 'will'}, 'will': {'My'}, 'not': {'My', 'name', 'will'}} You can then iterate on the list generating words whose comple...
63,136,669
63,136,918
Send string from pyserial to arduino
Hello i need to send spotify song name from python to arduino, but arduino receive only numbers like '122', '117' etc. How to send all string? Here is my code python code: import serial import time from SwSpotify import spotify ser = serial.Serial('COM3', 9600) while True: print(spotify.song()) ser.write(spotif...
In order to display a character use lcd.write http://www.arduino.cc/en/Tutorial/LiquidCrystalSerialDisplay */ // include the library code: #include <LiquidCrystal.h> // initialize the library by associating any needed LCD interface pin // with the arduino pin number it is connected to const int rs = 12, en = 11, d4 ...
63,136,777
63,989,085
How could just loading a dll lead to 100 CPU load in my main application?
I have a perfectly working program which connects to a video camera (an IDS uEye camera) and continuously grabs frames from it and displays them. However, when loading a specific dll before connecting to the camera, the program runs with 100% CPU load. If I load the dll after connecting to the camera, the program runs ...
After a lot of digging I found the answer and it is both frustratingly simple and frustrating by itself: It is Microsoft's poor support of OpenMP. When I disabled OpenMP in my project, the camera driver runs just fine. The reason seems to be that the Microsoft compiler uses OpenMP with busy waiting and there is also th...
63,136,911
63,138,478
Copying text from pastebin to a variable c++
I'm trying to create a program which will copy data from a link and then save it to a variable. I mean I have link like <https://pastebin.com/raw/2BVSSFVF> and I want my program to load this text to my variable, is that possible?
Presuming that you want to follow the link and download what it refers to... Strictly speaking the answer to the question "is that possible?" is simply "yes". It could be done by scraping the webpages themselves or more ideally if pastebin has an API you can call. Some brief googling indicates pastebin might have a RES...
63,136,919
63,137,052
I tried creating merge sort using vectors for a school project. Didn't get the desired output
#include<iostream> #include<vector> using namespace std; void sort(vector <int> &v, int i, int j, int end2) { vector <int> v1; int start1=i, start2=j, end1=j; while((start1<end1)||(start2<end2)) { if((start1<end1)&&(start2<end2)) { if(v[start1]<v[start2]) { ...
What's this piece of code for? int s=i; while(s<end2) { v[i]=v1[i]; i++; } Should just be removed IMHO. Shouldn't this code else if (v[start1]==v[start2]) { v1.push_back(v[start1]); start1++; start2++; } actually be this? else if (v[start1]==...
63,137,309
63,138,785
Initialize texture once for derived classes in sfml
Recently, I've tried to exercise SFML with textures. However, I've encountered some problems. SFML website tells me that the most efficient way to use textures is to update sprites. Otherwise, our program may consume a lot of memory. I have one base class and two other classes derived from it. How may I initialize my t...
The Flyweight Pattern SFML website tells me that the most efficient way to use textures is to update sprites. Otherwise, our program may consume a lot of memory. Yes, the relationship between sf::Sprite and sf::Texture corresponds to The Flyweight Pattern, a structural design pattern. An sf::Texture is a kind of heav...
63,137,352
63,144,104
how to match nocase c-string in boost multi_index_container by hash
check out code below, i overload hash function and string-equal function for nocase-c-string key(const char*), but the result is not what i expected: the main function will print not found, how to make it matched? struct hash_c_string { std::size_t operator()(const char *ctx) const { return MurmurHash2(...
You're attempting to hash by a derived property, namely a case-folded name. This is going to be expensive even if done right¹. All the signals here indicate that you might be doing these in the name of performance. If you need the case-insensitive lookup, I suggest to reify a key to index on, so you can have natural ha...
63,137,918
63,138,504
Translating OpenGL 4.5 stuff to OpenGL 4.0 make my program crash
I would excuse me if the title is not explicit I have a little program which print some mesh on screen, the code I use to init and draw is the following : (Here you have the init code) glGenVertexArrays(1, &VAO); glCreateBuffers(1, &VerticesVBO); glCreateBuffers(1, &NormalVBO); glCreateBuffers(1, &ColorVBO); glBindVe...
You have to use glBufferData instead of glBufferSubData because it doesn't allocate space in gpu
63,137,936
63,138,267
CMake project with independent subprojects
I am trying to create a cmake project which has the following directory structure: root_folder lib common_library_for_all_submodules submodule_1 src main.cpp tests main_test.cpp submodule_2 src main.cpp tests main_test.cpp Being new to C++ and also to CMake I have the following conf...
You can use several CMakeLists.txt files, use add_subdirectory statement. To declare library (which will be used in another subproject) use add_library. To declare app - add_executable. To link library to app - target_link_libraries(app1 PRIVATE utils common). This is short and very common description-example. There ar...
63,138,549
63,138,775
Ros callback function parameter explained
Why in ROS when you do call a callback function there is the header as following: void error_sub(const std_msgs::UInt16::ConstPtr& msg); From the following definition void error_sub(const std_msgs::UInt16::ConstPtr& msg) { ROS_INFO("I heard: [%d]", msg->data); error = msg->data; } Where is the problem if yo...
Either one will work, because of how ParameterAdapter is used to call the subscription callback. In fact, there are many possible callback function signatures: void callback(const boost::shared_ptr<M const>&); // (const M::ConstPtr&) void callback(const boost::shared_ptr<M>&); // (const M::Ptr&) void callback(b...
63,138,885
63,139,102
Can't draw Bresenham, OpenGL
I am implementing the Bresenham algorithm, and I am pretty certain that my implementation is correct, but the screen is still blank, I think I'm using OpenGL wrong. This is my full program. I am using nupengl.core.0.1.0.1 if it helps #include <GL\glew.h> #include <GL\freeglut.h> #include <iostream> #include <fstream> #...
I fixed it. The problem was I did not initialize the gluOrtho2D and glMatrixMode. The full code is #include <GL\glew.h> #include <GL\freeglut.h> #include <iostream> #include <fstream> #include <math.h> GLsizei windows_witdh = 800; GLsizei windows_height = 600; class lineBressenham { int x1, y1, x2, y2; public: ...
63,138,896
63,139,184
cin statement being skipped
#include <iostream> #include<string> using namespace std; int main() { struct fruitType { int sugar; string name; string color; bool isSuperfood; string random; }; fruitType fruit; cout << "Enter the name of the fruit."; cin >> fruit.name; cout << endl << "W...
The problem is here: cout << endl << "Is it a superfood? Answer true or false."; cin >> fruit.isSuperfood; The type of isSuperfood is a boolean and your assumption is that the program would accept the string "true" and "false", but it's not in actual. Rather, the program will understand true for bool if you enter 1, o...
63,139,353
63,139,493
How to get the size of a std::bitset from another class?
Im trying to create a class that has a std::bitset in, and another class is supposed to take it as a parameter and create an std::array getting the size of the std::bitset from the class. Like this: template<size_t size> class Individual{ public: std::bitset<size> data; }; template<typename Ind> class Process { pu...
The problem is that during the declaration of Process, it doesn't yet know that Ind is an Individual, so can't do much with it yet. Worse, data is not a static member, so Ind::data doesn't work without an instance of Process. Luckily, there's tons of workarounds, based on your restrictions. Size as parameter: template...
63,139,407
63,139,559
Why does reinterpret_cast only work for 0?
While studying the behavior of casts in C++, I discovered that reinterpret_cast-ing from float* to int* only works for 0: float x = 0.0f; printf("%i\n", *reinterpret_cast<int*>(&x)); prints 0, whereas float x = 1.0f; printf("%i\n", *reinterpret_cast<int*>(&x)); prints 1065353216. Why? I expected the latter to print...
A reinterpret_cast says to reinterpret the bits of its operand. In your example, the operand, &x, is the address of a float, so it is a float *. reinterpret_cast<int *> asks to reinterpret these bits as an int *, so you get an int *. If pointers to int and pointers to float have the same representation in your C++ impl...
63,139,772
63,140,203
If I declare a class instance on the heap are all its members going to be on the heap as well?
I was wondering if I declare a class instance on the heap (new) are its members going to be on the heap as well even if they weren’t created using the new keyword?
Lets say that we declare a class like so: class Foo { private: std::string Bar; public: Foo(std::string Bar); } When you create a new object of that class, it's data members are saved on the same place as the object itself, meaning that if you do something like this Foo* f = new Foo("hello"); all of the data i...
63,139,954
63,140,462
CMake using conda can't find include directory
I am trying to use CMake to compile a C++ program. I am using CMake installed with Anaconda (specifically miniconda3). When compiling, Anaconda isn't able to find headers contained in /usr/include/ My main CPP file looks like this: // Include standard headers #include <stdio.h> #include <stdlib.h> #include <iostream> ...
Those errors are telling you that you are missing a library. fatal error: GL/gl.h: No such file or directory #include <GL/gl.h> You need to install mesalib. For Gl/gl.h on Linux use: or sudo apt install mesa-common-dev or use conda install mesalib
63,140,573
63,140,914
What is the best way to communiate between C++ and Python on Hardware?
Setup: Robot that runs on C++ and an RL training-algo in python. Robot loop runs at 1kHz (can go higher). Goal: To send the robot-state information to the RL training online and send the control inputs back to the robot. Is there a best-way to achieve communication to and fro between C++ and Python processes (without h...
Personally I would do the same as @tdelaney and @cdhowie already mentioned: using IPC socket communication. However, I think it would be overkill to use zeromq or external library to do so, since using only Python standard libraries should be fine and equally easy. Depending of your application, using shared memory cou...
63,140,588
63,140,744
what is "powers of 2" and "word"?
I'm recently following C++ Primer Book In chapter 2 and I'm at this point Most computers deal with memory as chunks of bits of sizes that are powers of 2. The smallest chunk of addressable memory is referred to as a “byte.” The basic unit of storage, usually a small number of bytes, is referred to as a “word.” In C++ ...
"chunks of bits of sizes that are powers of 2" This means that most standard units of memory you'll encounter have a "width" (or size) contains a number of bits, and that number of bits is generally a power-of-two. A byte nearly always today contains 8 bits. The term "word" is frankly a little archaic at this point fo...
63,140,729
63,159,278
How to connect to MySQL in c++ on mac os?
Good morning, I am trying to connect to mysql in c++. I am working on macbook pro. I use simple code from original docs. When I try to compile my program it will fail. main.cpp:15:10: fatal error: 'cppconn/driver.h' file not found #include <cppconn/driver.h> I found here solution which doesn't work. Also solution in ...
I found full working solution. Just install package from this site.
63,140,865
63,141,019
Function overloaded ambiguity in inheritance wherein functions have same number of parameters
#include<iostream> using namespace std; class base1{ public : void greet(int a){ cout<<"How are you ?"<<a<<endl; } }; class base2{ public: void greet(int a){ cout<<"Comment ca va ?"<<a<<endl; } }; class derived : public base1 ,public base2{ public: void greet(int){ base1::greet(int); // ...
base1::greet(int) isn't a call to the base1::greet function. For it to be a call you need to pass an actual value (like e.g. base1::greet(9)). However it's a little hard to pass a value to base1::greet since the argument to derived::greet is ignored. You need to accept the argument and pass it on: void greet(int value)...
63,140,924
63,147,413
How to do the partial match for a struct parameter in gmock expect_call
struct obj { int a; string str; string str2; bool operator==(const obj& o) const { if(a == o.a && str == o.str && str2 == o.str2) return true; return false; } } Then in a function in a class, it is using struct object as input parameters: bool functionNeedsToBeMocked(obj& input) { //do someth...
You can implement your own matcher for the obj struct. When you type: EXPECT_CALL(*mockedPointer, functionNeedsToBeMocked(some_obj)).Times(1).WillOnce(Return(true)); then gmock is using the default matcher, Eq, using some_obj as its expected argument and the actual functionNeedsToBeMocked argument as arg in the matche...
63,141,077
63,225,062
Problems with CUDA on Windows10 + Ubuntu 20.04
I have a laptop with Nvidia GPU - MX250, and I would like to write and execute code, written with CUDA. I have an Ubuntu 20.04 LTS emulator installed on the Windows 10, namely this application from Microsoft store - https://ubuntu.com/tutorials/ubuntu-on-windows#1-overview. I have installed the nvcc toolkit, and the in...
This suggestion is an alternative to try without emulator https://sourceforge.net/projects/toysbox/files/bionic-nvidia/ubuntu-20.04-5.4.0-26-generic-nvidia-450.57-primeselect.iso it is live iso-image with nvidia-450.57 installed so you can run your cuda directly ;the only requirement is to set PATH and LD_LIBRARY_PATH ...
63,141,284
63,142,500
Check values against contents of 2D array
I am trying to loop through my 2D array which is of type Cell Cell m_grid[9][9] - when the current value in the array is not equal to the value that is in the row, column or 3x3 block of the array, I need to add this to my int m_candidateList[9] array. The 2D array itself contains an unsolved sudoku puzzle in a 9x9 for...
Most of this answer is just taken from the user that commented. I can see that you have have a setter function SetValue(int n) but to be able to access what you already have stored then you will also need a setter function so that you can make a call to your Cell object and have access to this value. Let's call this se...
63,141,309
63,141,374
Function with 0 arguments - void vs void*?
I know that you can declare a function without any arguments simply like this: void test() { cout << "Hello world!!" << endl; } But I have also seen void test(void) { cout << "Hello world!!" << endl; } and void test(void*) { cout << "Hello world!!" << endl; } My question is: What is the difference betwee...
What is the difference between using void and void* here? When the argument type is void, the function must be called without any arguments. When the argument type is void*, the function must be called with an argument that is a void* or can be converted to a void*. void stands for "nothing" but void* does not stand ...
63,141,553
63,141,629
How is the std::shuffle_order_engine table managed?
When I call operator() on a std::shuffle_order_engine will a new number immediately be generated to refill the lookup table? Or, will numbers be used up from the table and only when a missing number is required the table refilled?
Every call will have one or more calls to the underlying PRBG that adapter contains From cppreference: Generates a random value. The state of the underlying engine is advanced one or more times.
63,141,784
63,142,000
The placeholder variable does not update during iteration
I am trying to solve an online coding challenge that is asking me to find the left-most digit in a string and return that value. This is what is expected: leftDigit("TrAdE2W1n95!") ➞ 2 leftDigit("V3r1ta$") ➞ 3 leftDigit("U//DertHe1nflu3nC3") ➞ 1 leftDigit("J@v@5cR1PT") ➞ 5 And in my attempt, I made the placeholder...
Your code fails because you are not populating the vector correctly. std::vector<int> digits (0,9); declares a vector named digits that contains 0 elements of value 9, which is not what you want. You wanted a vector with 10 elements ranging from 0..9 instead. In C++11 and later, you can create that range using std::...
63,142,125
63,142,451
Function not returning/Program exiting
I'm writing code for a dynamic solution to the knapsack problem, with the values, weight, etc being read in from a file. After writing the knapsack function code, it seems that it will not return when I try to test just the result being returned. #include <iostream> #include <fstream> #include <string> #include <algori...
int** K = new int* [n + 1]; // ... K[i] = new int[cap + 1]; // ... for (j = 0; j <= n; j++) { for (l = 0; l <= cap; l++) { // ... } } // j == n + 1 // l == cap + 1 return K[j][l]; <--- Exception thrown because of out of bounds access to K ...
63,142,382
63,142,743
Which loop optimization is the compiler performing here?
Suppose the following code: #include <thread> #include <iostream> #include <vector> #include <future> #include <chrono> #include <cmath> long long int partialSum(const std::vector<int>& v, int begin, int end) { long long int sum = 0; for (int i = begin; i < end; i++) { sum += (v[i]); } return s...
The performance gap is there because you are actually copying the vectors here: std::future<long long int> f1 = std::async(std::launch::async, partialSum, v, 0, 10000000 /2); std::future<long long int> f2 = std::async(std::launch::async, partialSum, v, 10000000 / 2, 10000000); Use std::cref to pass them by const refer...
63,142,594
63,142,772
Return a double value from an array element to the console
I have some code where norms is declared as a double array of size 3 x 2. I would like to output norms[0] to the console. #include <iostream> using namespace std; double norms[3][2]; _cal_norm(dept,size,max_posn,norms[0]); cout << norms[0]; I would like to have the double value returned. I have tried using cout...
norms is a 2-dimensional array of arrays, so norms[0] is the 1st inner array in the outer array. If you use cout << norms[0];, it will print the address of that first array. That's why you got a hexadecimal number. If your goal is to print a number in a 2D array then you should write cout << norms[0][0]; which will pr...
63,142,656
63,142,731
c++ empty copy assignment operator copies data
I am sort of new to c++ and wanted to write a small matrix library which has a base class Matrix from which some new matrix types like SparseMatrix, DenseMatrix, HashMatrix etc. My base class looks like this: class Matrix { protected: int m,n; public: Matrix(int m_p, int n_p) : m(m_p), n(n_p){ ...
You have not deleted or defined the operator= copy-assignment operator for DenseMatrix, so the compiler will synthesize one for you. This function is going to do a member wise copy of the data members, in this case double *data. Since the pointer is going to point to the same contents in both mat and mat2, you see the ...
63,142,849
63,142,870
A variable in my basic calculator app isn't working
#include <iostream> using namespace std; int main() { cout << "Hello user, please enter your name: "; string userName; cin >> userName; cout << "Hello " + userName + ", welcome to the addition calculator.\n Please keep in mind that this calculator only supports two numbers."; cout << "Please enter a number for the pro...
On this line: cout << userName + ", thank you for using the addition calculator, the sum of your answer is " + sum; // ^^^^^ error, can't add double to string you are trying to concatenate a double to a string which is not possible. Instead you can chain the output: cout << userName << ", than...
63,143,185
63,143,429
How do I call a function from a given class in a different class
I want to declare a function in one class and run it in a different one.Below is the implementation of my class #include <iostream> #include <cstdlib> #include <math.h> using namespace std; int myNo = 1 + rand () % 10; class Point { protected: int x; int y; Point() { x = myNo; y = myNo; }...
You should use the parameter that you get, like this: float distanceBetweenMeAndAnotherPoint (Point anotherPoint){ float dist = sqrt(pow((x-anotherPoint.x),2) + pow((y-anotherPoint.y),2)); return dist; } Also for the bump method, use the parameter that you get. And additionally simplify boolean return valu...
63,143,237
63,144,412
Change WndProc of the window
I try to change standart WndProc function. I have this code: HWND btn = CreateWindowEx(WS_EX_TRANSPARENT | WS_EX_CLIENTEDGE, L"BUTTON", L"Window title", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON , 50, 50, 50, 50, (HWND)XApplicationMainWindow->window->_wnd, (HMENU)123, (HINSTANCE)GetWindowLongPtr(XAp...
DefWindowProc() is the wrong window procedure for your SubclassWindowProc() to be calling. You need to call the previous window procedure that you are replacing - the window procedure that handles all of the button's default behaviors (like drawing the button so it actually looks like a button, and responding to user i...
63,143,293
63,143,335
Can someone explain to me why this code doesn't output anything
I've already broken my head over what's wrong here. In the output I literally get nothing. It is very strange that nothing is output through a normal cout. Help me please! Thank you. int main() { int x = 111111; array<int, 10> numbers; numbers.fill(8); const auto numbers_copy = numbers; int y = 2222...
This loop: for (int* i = &y; i <= &x; i++) { has undefined behavior (UB). Comparing pointers to unrelated objects has unspecified results. In this case i is pointing to 2 different int objects, x and y, so the first comparison may or may not be true, because there is no guarantee that 2 objects on the stack will be pl...
63,143,301
63,143,357
Is std::chrono::time_point thread safe?
I have a std::chrono::time_point<std::chrono::steady_clock> variable that I am modifying across threads, is this variable thread safe? If not, I intend to make it atomic.
I have a std::chrono::time_point<std::chrono::steady_clock> variable that I am modifying across threads, is this variable thread safe? No. std::chrono::time_point<std::chrono::steady_clock> is not guaranteed to be thread safe.
63,143,537
63,144,005
"is not required" == undefined behavior?
My question is mainly about terminology and how to interpret the standard. [expr.rel]#4: The result of comparing unequal pointers to objects is defined in terms of a partial order consistent with the following rules: (4.1) If two pointers point to different elements of the same array, or to subobjects thereof, the poi...
The wording has changed in various editions of the C++ standard, and in the recent draft cited in the question. (See my comments on the question for the gory details.) C++11 says: Other pointer comparisons are unspecified. C++17 says: Otherwise, neither pointer compares greater than the other. The latest draft, cit...
63,143,656
63,144,587
Finding the position (index value) an element of a bst would be in if it was in a sorted array?
I have a function that finds the nth smallest element of a bst, I wanted to try to find a way to find the "index" an element would be in if the bst was converted to an array. This is my attempt so far int find_position(bst_node* r, int x) //x is the target { if(r == nullptr) return -1; ...
To do this efficiently, you need to record the size of each subtree at each node of the BST. Here is a BST with the cached sizes in parentheses: 20 (8) / \ / \ 10 (4) 30 (3) / \ / / \ / 5 (2) 15 (1) 2...
63,144,389
63,144,572
Pointer casting offset of a class with single inheritance
While learning the "Effective C++", I was firstly surprised when I learned the fact that if a class had multiple inheritance, its pointer may take offset when the pointer casting is done. Although it was not easy concept to grasp, but I think I managed to get it. However, the author claims that this offset might happen...
This can happen when polymorphism is introduced into a class hierarchy by a derived class. Consider the following class: struct Foo { int a; int b; }; This class is not polymorphic, and thus the implementation does not need to include a pointer to a virtual dispatch table (a commonly-used method of implementi...
63,144,717
63,145,567
C++ Comparing strings to determine palindrome
I am trying to determine if a string is a palindrome by reversing the string and then comparing the letters of both strings. The code is provided underneath. So far whatever I put I always get "is a palindrome " as an output. I am aware of the short cut method for doing this easily and efficiently but trying to underst...
First issue... your for loops go out of bounds... length() gives you number of characters in the string. Those characters have index 0 through length() - 1. Because you are using <= s.length() however, then the last time through you get erroneous data, if it doesn't give you out of bounds error. For loops using le...
63,145,186
63,145,791
Static array returned by a function is being overwritten because of recursion
I am coding a segment tree algorithm in which the nodes of the tree are arrays (it's supposed to represent the frequency of indices, it doesn't actually matter for my problem). Since I need to return an array when querying the tree, I figured I had to use a static variable. But that raises a problem: the total array is...
This is C++ and we are in 2020. Use std::array or std::vector auto query(std::array<std::array<int, 9>, 9> const &tree, int i, int j, int pos, int qi, int qj){ if(qi <= i && qj >= j){ return tree[pos]; }else if(qi > j || qj < i){ return std::array<int, 9>{}; } int const mid = (i+j)/2; auto const lef...
63,145,211
63,145,276
In C++, does the branch predictor predict implicit conditional statements?
In this code, it is written, result += runs[i] > runs[i-1];, an implicit conditional statement. In C++, does the branch predictor make predictions for this statement? Or do I have to explicitly use the if keyword to get branch prediction going? using namespace std; int progressDays(vector<int> runs) { if (runs.siz...
CPUs don't run C++ directly, they run machine code. So the answer depends on how your C++ compiles to assembly / machine code. Your choices for expressing program logic in C++ only indirectly influences this. Modern compilers can and will do if-conversion of a C++ if() statement into asm without branches (aka branch...
63,146,217
63,147,337
How do you get a file name with the file name extension given the file path and store it in a string in C++ Console Application?
I'm using Visual Studio 2019. The file path must be taken as an User input. I'm new to C++ and will appreciate any help i can get.
#include <iostream> #include <string> int main() { std::string filename; std::cout << "Enter file path: "; std::cin >> filename; // "Example: C:/test/file1.txt" // Remove directory if present. // Do this before extension removal incase directory has a period character. const size_t last_slash...
63,146,296
63,146,351
Empty array in c++ shows absurd behavior
The code: int arr[] = {}; int n; n = 7; arr[0] = 15; cout << n; gives output:15 Why not 7 ?
The first line in your code creates an array of size 0. The next variable in the memory is n, and that's why your program overrides it. You need to fix your first line to: int arr[1] = {}; Like people mentioned in the comments above, it does in fact depend on your compiler.
63,146,320
63,146,932
What is the difference between using () and not using () in creating class instance
I wrote a class like this #include <iostream> using std::cout; class Resource { public: Resource(){ cout << "allocated\n";} ~Resource(){ cout << "deleted\n";} }; Then inside int main() I create 2 instances of the class int main() { Resource* p1 = new Resource(); Resource* p2 = new Resource...
The parentheses do make a difference! As @songyuanyao pointed out: you invoke value initialisation with the use of parentheses, and default initialisation without it. For a class type like your Resource you won't see any difference. The constructor is called in both cases. However, if you have a fundamental data type s...
63,146,607
63,146,668
Why does deleting a valid heap-allocated pointer give "free(): invalid pointer" error?
I am new to C++ and am trying to do a very basic implementation of a shared_ptr (WIP). I am trying to delete a heap-allocated pointer in the destructor right after finding the underlying value by dereferencing. While the dereferencing happens fine, deletion of '''ref_count''' variable is causing problems. Can someone p...
Operator precedence is causing you problems. You're actually decrementing the pointer, then deferencing the new address. If you crank up your warnings, you'll get something like this: p.cpp:35:7: required from ‘shared_ptr<T>::~shared_ptr() [with T = int]’ p.cpp:58:26: required from here p.cpp:14:5: warning: value...
63,146,657
63,146,827
Accessing shadowed variables from inner scope
My code : int num = 1; // global scope int main(){ int num = 2; // local scope 1 { // local scope 2 int num = 3; { // local scope 3 int num = 4; std::cout<<num<<...
You cannot just simply achieve this as the inner variable just overshadows your outer scope variable. If an inner block declares a variable with the same name as the variable declared by the outer block, then the visibility of the outer block variable ends at the point of the declaration by inner block. However, if you...
63,146,908
63,147,541
QAction doesn't call the connected slot
I have a Qt project with a QMainWindow, which has the following actions and slots: class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = Q_NULLPTR); private: Ui::MainWindowClass ui; //..... other code QMenu* fileMenu; QAction* newAct; //The concerned QAction* ...
your code with the QAction, Shortcut and Connect looks fine so am suspecting of the slot newGame in the mainWindow I did try on my system with a lambda like connect(newAct, &QAction::triggered, []() { qDebug()<< "Hello Action"; }); and I can see the HelloAction when clicking and when using the shortcut ctrl+N
63,147,158
63,160,560
Invalid read size 1 in valgrind using boost::smatch
I am using boost::smatch object to get the matching pattern from boost::regex_match and use that matching pattern string for further operations. It's working fine in a normal run, but when I use Valgrind for memory checking it is showing an error in the line where I am reading a match string i.e. match.str(1) I am tryi...
Kudos for unning with ASAN/UBSAN/Valgrind. You see why it is important :) You're reading a subgroup that wasn't successfully matched. You probably want to check that it did, the check size()>1 is NOT enough: Live On Coliru #include <boost/regex.hpp> #include <iostream> #include <iomanip> namespace dcv { boost::reg...
63,147,287
63,155,360
How can I combine several return type requirements of C++20 constraints into one return type requirement?
Currently, I have implemented the Allocator concept (which refers to the Boost proposal) using C++20 constraints and concepts: #include <concepts> #include <iterator> template <class A> concept allocator = std::copy_constructible<A> && std::equality_comparable<A> && requires(A a) { { a.allocate(0) } -> std::...
For this particular case, you should follow the concept more closely. The return type of allocator_traits<A>::allocate is required to be allocator_traits<A>::pointer. So that's what you should test. It is allocator_traits<A>::pointer that must satisfy the various constraints of contiguous iterator and nullable pointer....
63,147,751
63,148,024
How to properly specify noexcept with a C++ forwarding reference?
Take, for example, the following: #include <iostream> #include <type_traits> #include <utility> struct Bar { Bar() = default; Bar(Bar const&) noexcept(false) = default; Bar(Bar&&) noexcept(true) = default; }; struct Baz { Baz() = default; Baz(Baz const&) noexcept(true) = default; Baz(Baz&&) n...
You can do something like this: template<typename U, typename = std::enable_if_t<std::is_same_v<std::remove_reference_t<U>, T>>> Foo(U&& val) noexcept(noexcept(T(std::forward<U>(val)))) : _val(std::forward<U>(val)) {} The inner noexcept is a noexcept operator, the outer one is a noexcept specifier. Demo I ha...
63,148,116
63,149,884
Better way to convert decimal float into special hexadecimal notation
I have decimal numbers in the range between 0 and ~15.9 and want to convert them into a specific hexadecimal notation. So the special notation goes like this: There are 16 bits. The first 4 bits are for the pre-decimal-point position. The next 12 bits are for the decimal places. A * 16^0 + B * 16^{-1} + C * 16^{-2} + D...
I wounder if there is no better, more elegant way to do this Elegant is subjective, but: One thing you can do is work with the bits directly. Check this simple converter to see how IEEE floating point numbers work (if you don't know already). Then look at this question for a method to get the different groups of bits...
63,148,131
66,777,252
error: redefinition of 'int main()' even if "int main()" apperas only once
I was working on a problem on Pbinfo: https://www.pbinfo.ro/probleme/898/sumfactcif but each time I tried to run my code it said: sumfactcif.cpp: In function 'int main()': sumfactcif.cpp:35:5: error: redefinition of 'int main()' int main(){ ^ sumfactcif.cpp:25:5: error: 'int main()' previously defined here int ...
Answer: Looks like the site already added an "int main" to my code, so that the result had two "int mains". Thanks to @churill for pointing that out
63,148,583
63,148,844
Code Runner in VSCode is running in output instead of CMD in the Terminal
I just re-installed my VSCode for some reason and after downloading the Code Runner extension, it is processing all the commands in the OUTPUT window instead of CMD in the Terminal... I am compiling my C++ code so I want that cd and g++ command in my CMD window, and not in the output one...
You can specify to run in the integrated terminal per their configuration: "code-runner.runInTerminal" : true This is defaulted to false
63,148,911
63,149,283
Nested class constructed in a member function with smart pointers in c++
I have the following simple code class Hybrid{ std::unique_ptr<Bcf> bndfac; void constructbndFace( const int &nn){ bndfac( new Bcf(nn) ); // Does not work (A) //std::unique_ptr<Bcf> bndfac( new Bcf(nn) ); // WORKS (B) } } class Bcf{ Bcf(const int nn_) : nn(nn_){} private: int nn; } ...
In you line B you create a temporary object with the name that shadows member name. Then it is destroyed at the next line with closing curved bracket. If you want to construct bndfac object, you should replace your line B with this: bndfac = std::make_unique<Bcf>(nn);
63,149,347
63,185,194
is there a way to add process_query_information to existing process handle?
i'm absolute beginner to this, i've been trying to collect handle on my system using ntquerysysteminformation and now i get the handle that i want(i know this by using processhacker) but the problem coming when i try to collect the pid from that handle in order to determine which handle that is correct to inject my dll...
Since we are in an external process, so it makes no sense to distribute the handle provided by NtQuerySystemInformation, you need to copy the handle into our own process. source process for testing: #include <Windows.h> #include <iostream> #include <fstream> int main() { HANDLE hprocess = OpenProcess(PROCESS_VM...
63,150,160
64,084,878
emscripten C++11 with boost support issue
I have an issue when building my C++ project that uses boost in Emscripten as shown on the screenshot, it says that '_Atomic' is a C11 extension however even if i add -std=c++11 or even -std=c11 i am still getting the error, the _Atomic use is defined from boost. any idea on how to work around on this? reading around ...
Why The message in your screenshot shows: you are compiling with clang error: '_Atomic' is a C11 extension [-Werror,-Wc11-extensions] So clang warns on c11 extensions because it has the diagnostic flag set, and is also configured to fail on warning which leads to your failed compilation. -Wc11-extensions may have be...
63,150,566
63,150,974
How to print a specific row of a multidimensional array
In C++ it is possible to print all elements of an one-dimensional array like this : char abc[3]={'a', 'b', 'c'}; cout<<abc<<endl; My question is whether there is a way to do that with multidimensional arrays. Is it possible to print only one row of an array? I've tried this: char abc[3][3]={ {'a', 'b', 'c'}, {'d', 'e...
Adding '\0'-s to the end of the arrays would be hack. And another hack that I see here is that you're trying to treat a two-dimensional array as a single-dimensional (you're passing arr[0] instead of something like arr[0][i]). The reason that it somehow works, is that the cout just blindly reads the contents of the arr...
63,150,971
63,151,022
Multiple condition in 'for' loop is not working in C++
I am trying to print all occurring even numbers up to 20. The code is working fine with an if condition, but it is not working with multiple conditions in the loop. #include <iostream> using namespace std; int main() { for(int i = 1; ((i <= 20) && (i % 2 == 0)); i ++) cout << i << endl; }
You are confusing two different things. When you want your loop to stop, and when you want to print a number. In the code you have written you've put the 'when you want to print a number' condition where you should only have the 'when you want your loop to stop' condition. Because of this, as soon as you get an odd num...
63,151,112
63,151,574
Deduct Parameter Pack Arguments for Lambda Functor
I have a class that I want to use to execute a callback on an EventQueue: template <class, class> class Handler; template <class Fun, class... Args> class Handler<void(Args...)> { public: Handler(events::EventQueue &eq, Fun fun) : _eq(eq), _fun(fun) {} void operator()(Args... args) { _eq.call(...
Your syntax is almost correct. I don't see a good reason to convert Args... into void(Args...) and suggest the following solution: // This stub is here for the sake of code completeness only class EventQueue { public: template<class T, class Fun, class... Args> void call(T* obj, Fun fun, Args... args) const { ...
63,151,118
63,152,091
c++ Property Implementation wrt getter for struct type cannot be converted automatically?
im trying to implement Property on c++ and here's my code: Property.hpp #ifndef __VIOLET_PROPERTY_H__ #define __VIOLET_PROPERTY_H__ class IProperty { protected: virtual void init_properties() = 0; }; #define READ_ONLY 1 #define WRITE_ONLY 2 #define READ_WRITE 3 template <typename Container, typename ValueType, i...
You have two user defined conversions: a.Value is a property<A,B,READ_WRITE>. It has a user defined conversion operator to B. B has a user defined conversion operator to int. They cannot form a so called implicit conversion sequence and therefore you need to explicitly convert a.Value to B first. From cppreference.c...
63,151,334
63,164,434
how does OnOverlapBegin_Implementation means and OnOverlapBegin differs?
I am confused how the UFUNCTION(BlueprintNativeEvent, Category = Collision) void OnOverlapBegin(UPrimitiveComponent* Comp, AActor* otherActor, UPrimitiveComponent* otherComp, int32 otherBodyIndex, bool bFromSweep, const FHitResult& SweepResult); and virtual void OnOverlapBegin_Implementation(UPrimitiveComponent* Comp, ...
Essentially, this is a question about the BlueprintNativeEvent function specifier. So the top function definition you have up there would be in a class' header file. UFUNCTION(BlueprintNativeEvent, Category = Collision) void OnOverlapBegin(UPrimitiveComponent* Comp, AActor* otherActor, UPrimitiveComponent* otherComp, ...
63,151,658
63,151,988
Create Dynamically Allocated Array of Pointers C++
I'm currently trying to dynamically allocate an array of character arrays and set values from another array of character arrays to the new dynamically array. When I print the values from the dynamically array I got some junk values and I can not understand where they come from. Class - class Class { private: char*...
Look here as you may understand from the documentation, strlen function does not count \0 character which is end of the string. Hence it is not copied with strcpy function call, and cout does not encounter with \0. This is the reason of absurd characters in terminal output. While allocating memory for course names, all...
63,152,007
63,152,883
Overwrite byte in file without clearing it
How to overwrite a byte in a file without clearing the entire file? Note that I don't want to insert additional bytes but rather overwrite a byte at a certain offset. I have tried the following code to write a byte at some offset. However this clears everything after the specified offset which is not what I want. #incl...
It's perfectly possible (in fact common) to update a file, provided you don't want to insert any new bytes before the current end of file. Change to this std::ofstream ofs {"foo", std::ios::in|std::ios::out|std::ios::binary}; However this will fail if the file does not exist, but it sounds like that is not a concern. ...
63,152,252
63,152,355
how do i initialize 2 static members belonging to 2 different derived classes
New to c++. I'm solving questions to understand better. So, i have to make a program which has a parent class called Person and it has 2 derived classes named Student and Professor. The parent class Person has normal variables - std::string name and int age. The derived class Student has variables int sum, int marks[6]...
You should define cur_id in Professor class as static.
63,152,275
63,157,239
How to get back the image from Tensor in libtorch?
I am trying to get the image back from the tensor I created earlier and visualize it, However, the resulting image is distorted/garbage it seems. This is how I convert a CV_8UC3 into the corresponding at::Tensor: at::Tensor tensor_image = torch::from_blob(img.data, { img.rows, img.cols, 3 }, at::kByte); and this is ho...
When the tensor was created using a c10::kByte for the cast we need to use uchar and not char or uint, etc . so in order to get this fixed I only had to use uchar instead of int: auto ToCvImage(at::Tensor tensor) { int width = tensor.sizes()[0]; int height = tensor.sizes()[1]; try { cv::Mat outp...
63,152,981
63,153,216
C++ templates avoid passing element type twice
I have a templated class where I need to pass both the container and the element of the container as template parameters. For example: template<class CONTAINER, class ELEMENT> class M { void addElement(const ELEMENT e){} CONTAINER container; }; so the class would be instantiated like: M<std::array<CustomType, ...
I could suggest two options: Use value_type member type that all standard containers have: template<class CONTAINER> class M { using ELEMENT = typename CONTAINER::value_type; // ... }; Get element type from some member function. For example: template<class CONTAINER> class M { using ELEMENT = std::decay_...
63,153,203
63,153,710
C++ Saving objects inside a list to reuse later
Suppose I own a list of edges saved inside a vector like: typedef struct edge { int v; size_t start; size_t end; }e; typedef vector<list<e>> adj_list; adj_list tree; I have to do logic on this tree object, but the logic is too complicated to do it in place (constricted to not recurse). I need an extra data stru...
As discussed in the comments, the solution is to store iterators instead of copies, e.g.: list<list<e>::iterator> aux; aux.insert(aux.begin(), tree[0].begin(), tree[0].end()); while (!aux.empty()) { e& now = *(aux.front()); aux.pop_front(); now.v++; aux.insert(aux.begin(), tree[now.v].begin(), tree[now.v].end()...
63,153,342
63,154,307
Cmake undefined reference to symbol 'dlsym@@GLIBC_2.2.5 even though I link with -ldl
I'm getting undefined reference to dlsym@@GLIBC_2.2.5 even after linking it before and after the libraries. However in the linking output it appears that it's linking just before, but linking before all libraries should work, I guess. /bin/g++-9 CMakeFiles/http_downloader.dir/http_downloader_cli.cpp.o CMakeFiles/ht...
Would you inspect carefully the actual command line used for linking, you will find that after libsmoltcp_cpp_interface_rust.a, which has missed symbol, there is no -ldl parameter. It seems that in your case smoltcp_cpp is an IMPORTED library target, which has libsmoltcp_cpp_interface_rust.a as a link dependency (not a...
63,153,447
63,153,856
transform vector of shared_ptr with non const elements to vector of shared_ptr with const elements
I have a class A containing a vector of shared_ptr<B>. I implemented a getter to this vector. In some cases, it would be nice to ensure that the content in B does not change (make B read only or a const reference). If I would not have used vector<shared_ptr<B>> but rather vector<B> I could simply write two getters, one...
You need to construct a new vector with the desired elements: const vector<shared_ptr<const B>> get_vb_const() const { return vector<shared_ptr<const B> > {vb.cbegin(), vb.cend()}; } Note that the function doesn't return a reference now because we are creating a temporary and returning it.
63,153,720
63,153,785
Null pointer and pointer arithmetic
Is there a way to stop the while loop below from iterating after surpassing 40? I am trying to replicate the linked list concept of iterating while NULL pointer is not found. int main() { int* arr = new int[4]{ 10,20,30,40 }; //for(int i=0; i<4; ++i) -- works fine while (arr) { cout << *(arr++) << e...
Is there are to stop the while loop below from iterating after surpassing 40 There are two ways to stop the loop: Cause the condition to become false, or jump out of the loop (break, goto, return, throw, etc.). Your loop doesn't do either. Your condition is arr which is false only if the pointer points to null. You n...
63,153,765
63,191,078
'variable JNIEXPORT is not type name'
I don't know why is giving me errors on JNIEXPORT and JNICALL... Info: Visual studio 2017, Windows JAVA_HOME is set. Added the directory in 'C/C++ > General > Additional Include Directories' Include directory > C:\Program Files\Java\jdk1.8.0_251\include I tried adding jvm.lib but didn't work. error: JNIERROR - 'variabl...
When you include "jni.h" to compile JNI code in C or C++ you have to add both your JDK's "include" directory to your include path and the directory where the platform dependent include files (referenced by "jni.h") are. Those are "include\win32" on Windows, "include/linux" on Linux, and "include/darwin" on macOS. Usual...
63,153,901
63,154,092
Why -1 equals 4th byte of integer -5?
Why does this code deduce a true (or 1 without std::boolalpha) char* arr = new char[4]; int* i = new (arr) int(-5); char c = -1; std::cout << std::boolalpha << (arr[3] == c) << std::endl;
Why does this code deduce a true Depending on the system used to run the program, the output could be either true or false, or behaviour of the program could be undefined. On systems where negative numbers are represented using two's complement (which is very common, and will be guaranteed since C++20) and where byte...
63,154,552
63,155,016
C++ typedef with tuple of indefinite size
I am working with some C++ code that creates a set from quaternary tuples. I would like to generalise the code so that tuples of any magnitude could be added to the set. Is there a way of creating a typedef for a tuple of an indefinite number of elements? For the sake of compatibility with the project that I working on...
I need a run time variable size container of a single type, int. If it's "run-time variable size", use std::vector<int>. If it's known in compile time, use std::array<int, n>, where n is your size. std::tuple is meant for a few of values of possibly different types, especially in a generic context; you can think abou...
63,154,863
63,155,628
Go through the indexes of an array in a specific way
#include <iostream> using namespace std; int main(){ int n; int *weight; int index,container; cout<<"Enter number of weights (1<=number<=10^5) you have: "<<endl; cin>>n; weight = new int[n]; cout<<"Enter "<<n<<" number of weights (0<=weights<10^4) to the array:"<<endl; for(...
Your goal is to count how many containers are needed to store N items, where all items in a given container weigh at most 4 more than the lowest weight item in that container. The following should help (it assumes that the array of weights is sorted in ascending order): #include <iostream> using namespace std; int m...
63,154,987
63,155,442
Array size template deduction
I have a class that stores an std::array. The size of the array is evaluated in compile time, this is because the application runs on an embedded device so no dynamic allocations :(. The code looks something like this: template<uint8_t size> class A { //some constructor A(...); std::array<int, size> what; }...
A small example using deduction guides: template<uint8_t size> class A { public: template <typename... Args> constexpr A(Args&&... args) : what { std::forward<decltype(args)>(args)... } {} constexpr size_t getSize() const { return what.size(); } private: std::array<int, size> what; }; //deducti...
63,155,117
63,155,443
How to compile a C++ program that includes external library headers?
I'm trying to compile a .cpp file that includes an external library header, and that header includes other headers from the said library. Here's the directory structure: ROOT/ ├── theLibDir/ │ ├── lib_header1.h # includes "theLibDir/lib_header2.h" and "theLibDir/lib_header3.h" │ ├── lib_header2.h │ ├── lib_header...
The directive #include <theLibDir/lib_header1.h> and the option -I theLibDir try to find a file named ROOT/theLibDir/theLibDir/lib_header1.h. Two solutions: use the directive #include <lib_header1.h> or put the ROOT directory in compilation option -I.
63,155,279
63,155,377
How to detect the size of the parameters that are passed through ellipsis in C++?
The answer to this question says that C doesn't provide any means to detect the size of parameter passed through ellipsis: How to detect the size of the parameters that are passed through ellipsis? Is there C++ solution to this problem?
For C style vararg functions, no. For C++ style vararg templates, yes. You use sizeof ... operator for that. See cppreference: #include <iostream> template <typename ...Args> void print_arg_cnt(Args... args) { std::cout << "Arg count: " << sizeof ...(Args) << '\n'; } int main() { print_arg_cnt(1, 1.1, 'a'); ...