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,240,547
63,387,080
Separate Y and UV of a video frame C++
I am receiving a video frame in a GstVideoFrame structure of a gstreamer element which is written in C++. The frame is in YUV420 NV12 format In this gstreamer element, I am trying to copy y-frame and uv-frame in separate buffers. According to videolan.org, the YUV420 NV12 data is stored as following in the incoming fra...
Thanks to @Ext3h, this is how I was able to separate y-data and uv-data from incoming YUV frame. y_data = (u8 *)GST_VIDEO_FRAME_PLANE_DATA (in_frame, 0); uv_data =(u8 *)GST_VIDEO_FRAME_PLANE_DATA (in_frame, 1);
63,241,065
63,242,226
How does this loop work (Check Duplicate in array loop)
Beginner programmer here can someone please explain to me how this loop works. How can the loop detect the duplicate element in the array? sorry for the simple question. #include <iostream> using namespace std; int main() { int num[5]; int numSize = sizeof(num) / sizeof(num[0]); for(int i = 0; i < numSi...
Avoid indexing when it is possible. It is not final solution but it may show you right direction. #include <iostream> #include <algorithm> int main() { int num[] = { 0, 5, 6, 8, 0, 2, 5, 8 }; std::sort(std::begin(num), std::end(num)); auto it = std::begin(num); while(1) { it = s...
63,241,176
63,241,396
What is the difference betwene int *p and int * p = new int;
I have 3 questions: Q1. When we create the object using the new operator, following is the syntax: pointer_variable = new data-type //To create an object pointer_variable = new data-type(value); //To create an object with value pointer_variable = new data-type[size]; //To create an array Why always there is a pointer...
in C++, a typical new expression allocates memory on the heap, and returns a pointer to that memory. Re Q1: you can save the resulting pointer to a local variable for immediate use: pointer_variable = new int. But you don't have to do that: you could instead use it as an argument to a function: use_pointer(new int)....
63,241,219
63,275,081
How to manage importing an SCons project
I have an SCons-based project that has a rather specialized SConstruct file (due to CUDA), let's call it project A. I am using it as a submodule for another project I am working on we can call project B that is also going to have some rather peculiar compilation requirements (due to MEX). I'd like to leave project A ef...
(this was too long for a comment, not sure it's an "answer"...) SConstructs are unique top-level things, but then again, they also aren't - you can call any file when you call SConscript(), including one named subdir/SConstruct, as long as the latter is structured in a way that has that make sense, and having A Export(...
63,241,576
63,241,690
What is wrong with my sentence palindrome code (C++)?
The below code is of a sentence palindrome checker. I'm a newbie programmer so I'm having a hard time debugging this code. It's showing incorrect output. For example, if the sentence is "A man, a plan, a canal: Panama" It's giving false as a result instead of true. (Blank spaces and punctuations are to be neglected.) ...
The problem is very likely that the character classification functions (like e.g. ispunct) does not return a bool result. They return an int whose value can be any non-zero value for "true". That means the condition like ispunct(s[i]) == true might actually be false for punctuation characters. You need to use e.g. ispu...
63,241,921
63,242,943
Heap allocation vs std::vector
I need to create a multi-tree in a critical part of my code. Standard way is to use something like: struct node{ // or class ... data ... std::unordered_set<node*> children }; node* root; One important thing is that, once a node is created, on won't be deleted until the whole tree will be deleted. The obvious w...
I'm guessing you have a tree in the size of some 10 million+ elements (or at least in the ballpark of 100k+ elements) to be concerned with this. It then all depends on how your data and tree is used. Spatiality of data is usually of concern but its not obvious if that is your case too. If the tree is traversed a lot af...
63,241,941
63,242,325
Since vptr is inherited in derived class, how it point to its own vtable?
I googled many explanation and they said vptr is only declared on Base class, the Derived class only inherit the vptr and construct during constructing the object. And vptr point to its own vtable(NOT Base::vtable) So to my understanding, in this model, we only have Base::vptr, but we have two different vtable (Base & ...
The virtual table pointer is just like any other member variable, it's just hidden from the program and the code (so it can't be accessed directly). And as any other normal member variable, an instance of the base class will have its own distinct copy of vtable pointer. And an instance of a child class will have its ow...
63,242,207
63,257,091
boost::program_options generating MLK.MUST in Klocwork
I wrote the following C++ code based on the Boost library to take inputs from command line. #include <iostream> #include <boost/program_options.hpp> #include <boost/format.hpp> using namespace std; namespace po = boost::program_options; int main(int argc, char** argv) { int party = 2, port = 9999; string serv...
Another issue reported by Klocwork is 'port' is used uninitialized in this function. It specifically mentions that passing '&port' to 'po::value' This is a false positive: nothing uses the value of port before it's initialized (I checked). However, it should be enough to actually initializing port to silence the mess...
63,242,232
63,242,274
c++ derived class accessing base class' friend operators
I am working with operator overloading and inheritance. I currently have something similar to the following code: istream& operator >> (istream& in, derived& d) { /* Some code asking for input to populate the object's data members*/ cin >> d; /*Here, the operator called is this one, creating an infinite loop*/ } ...
You need to convert it to the base class to call the operator>> on base class, otherwise it would try to call itself and lead to infinite recursion. E.g. istream& operator >> (istream& in, derived& d) { in >> static_cast<base&>(d); return in; } PS: You should use in instead of using cin fixedly, and return in ...
63,242,411
63,242,520
TCP connection breaks after 1 message
I have a project which i communicate with DNS servers. For example I used googles DNS server. After connecting to the server and sending a message, everything works well and the server returns an answer. But by the time i send the second query, the server already closed the connection by himself(sends FIN) and now I se...
From the DNS over TCP RFC: The server should assume that the client will initiate connection closing, and should delay closing its end of the connection until all outstanding client requests have been satisfied. This means that if you send multiple requests simultaneously, the connection will stay open until all the ...
63,242,484
63,242,579
c++ int pointer to array of pointers to arrays memory leaks
so I have this class with a functions.hpp and a functions.cpp #include "function.hpp" test::test(int size) { this->size = size; matrix = new int*[this->size]; for (int i = 0; i < size; i++) { matrix[i] = new int[this->size]; } } test::~test() { for (int i = 0; i < this->size; i++) ...
The problem is that the destructor is not called until main is exited which is after you call _CrtDumpMemoryLeaks. Change your code to this int main() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); { int size = 10; test test(size); } _CrtDumpMemoryLeaks(); return 0; ...
63,242,538
63,242,638
GCC misses some errors or warnings
Consider this copy constructor of a template class which has an error: MyClass( MyClass const& other ) : m_x( other.n_x ) // typo: should be `other.m_x`. { // does something } Or this copy assignment operator overload which does not return anything (return-type warning): MyClass& operator=( MyClass const& other )...
GCC checks templates only by static checker unless they were instantiated. Standard doesn't require even that. This is possible if your template class is derived from other template. It is not known if that template will have a specialization with such member or not. E.g. this code is still valid template <template <cl...
63,242,708
63,299,923
How to create a numpy array of boost::python::object types
I'm trying to create a 2x2 numpy array of python objects: #include <boost/python.hpp> #include <boost/python/numpy.hpp> int main() { Py_Initialize(); boost::python::numpy::initialize(); boost::python::tuple shape = boost::python::make_tuple(2, 2); boost::python::object obj; boost::python::numpy::dty...
You're using the dtype constructor correctly; it's obj that's causing the trouble. The default construction boost::python::object obj; sets obj as the 'None' Python object. The dtype associated with 'None' is a NPY_DEFAULT array descriptor type. And that maps to a double when creating the numpy array, which explains yo...
63,242,739
63,248,073
How to properly use RcppThread to parallelize a for-loop
I am trying to parallelize a for loop with RcppThread. The unparallelized version looks like this: IntegerVector simulate_pos(NumericVector x_pop, NumericVector y_pop, int n_studies, int sample_size_min, int samp...
You write Is the problem that several threads are reading the same memory address at the same time? Or are the Rcpp data structures (e.g. NumericVector) causing issues? and I am inclined to say "likely". See the excellent documentation in package RcppParallel, and how it builds up from small examples. I know this sou...
63,243,279
63,243,939
c++ templates, how to map template parameters to other template parameters
Can I somehow make a map of template parameters? let's say I have the following function: template<typename T> T SumCoefficients(const std::vector<T>& coeffs) { T sum = static_cast<T>(0); for(int i=0; i<100; ++i) { sum += SomeFunc<T>(i) * coeffs[i]; } return sum; } // explicit instantiation template doubl...
The constexpr if approach is fine, but I'd like to add another solution which I think is preferable, if you have many calls to SomeFunc across your code base. Another advantage of my solution is that it scales better if you have many types or you need to be able to add types later because the mapping logic is encapsula...
63,243,462
63,245,236
SIGSEGV __gnu_cxx::new_allocator<int>::construct<int, int const&> in Codeforces Round #660 Problem D
I have been working on a problem from CodeForces round #660 Problem D My code is as follows:: #include <bits/stdc++.h> using namespace std; vector<vector<int>> child; //Array of b[i](parent) vs i(child) vector<long long int> a; //We will update it later, and will be our subtree vector<int> b,found; void DFS(int ind...
As a general answer: you are not doing any explicit allocations or deletions, so it is likely the problem stems from an out-of-bounds access to one of the vectors. If you use v.at(i) instead of v[i] to access the ith element of a vector v, an out-of-bounds access will throw an exception, rather than cause a segmentatio...
63,243,704
63,250,876
I am getting a TLE error while performing cycle detection
I have written a code to the leetcode problem(courseSchedule) which basically asks whether a given set of courses can be done given dependencies. my approach is to create a graph and then check for a cycle, however, it's giving a TLE error. Can you help me as to why is the TLE happening or if there's a better approach ...
Actually, your function is correct but so inefficient. This is because in the cycle function performs so many redundant operations i.e check for the same node multiple times. Your Code: bool cycle( vector<vector<int>> &adj,int i,vector<bool> vis){ if(vis[i]) return true; vis[i] = true; ...
63,243,712
63,243,949
Boost regular expression for match whole word does not work
I am using some regular expression with boost to search for whole word inside some string. The source looks like this: boost::regex regExp; std::string searchExpression; searchExpression = "((\\b)" + searchExpression + "(\\b)|(?<=^|\\s)" + searchExpression + "(?=\\s|$))"; regExp.assign(lConvertedSearchExpression, boo...
The boost::regex documentation states that a lookbehind needs to be a fixed length. Your lookbehind matches zero or one character.
63,243,729
63,247,826
How to get all currently spawned vehicles in sumo through traci
I have a question about sumo/traci. In python there exist functions for retrieving values from sumo: sumo documentation How do I do that in C++, specifically i need a list of all vehicles which are currently in the simulation. Thank You
If you are using Veins 5.0, you can find a list of all implemented methods for interacting with SUMO in https://github.com/sommer/veins/blob/veins-5.0/src/veins/modules/mobility/traci/TraCICommandInterface.h Specifically, though, the list of all currently-simulated vehicles can most reliably be obtained by calling TraC...
63,244,349
63,267,851
When is integer to floating point conversion lossless?
Particularly I'm interested if int32_t is always losslessly converted to double. Does the following code always return true? int is_lossless(int32_t i) { double d = i; int32_t i2 = d; return (i2 == i); } What is for int64_t?
Question: Does the following code always return true? Always is a big statement and therefore the answer is no. The C++ Standard makes no mention whether or not the floating-point types which are known to C++ (float, double and long double) are of the IEEE-754 type. The standard explicitly states: There are three fl...
63,244,404
63,245,062
C++ base class method with different input struct argument for derived classes
I'm trying to create a base class defining an interface for derived classes - say a simple audio wrapper class. class AudioStreamBase { public: virtual ~AudioStreamBase(void); virtual void open(const void * settings) = 0; virtual void start(void) = 0; virtual void stop(bool force) = 0...
You could use the CRTP to inject the derived class into the base. Then you could define a traits helper to define e.g. which settings have to be used for some derived class. Admittedly, a bit verbose but now your code is type-safe. If you need the base class to be non-template, you could pull out everything except the ...
63,244,738
63,247,570
Can values be set for CMake SOURCE(S) other than using set?
Suppose I have a simple C++ hello-world project with the following CMake script: cmake_minimum_required(VERSION 3.15) project(hello) set(SOURCE main.cpp) add_executable(${PROJECT_NAME} ${SOURCE}) Now I noticed that PROJECT_NAME is built-in and its value is set from project(*value*) but also SOURCE (and SOURCES) see...
Using a SOURCE variable is a common patter in CMake files, but it is not required. The code above can be written without any variables, it would look something like this: add_executable(hello main.cpp) When there are a lot of source files, passing them all to add_executable can be inconvenient. Another alternative is ...
63,245,234
63,245,476
Template function that calls itself results in "instantiation depth exceeds maximum of 900"
I am trying to create a function that accepts a lambda function callback and some candidate_primes that can be a set or a vector, but it gives the error: template instantiation depth exceeds maximum of 900 template<class PrimeIter, class Function> void iter_feasable_primes( const PrimeIter& candidate_primes, const ...
Indeed lambda have unique type and so you have to instantiate infinite recursion. One way to solve that is to give an unique type, either a custom functor, or a type-erased type as std::function template<class PrimeIter> void iter_feasable_primes( const PrimeIter& candidate_primes, uint32_t larger_prime, uint8_t ...
63,245,264
63,245,617
Finding item in string and say WHEN it was found - c++
I have a string of items (see code). I want to say when a specific item from that list is found. In my example I want the output to be 3 since the item is found after the first two items. I can print out the separate items to the console but I cannot figure out how to do a count on these two items. I think it is becaus...
I replaced your search algorithm with the method explode, that separates your string by a delimiter and returns a vector, which is better suited for searching and getting the element count: #include <string> #include <vector> #include <sstream> #include <iostream> #include <algorithm> std::vector<std::string> explode(...
63,245,640
63,245,936
how to remove json object key and valyue in QT/c++?
I have a json file as shown below { "TestId:1": { "FILE ID": "223", "CLASS": "rame", "PLATFORM": "test" }, "TestId:2": { "FILE ID": "123", "CLASS": "raj", "PLATFORM": "test2" } } I want to remove the "TestId:2" key content. I tried delete obj["TestId:2"]...
You need to create a QJsonObject to edit it. First, read your file: QFile file("myfile.json"); // to replace with you file name file.open(QIODevice::ReadOnly); QByteArray data = file.readAll(); file.close(); Then, create the QJsonDocument with the data from the file: QJsonParseError error; QJsonDocument doc = QJsonDoc...
63,245,755
63,245,949
declare a defined class as a struct inside a template parameter
A class A is defined and implemented. Later it's declared as a struct as the template argument of std::unique_ptr. The compiler(g++10.1) complains nothing about it and the program can be run. #include <iostream> #include <string> #include <memory> class A { public: std::string info = "Hello World!"; }; int main()...
It's allowed to mix class and struct in a declaration, it's only an issue in a definition of a class. Refer to Mixing class and struct for more details. The seg fault in the second case comes from null pointer access, a form of undefined behavior. std::unique_ptr<struct A> a; initializes a to an "empty" state. Then a->...
63,246,024
63,246,472
Unresolved externals, Missing comdlg32.lib library
I am working with application for WindowsCE 2013 which is partially created in WinAPI. While I tried compile the code, I met a error message "Error 2 error LNK2019: unresolved external symbol PageSetupDlgW referenced in function "long cdecl WndProc(struct HWND *,unsigned int,unsigned int,long)" (?WndProc@@YAJPAUHWND__@...
Ok problem was solved. The solution is that in WindowsCE equivalent for commdlg32.lib is commdlg.lib
63,246,575
63,246,655
is default enough for a c'tor d'tor of a class with vector elements only?
I have a class called Item that has two vectors as private elements class Item { private: std::vector<std::string> V; std::vector<std::string> E; public: Item(std::vector<std::string> V,std::vector<std::string> E): V(V),E(E){} Item(const Item& Item)=default; ~Item()=default; Item& ope...
You don't need to write your own, but I'd modify the declaration of your constructor. Item(const std::vector<std::string>& v, const std::vector<std::string>& e):V(v), E(e){} Always prefer passing large object by const reference to by value. Passing object by value may causes unnecessary copy of object.
63,246,792
63,251,316
Operator Overloading: Failed to return an object through *this
The class "vector" is declared as below: class Vector { private: float *arr; int currentIndex; int arrSize; public: Vector(); Vector(int size); Vector(const Vector& V); ~Vector(); float length(); Vector normalize(); Vecto...
You are trying to implement operator+() so you don't want to edit anything in memory for that object (That would be the job of operator+=()). You'd do this: Vector Vector::operator+(const& Vector v) //Note it's Vector, not Vector& { //You probably want to verify that the vectors are the same size? ...
63,247,154
63,247,296
What does the strange syntax mean in c++
In Unreal Project I have this line: class USpringArmComponent* CameraBoom and class UCameraComponent* FollowCamera And I haven't ever seen this syntax in c++. What does it mean?
That's just telling the compiler that UCameraComponent is a class. Not anything else. It's like in C you put struct before any structure variable declarations. This syntax is useful when you have some messy code (or to convey that it is a class verbosely to the developer). For example: class counter { // bla bla bla......
63,247,173
63,257,187
Link Error in Visual Studio 2017 with restbed
I followed resthub github for building the library mkdir build && cd build cmake -DBUILD_SSL=OFF -DBUILD_EXAMPLES=ON -G "Visual Studio 15 2017" .. msbuild INSTALL.vcxproj It successfully created distibution folder. I added those in my sample restbed project as shown below But I am getting the link error as shown bel...
There are three steps to add a lib: Properties->C/C++->General->Additional Include Directories Properties->Linker->General->Additional Library Directories Properties->Linker->Input->Additional Dependencies Also, you could refer to this link about lnk2019.
63,247,254
63,247,552
I need a C++ list with fast search
I created a list with a key and description, however I want the key in the order I added to the list, not sorted by the key. Here's the application: // The list I need of string pairs // I thought about using map or set here but they sort the keys alphabetically. Unordered // leaves the list in random order. I want the...
First, don't do find and then insert. Insert already returns a pair which second element is a bool saying whether insert really occurred. Shorter and more effective: void add_entry(string key, string desc) { if (stuff_map.insert(pair<string, string>(key, desc)).second) stuff.emplace_back(pair<string, string...
63,247,260
63,247,358
How to initialize an object that declared as const on header file?
I want to initialize std::ifstream object only in the main() function after declare it in the header. Is there any way to do it in C++? I wrote this but it's not compiling //header.h #include <iostream> #include <fstream> class class1{ static const std::ifstream fs; }; //proj.cpp #include "header.h" void mai...
static variables need to be defined at global scope, not inside a function. main should also return int not void. A const std::ifstream doesn't make much sense as most of the methods you would need to use are non-const so wouldn't be callable on your const stream. Fixing these issues gives: //header.h #include <iostrea...
63,247,268
63,247,655
For auto loop to fill a matrix
I want to transform a adjacency list to adjacency matrix The adjacency list is as follows: vector< vector< Arc * > * > _adjacences; and class arc has these: public: int sommetArrive; // tops int longueur; // distance I have 3 vectors as follows to be filled: std::vector <int> list[_adjacences.size()]; // vect...
So I think list and listD are a mistake because you are separating information that should stay together. Instead you should construct matrix directly from _adjacences. Like this vector< vector< Arc * > * > _adjacences = ...; std::vector<vector<int>> matrix(_adjacences.size(), vector<int>(_adjacences.size())); for (un...
63,247,383
63,254,881
unable to add imgui to existing scene OpenGL
I am trying to add imgui for debugging the scene but imgui always render at back irrespective of order in which i call render. scene and imgui render fine if done individually(commenting other one). i tried disabling depth testing, using stencil function ,everytime imgui is rendered first . render loop is as void rende...
It would seem that ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); is what is actually rendering the Imgui interface, but it happens right after the glClear(GL_COLOR_BUFFER_BIT); while it happens at the endof the loop in practice what will happen is Clear Draw ImGUi DrawRest Clear etc.. so imGui will al...
63,247,518
63,248,271
Can I be sure that the binary code of the functions will be copied sequentially?
Sorry if this question already exist, because I hope this approach is used but i just don't know how this called. So, my purpose to execute sequence of functions from memory, for this I copied size of first and last func. This is my first try: source.cpp void func1(int var1, int var2) { func2(); func3(); //etc. ...
GCC family only! You can force the compiler to put the whole function to separate section. Then you can know the memory area where the funcion resides. int __attribute__((section(".foosection"))) foo() { /* some code here */ } in linker script in the .text you need to add .text : { /* ... */ __foos...
63,247,519
63,247,598
How to print a character or string in multiple times in c++
I have a my code that's look like this #include <iostream> #include <string> using namespace std; int main() { int x; char chars = '*'; cin >> x; for (int i=1; i<=x; i++){ cout << chars * i << endl; } cout << "\n\n"; system("pause"); return 0; } and it compiled succesfully but, wh...
To do what you want you can do this: #include <iostream> #include <string> using namespace std; int main() { int x; char chars = '*'; cin >> x; for (int i=1; i<=x; i++){ cout << chars; } cout << "\n\n"; system("pause"); return 0; }
63,247,642
63,253,958
Trying to build with boost filesystem: "relocation … can not be used when making a shared object; recompile with -fPIC"
Is this the linux/g++ version of static vs shared libraries? Ubuntu 18.04, boost 1.65, g++ 7.5.0, cmake 3.10.2, GNU make 4.1. Pretty much everything at the default version for ubuntu 18.04, plus the "latest" boost version available via apt-get. (btw, is there a more recent version available for a more recent ubuntu, or...
I ended up dropping back and punting: In cmake, I set(BOOST_USE_STATIC_LIBS OFF) In retrospect, this seems obvious. :wq
63,248,124
63,248,180
Overload resolution in nested namespace with parent namespace
I thought that in a nested namespace, anything that is part of the parent (or global) namespace is considered equally for overload resolution, but this example seems to show otherwise. This works fine: #include <iostream> void foo(int) { std::cout << "int\n"; } void foo(float) { std::cout << "float\n"; } namespace NS...
The point is name lookup, which happens before overload resolution. When the name foo is found at the namespace NS, name lookup stops, the further scopes won't be checked, the global foo won't be found at all. Then there's only one candidate in overload resolution, and int could convert to float implicitly, then NS::fo...
63,248,455
63,248,801
Is having a reference/ptr to std::unique_ptr<> owned object safe when the unique_ptr is in a vector?
On the surface I like the pattern of having a container of unique_ptr's to own data. My question is, is it safe to then take pointers/references to members of such an owned object, if I know that the unique_ptr will not go out of scope? For example I may have auto v = std::vector<std::unique_ptr<ClassWithFooMember>>{};...
Since the ClassWithFooMember objects “in” such a vector are allocated separately, your foo_ptr (or a pointer to the entire ClassWithFooMember object) will remain valid regardless of any operations on v so long as the (anonymous) ClassWithFooMember object exists. For instance, sorting v or causing it to reallocate woul...
63,248,485
63,248,625
Reading words from a text file: weird behaviour
I'm running the following program #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; int main(int argc, char *argv[]) { ifstream input_file(argv[1]); vector<string> words; string line; while(getline(input_file, line)) { cout << line << endl; ...
Because your file has Windows line-endings ("\r\n") and you're on Linux or Mac (which doesn't translate these into "\n"). std::getline is only trimming the '\n's for you. So, \r is left at the end of each of your strings; in many consoles, '\r' moves the write cursor to the start of the line. Then, the " " << words.bac...
63,248,781
63,331,285
Is there a way to make G++/clang++ compile times as fast as MSVC?
For my tests I need to compile some thousand C++ files which have a lot of code in common. Because not all compilers are conformant (or more permissive) I execute all my tests with g++, clang++ and msvc on windows and linux. To improve compile times I use already precompiled headers for common code. Additionally I wrot...
I see at least in the current clang trunk that there is some notable progress to improve compile times in combination with templates and precompiled headers / modules. Perhaps gcc implements something similar - we will see. But thanks for your comments.
63,248,786
63,248,880
Why does passing a struct with const reference members cause a C2280 error?
I ran into a issue while attempting to assign a struct with const& members to a map. struct test { const int& number; test(const int& cnumber) : number(cnumber) {} test(const test&) = default; test& operator=(const test&) = default; }; int main () { std::map<std::string, test> testmap; tes...
Since you have reference members, the test type is not assignable by default. So this line: testmap["asd"] = test(2); // error won't compile since it needs a user-defined operator=, which you have not provided. Instead, you could do: testmap.emplace("asd",test(2)); // ok Here's a demo.
63,248,904
63,249,924
How can I debug C++ pybind11 module with lldb?
I tried to follow the instructions here, but I'm getting the unable to resolve breakpoint to any actual location warning. Here is what I do exactly. I first compile the code with the -g flag: c++ -g -Wall -shared -std=c++11 -undefined dynamic_lookup `python3 -m pybind11 --includes` fractal.cpp -o fractal`python3-config...
All you need to do now is to import your module now. While it's not imported, neither python nor lldb can "know" about existance of your sorce file (fractal.cpp). After you import it, the lldb will immediately react with: 1 location added to breakpoint 1 And then once you call the function with breakpont in it: Proces...
63,249,054
63,249,161
How can I print prime numbers till 10^8 using Sieve?
I have recently learnt Sieve algorithm and started to play with it to learn how to use the algorithm in problems. I have written the code correctly as I can't find any bugs in it, but it closes without showing any output. Can't find what's wrong. Help would be appreciated. #include <iostream> #include <vector> //#defi...
You are creating a static array of size 10^8, which is stored on the stack. This is too large for the stack, and will likely cause a stack overflow. Instead, use a vector that stores the data on the heap, like this: vector<bool> isPrime(MAX+1); Here's a demo. Also, note that you have an off by one error, since you are...
63,249,315
63,250,526
Use of 'auto [...] 'before deduction of 'auto' with recursive, concept-based function template
I wanted to create a deep_flatten function template that would produce a range of elements that are deeply joined. For example, if we take into account only nested std::vectors, I can have: template <typename T> struct is_vector : public std::false_type { }; template <typename T, typename A> struct is_vector<std::vect...
There are two problems here. The first problem is yours: namespace rng { template <std::ranges::range Rng> auto deep_flatten(Rng&& rng) { using namespace std::ranges; if constexpr (range<Rng>) { // <== return deep_flatten(rng | views::join); } else { return rng |...
63,250,039
63,250,073
How do you accept multiple values for a switch case?
How does one accept more than one value for a single case in C++? I know you can make a range of values for one case (e.g. case 1..2) in some other languages, but it doesn't seem to be working in C++ on Xcode. int main() { int input; cin >> input; switch (input) { case 1: cout << "option...
You can "fall through" by having sequential case statements without a break between them. switch (input) { case 1: cout << "option 1 \n"; break; case 2: case 3: cout << "option 2 and 3 \n"; break; default: break; } Note that some compilers support range synt...
63,250,244
63,250,329
Why are namespaces used?
This is confusing me a great deal. All code examples being namespaceA and namespaceB and the method names being foo() and bar() are not helping, either. The way everyone explains it makes it seem as though namespaces are a relic of pre-OOP times where you could not say 'class car give fuel level' but had to go to this ...
For small, self-contained projects, there's not much need for namespaces, and you'd never create a namespace for each object or concept in your code. Larger projects using libraries benefit from being isolated from names introduced by those libraries, as well as some internal organisation to make readability easier. Si...
63,250,539
63,250,590
Assertion intention: assert(!distNodePt == !indexNodePt)
What is this assertion intention? For some reason, I cannot make sense out of it. // Instantiate pointers of two custom types FloatNodeType * distNodePt = distAcc.probe(origin); Int32NodeType * indexNodePt = indexAcc.probe(origin); assert(!distNodePt == !indexNodePt); // What is this assertion trying to ma...
assert(!distNodePt == !indexNodePt); // What is this assertion trying to make sure? This checks that either both pointers are pointing to valid memory, or that both pointers are equal to nullptr. Note that the ! is necessary, otherwise you'd be comparing the actual addresses, which is not the same thing.
63,250,546
63,250,889
QTime behaving different in linux and windows platforms
I have same Qt code which runs in both linux and windows . But it is acting different in each case. In linux it is behaving correct , but while in windows it is not. you can see that in windows platform it is returning null string and in linux platform it is behaving as expected. What could be the reason ?
The default constructor of QTime produces an invalid time, most operations on an invalid time will fail or return another invalid time. Calling addSecs still leaves you with an invalid time and calling toString on an invalid time returns an empty string. To construct a QTime of midnight you need to use: QTime time(0,0)...
63,250,957
63,250,999
C++ how to declare a "complex" object inside a loop?
edit: As mentioned by @HolyBlackCat "If you need it to retain it's [a variable's] value between iterations, it has to stay outside." This is of course true of even primitive types, eg. int. So this question is actually just noise, sorry. I'm trying to get my head around how to be consistent when declaring objects, the ...
Yes, you can do this: std::vector<int> V{i}; which initializes the vector V with the value i when it's declared. On the other hand, neither of your loops are actually doing anything useful. You are redeclaring V inside the loop every time, so previous push_backs are not visible. Also, V is not usable outside the sco...
63,251,088
64,042,380
'Qt5' not found in CMake project with vcpkg static export
I wanna create a project use VSCode+CMake+VCPKG(VTK+Qt5) And I still want to share my VCPKG depencies with teammate. So I export VCPKG. When I try to find_package(Qt5 COMPONENTS Core REQUIRED) problem happened By not providing "FindQt5.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configu...
Finally, I found how to make it Add script in CMALKELIST.txt cmake_minimum_required(VERSION 3.0.0) set(VCPKG_DIR "C:/vcpkg/installed/x64-windows") set(VCPKG_TARGET_TRIPLET "x64-windows" CACHE STRING "") set(CMAKE_TOOLCHAIN_FILE "C:/vcpkg/scripts/buildsystems/vcpkg.cmake" CACHE STRING "") and to add Qt comp...
63,251,425
63,251,600
Why is the return value of std::getline not convertible to bool?
When I run the below example code from Accelerated C++, I get the error: error: value of type 'basic_istream<char, std::__1::char_traits<char> >' is not contextually convertible to 'bool' while (std::getline(in, line)) { I read in this answer that starting from C++11, getline() returns a reference to a stream whic...
You didn't add #include <istream> to your code, so the compiler doesn't know what istream is and therefore it doesn't know it is convertable to bool. Add #include <istream> to fix the issue.
63,252,062
63,285,352
Problem with CreateDC of printer after call PageSetupDlg() function
I am working with project in C++ WinAPI for WindowsCE 2013. IDE which I use is Visual Studio 2013 I firstly initialize a PageSetupDialog in my application.. Screen below: Unfortunately I still have problem with start printing. I have assumption that problem is in CreateDC that the values from DialogBox are not forward...
Problem was solved by this fragment of code: memcpy(&dm, (DEVMODE *)(psd.hDevMode), sizeof(DEVMODE)); lstrcpy(DriverName, ((TCHAR *)((BYTE *)psd.hDevNames + ((DEVNAMES *)psd.hDevNames)->wDriverOffset))); lstrcpy(DeviceName, ((TCHAR *)((BYTE *)psd.hDevNames + ((DEVNAMES *)psd.hDevNames)->wDeviceOffset)))...
63,252,262
63,252,281
size_t template parameter in std::array
The std::array template parameters are template < class T, size_t N > class array; where N stands for the number of elements in the array. My doubt is why is the type std::size_t? Isn't std::size_t an alias for the size of an object/pointer in bytes. std::size_t Why is it used to denote the number of elements in std::a...
The type std::size_t is defined to be a numeric type that can represent the size of the largest possible object (say, N bytes). The largest object could be an array, and the array with the most possible objects is therefore an array of N chars. So, std::size_t makes sense for array indexes and dimensions too. You shoul...
63,252,346
63,252,400
Deduce template type from lambda invocation on container
I have the following map implementation that takes a vector and a lambda as input and returns a new vector. template <typename R, typename T, typename Predicate> std::vector<R> map(const std::vector<T> &v, Predicate p) { std::vector<R> mapd(v.size()); std::transform(v.begin(), v.end(), mapd.begin(), p); ret...
Do you mean something as follows ? template <typename T, typename Predicate, typename R = decltype(std::declval<Predicate>()(std::declval<T>()))> std::vector<R> map(const std::vector<T> &v, Predicate p) { std::vector<R> mapd(v.size()); std::transform(v.begin(), v.end(), mapd.begin(), p); return m...
63,252,748
63,252,838
c++ template argument deduction from another argument
I'm using pimpl pattern in my code, so for each class X, there will be a corresponding impl class XImpl Say we have A, AImpl, B, BImpl, C, CImpl, where A,B,C are similar class, and I would like to write some template function for them. template <typename T, typename TImpl> std::shared_ptr<const T> GetObjectById(int id)...
Do you mean something as follows ? template <typename T, typename TImpl = typename T::impl> std::shared_ptr<const T> GetObjectById(int id);
63,252,791
63,253,758
Calling a function that moves the parameter value in a function that copies it
I passed by the following code: void enqueue(T&& value) { move_value_somewhere( T(std::move(value))); } void enqueue(const T& value) { enqueue(T(value)); } The second function that copies the input parameter, calls the first function that moves it. Assuming the code is correct, how is that T(std::move(value))...
In void enqueue(const T& value), a temporary T is being copy-constructed from value as input. That temporary is then passed to void enqueue(T&& value). In void enqueue(T&& value), another temporary T is being move-constructed from value as input (assuming T has a move constructor, otherwise it will be copy-constructed...
63,253,128
63,258,767
Segmentation fault when trying to fill a vector as instance variable
I want to make a filled matrix as an instance variable in my .hpp file but end up with seg fault. I have a graphe class. In my .cpp file, i filled an adjacency matrix as follows void Graphe::shortRoute( void ){ std::vector<vector<int>> matrix(_adjacences.size(), vector<int>(_adjacences.size())); std::vector<vec...
Not what you are asking about but this code for ( unsigned i = 0; i < _adjacences.size(); i++) for (unsigned j = 0; j < _adjacences.size(); j++) { shortPath[i][j] = SP[i][j]; matrix[i][j] = M[i][j]; } can be simplified to this shortPath = SP; matrix = M; You don't have to write loops t...
63,253,164
63,253,360
When the file is opening in C++ and we start reading , does the whole file load to RAM from hard disk or just a block by a block?
When the file is opening in C++ and we start reading , does the whole file load to RAM from hard disk or just a block by a block ?
You decide how much to read into RAM. When you do 'getline' or read an amount into a buffer you are moving it from disk to RAM. If the file format is 'streamable' you can work on small chunks of the file at a time and still do the entire operation. Some file formats you need to read in most of the file to do an operati...
63,253,259
63,254,730
How to exit from a stream reading loop, avoiding an additional empty loop?
When the program enters in the if and then break, empty cout-s are printed again. void Person::ShowRecords() { std::ifstream data("Input.txt"); while (true) { if (!data.good()) { break; } Person person; data >> person; std::cout << "Firs...
I really think that the most didactic way of tackling stream input is: while (true) { // Read // Check (if fail then break) // Use } Notice the pattern: infinite loop with Read/Check/Use. Check is where we can exit the loop. First you read, than you check if the reading operation was successful or failed, ...
63,253,270
63,253,513
C++/Qt5: Get a random image file from specified location
Given a folder and subfolders all containing jpeg files, what function can I write an function to pull a random file from it, every time the function is called. For example say we have the follwing directory structure: root_directory/ ├── image_1.jpg ├── child_directory_1/ │ ├── image_1.jpg │ └── i...
my suggestion would be, use the qdirEntryList: set the root to root_directory then search all the images using a filter(png, jpg or what you need) and after that, generate a pseudo random number between 0 and list.size() and use that as index for getting the path of the image, that finally you will use in the construc...
63,253,287
63,253,897
Using SFINAE to detect method with GCC
I am having trouble using the SFINAE concept to detect if a class has a particular template method with some compilers, most pertinently GCC. Consider the code below. It compiles and works as expected with MSVC; however, when I compile the same code with GCC, it complains that std::vector<double> does not have a seri...
In the event someone else encounters a similar error/misunderstanding, my error (aptly pointed out by n. 'pronouns' m.) was using the wrong type in the has_serialize::test. From what I can infer (in my naivety) is that for template<typename T> struct has_serialize { // ... template<typename C> static const...
63,253,398
63,253,865
Explanation of the algorithm to find a number 'm' made up of digits 0's and 1's which is divisible by the number n
Here's a piece of code from a udemy course that I am currently taking that uses the pigeon hole principle to find a number made up of 0's and 1's divisible by the number n. void findNumber(int n) { int cur_rem = 0; for(int i = 1; i <= n; i++) { cur_rem = (cur_rem * 10 + 1) % n; if(cur_rem == 0) { for(in...
Suppose the last number 111... (we'll call it m), had remainder r. m % n = r m = kn + r Now the next number, 111..., call it m', is one digit longer than m. m' = 10 m + 1 m' % n = (10 m + 1) % n = (10(kn + r) + 1) % n = (10 kn + 10r + 1) % n = ( 10r + 1) % n
63,253,822
63,253,986
Access elements of a char* and check value C++
I know you can access individual characters stored in a character array: example[] = 'HeLlo"; for (int i = 0; i < 6; i++) { if (example[i] >= 65 || example[i] <= 90) { example[i] += 32; } } Unfortunately this won't work for my code as I have to store it in a character pointer (I am taking input fr...
You can't store user input into an uninitialized pointer. You need to allocate a character array of sufficient space, and then read into that array, eg: #include <iostream> #include <iomanip> #include <cstring> // Store input in mode char mode[256] = {}; std::cin >> std::setw(256) >> mode; or: std::cin.get(mode, 256)...
63,254,013
63,254,600
How to use Swift static library (.a) in C++ project?
I have a pure Swift package that I built with the Swift Package Manager. My Package.Swift looks like this: // File: Package.swift // swift-tools-version:5.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Swif...
Summary: this can be made to work (probably), but if this is intended to be used in production code, then the only correct approach is to consult the Swift documentation and, if it is still the case there is no official support, ask the Swift team how to approach the problem. You should follow whatever documentation S...
63,254,256
63,254,368
Is there an XLib alternative for glXSwapBuffers()?
I want my application to instantly draw all the data to a display. In windows there is SwapBuffers() function to do such kind of things, where you can do all the drawings to a second virtual window and then swap that virtual window with an existing one. OpenGL provides a glXSwapBuffers() function to do roughly the same...
In X11 there are the Pixmap resources which are considered as Drawable (like Window). Then you can draw to a Pixmap using as many steps as necessary, and finally use XCopyArea() to send the resulting drawing to a Window. Note that a Pixmap stands on the server side, like a Window, so the final copy operation is local t...
63,254,782
63,257,256
Undefined identifiers with glfw
#include <iostream> #include <GLFW/glfw3.h> #include <math.h> const GLchar* vertex120 = R"END( #version 120 uniform mat4 matrix; attribute vec4 inColor; attribute vec4 inPosition; varying vec4 outColor; void main() { outColor = inColor; gl_Position = matrix * inPosition; } )END"; int main() { GLFWwindow* ...
OpenGL is implemented by the graphics driver as a bunch of functions implemented, not as a standalone library, therefore cannot be simply linked to your project. To call a function you have to ask OpenGL for a pointer to that function and you have to do that with all the functions you will call. You can do that by func...
63,254,978
63,255,308
Candidate template ignored: couldn't infer template argument 'T'
I know this question probably has been asked before but I'm a beginner to templates, and here is my code, HeaderFile.h class Identity { public: template <typename T> T getFamilyMembers() { if(1) { return false; } std::string whatever = "Test"; ...
This isn't how templates work. The caller specifies what T is. When T is a return type, then all return statements in the function must be a T value, or something implicitly convertible to T. The function itself can't dictate what T is at runtime. Beyond that, T is known at compile time. You can't return different t...
63,255,298
63,257,125
Defining a function for different containers
I want to define a function that accepts different types of containers: those that own the data (like std::vector) and those that don't (like boost::iterator_range). I wrote the following: #include <vector> #include <boost/range/iterator_range.hpp> template<typename C> void fill(C& c, typename C::value_type v){ fo...
You can use perfect forwarding: template <typename C> void fill(C&& c, typename std::decay_t<C>::value_type v) { for (auto& j : c) j = v; } This isn't actually "perfectly forwarding" since you're not looking to take advantage of move semantics, if you wanted to you should write std::forward<C>(c) instead ...
63,255,352
63,255,388
How to alias a template function inside a template class
I have a need to implement 2 functions inside a templated class, where both functions do similar things, but not everything is the same. My proposed solution was to use if constexpr on a single template function, and then have an alias for each function: template <typename T> class MyClass { private: template <bool ...
You could do: void TestTrue() { TestFunc<true>(); } void TestFalse() { TestFunc<false>(); } I don't think there's a better way.
63,255,668
63,262,123
LLVM - setting insert point of BasicBlock after adding instructions causes segfault
I'm writing a compiler frontend using LLVM. If I create a BasicBlock, add some Instructions to it and finally set the insert point, everything work fine. But when I call SetInsertPoint and THEN add some instruction like this: Function * MainFunction = Function::Create( FT, Function::ExternalLinkage, "main", m_Modul...
m_Builder.SetInsertPoint( BB ); m_Builder.CreateCall( m_Module.getFunction( "writeln" ), {ConstantInt::get( m_Context, APInt( INT_SIZE, 1 ) )}, "calltmp" ); m_Builder.CreateRet( ConstantInt::get( Type::getInt32Ty( m_Context ), 0 ) ); Try this.
63,255,818
63,255,894
Error related to headers and namespaces when migrating from C++/CX to C++/WinRT
File.h: std::map<winrt::hstring, winrt::hstring> someMap; File.cpp auto it = someMap.find(someKey); if (it != someMap.end()) { it.second += (winrt::hstring{L", "} + someString.c_str()); } I get the following error: 'second': is not a member of 'std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<_Ty>>>' ...
std::map::find returns an iterator. An iterator doesn't have first or second members, unlike the actual items of the map. If you want to access the item, you need to dereference the iterator, either by using the * or the -> operators: auto it = someMap.find(someKey); if (it != someMap.end()) { it->second += (winrt:...
63,256,081
63,256,253
error: aggregate ‘HMAC_CTX ctx’ has incomplete type and cannot be defined
I am trying to understand what is going wrong while I compile my application ang got the following error: security.cpp: In member function ‘void Crypt::load()’: security.cpp:16:21: warning: ‘void OPENSSL_config(const char*)’ is deprecated [-Wdeprecated-declarations] OPENSSL_config(NULL); ^ In fil...
In recent versions of OpenSSL (as of 1.1.0, I think), a number of structures which were previously declared publicly have now become private and appear in the public header files as incomplete types only. In consequence, you cannot use them directly in your code (you can only use pointers). In consequence, the way you...
63,256,524
63,256,730
Navigating through project directories to call or invoke another program or executable within its own process
I'm working in Visual Studio 2017. In my current solution, I have 2 active projects. The 2nd project depends on the 1st project and my 2nd project is my startup application. When I run or compile my 2nd project, there is already a compiled executable of my 1st project that is within my solutions directory... Here is th...
Aside from the lack of any error handling on CreateProcessA(), you are trying to launch CacheQuery.exe using a relative path, so the issue is most likely that the current working directory of the calling process is not what you are expecting it to be, causing CreateFileA() to fail if it can't find CacheQuery.exe. You s...
63,256,659
63,262,075
operator= overloading, terminator called recursively
I am having an issue with overloading the assignment operator. I am getting a "terminator called recursively" error in the console. I am relatively new to data structures and I'm having trouble debugging this issue. Here is the class declaration: class Player { public: Player(const unsigned int x_, const unsigned i...
I think that using Position* pos is not a good choice. You always have to initialize it by constructor. Although you did so, in Player& operator=(const Player& p_), i think there is trouble with first line and second line. You already removed pos in memory by delete pos but you're trying to set pos to nullptr.
63,256,668
63,256,750
c++ compiling error for reading object from file
I saved objects to file and while reading them back i want to write it content to output stream. I did add operator overloading for it friend std::ostream& operator<<(std::ostream& out, T& c) but how to do it in correct way? #include <iostream> #include <fstream> class MySpecificClass { std::string data; unsig...
Basically this, outside of your class definition: std::ostream& operator<<(std::ostream& out, MySpecificClass& c) { out << c.Print(); return out; } You don't need to add the friend function definition, because you are not using any private members in your operator<<. And if you were, you would actually need to...
63,256,695
63,257,114
g++ permission denied(Mac)
I tried to run a c++ file with the mac terminal, but it gave me the error as shown below: Does anyone have any idea why this is happening?
If you do this gcc test.cpp you will get executable called a.out, and to run it you type: ./a.out to get executable called test you have to run g++ test.cpp -o test now you can run this: ./test
63,256,711
63,256,747
How to get the returned exit value of an invoked program to store it internally?
This question is related to a previously asked question found here: I'm able to invoke another executable within my runProgram() function. However, before this runProgram() function returns back to main() and closes the handle for the process. I need to retrieve the value that the executable returns when it exits... He...
You can get it by calling GetExitCodeProcess (pi.hProcess), after waiting on the handle but before you close it. The exact code you need is: DWORD exit_code; BOOL ok = GetExitCodeProcess (pi.hProcess, &exit_code); Strange this is not mentioned in the Remarks section for CreateProcess at all.
63,256,855
63,256,950
Initialize with global variables in c++
I've tried to read the thread below about creating global variables that can be used between multiple files but it will not work. Global Variable within Multiple Files variable.h extern const int variable1; file1.h class fileOne{ private: fileTwo ft[variable1]; public: //some functions... }; file2.h clas...
To define an array you need to specify the actual size of the array and the size must be something the compiler can turn into a constant. Since variable1 can't be turned into a constant, the compiler issues the error. What you can do is something like the following. file1.h class fileOne{ private: fileTwo ft[variab...
63,256,976
63,257,135
C++: Can a Template be friend of a Class?
Is it possible to make friend of a class, all possible variants of a class-template? Just to clarify, for example, something like this: class A { friend template B; } // syntactic error yeah So any B<X> variant could manipulate any protected attribute of A. A is an small and simple class with a lot of friends who m...
You may define a friend template class like that: class A{ template<typename T> friend class B; }; That would make every specialization of class B a friend of class A. I've had a similar question that had the opposite goal: to restrict some specializations: Friend template function instantiations that match pa...
63,257,072
63,257,159
How do I return multiple values in a function C++?
I am writing some code and ran into an error when I need to return multiple values to main() from another function. Here, I am trying to return item and total to the main() function. However, I am getting a warning saying that item has not been used, but I am using it in main(), where it then says "use of undeclared i...
Use the below in your processSelection referencing https://www.geeksforgeeks.org/returning-multiple-values-from-a-function-using-tuple-and-pair-in-c/ from Mike. return std::make_pair(item, total); and call using in your main. std::pair<int, int> p = processSelection(); Then you can use p.first and p.second to access ...
63,257,265
63,265,787
Find base address of a a specific program in storage/memory?
I want to find the current base address of a program without any manual input. Basically I want to write to specific addresses in memory using offsets. To do that, I need to find the base address of the program I'm modifying. Currently, I can do that by finding the base address manually through another software, howeve...
I've researched this a lot and we only need two methods two find the base address of any process you want. DWORD GetProcessId(const wchar_t* processName); //gets the process Id uintptr_t GetModuleBaseAddress(DWORD processId, const wchar_t* moduleName); //gets the module base address These are the main headers that w...
63,257,756
63,259,641
C++ Not find members
Error message: "std::__cxx11::basic_string<char, std::char_traits, std::allocator>" No members "isSubsequence". #include<iostream> #include<string> #include<unordered_map> #include<vector> using namespace std; class Solution { public: bool isSubsequence(string s, string t) { if(s.size()<t.size()) return f...
There's a naming conflict here: string s = "abc"; // ^ string t = "ahbgdc"; Solution s; s.isSubsequence(s,t); ^ ^ Probably you wanted to do: string str = "abc"; string t = "ahbgdc"; Solution s; s.isSubsequence(str, t);
63,257,764
63,258,892
Rotation in an AVL Tree
While performing a rotation in an unbalanced binary search tree, we need to rotate the parent node[single rotation] if the imbalance is being caused in right-right or left-left. so the parent node can be easily accessed as it is being passed to the function. void add_node(T data,Node<T>* &node){ if(this->root==null...
Now there are multiple ways in which you could implement this; by passing the parent node, or by passing the left/right pointer of the parent by reference when you take left/right path respectively or by returning the root of the current subtree (after balancing if it's required) to the parent as you're moving up the t...
63,258,000
63,258,032
An error "Call to constructor of ' ' is ambiguous", although the class's constructor parameters do not look the same?
There is an error message that appears Call to constructor of 'Binary' is ambiguous, that error message just appears when using LLVM compiler on macOS but on windows, it doesn't appear. Also, the class's constructor parameters do not look the same. class Binary { public: Binary() = default; Binary(uintmax_t con...
uintmax_t is a typedef for the maximum-width unsigned integer type on your machine. When compiling your code, if that type is not exactly unsigned long long, then this call: Binary fileContent((unsigned long long)fileSize); is ambiguous, since the argument will need to undergo exactly one conversion to match either o...
63,258,289
63,461,801
Can function loaded from dlopen call a function from the executable that loaded it?
Setup Suppose I wrote a program in C/C++ and wanted to allow plugin loading. The typical solution would be to write the plugin as: plugin.c int my_plugin_fn() { return 7; } And compile it using something like gcc -fpic -shared -o plugin.so plugin.c Then, in the main program that loads this plugin, we might have: l...
Is there a way to have plugins loaded using dlopen() call functions from the program that loaded them? Yes, but the function that you want to call from the main executable must be exported from it, which does not happen by default. You can see which symbols are exported from your main binary with nm -D loader. You ca...
63,258,343
63,258,416
G++ Not Finding Included .cpp Files When Compiling
Inkey.cpp and Key.cpp are in the same directory, /root/src. Compile.bat is in /root. When I run Compile.bat, I am given the message "Key.cpp: No such file or directory". Thanks in advance for any advice. Inkey.cpp #include <iostream> #include <Key.cpp> using namespace std; int main(int argc, char *argv[]) { cout ...
First off, rename Key.cpp to Key.h. Put the declaration in Key.h. Then put the definition in Key.cpp (Don't forget to include Key.h here). Then include your Key.h in all files using Key objects. Now, compile them with g++ -o filename.out file1.cpp file2.cpp -O3 -Wall Also, learn to use boilerplate code P.S. as @Sorone...
63,258,494
63,258,539
'arr' was not declared in this scope when declaring arr in default constructor
I am new to C++. I am trying to implement a stack. I am declaring an arr named variable inside the default constructor. But when I compile my code I get an error saying 'arr' was not declared in this scope My code: #include<iostream> using std::cout; using std::endl; using std::cin; class Stack { private: int to...
The int arr[n]; // 100 element stack is a local variable that exists only inside the constructor(scope). The other members will not know about this array and that is the reason for the error. Move the array declaration to the private section and n should be known at compile time class Stack { private: int top = -...
63,258,527
63,258,859
Cause of Infinite Loop? (iterative inorder traversal implementation) C++
Question: Implement Inorder Traversal iteratively. My Attempt: (results in an infinite loop that I haven't been able to debug) any help or suggestions greatly appreciated /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val...
Here is the problem : dfs.push(dfs.top()->left); visited.insert(dfs.top()->left); You are pushing to stack (then dfs.top() will change) and then accessing dfs.top()->left in the next line.
63,258,679
63,260,014
How to correctly call the HeapSummary API in Win32?
I would like to call the HeapSummary function from the Win32 API: https://learn.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapsummary There seems to be missing a list of the possible options for the dwFlags parameter. I tried with no flags but GetLastError() returns The parameter is incorrect error messa...
As @Jonathan Potter says, We should set the cb member to sizeof(HEAP_SUMMARY). I create a sample to find the reason: #include <windows.h> #include <heapapi.h> int main(int argc, const char* argv[]) { HEAP_SUMMARY heap_summary; memset(&heap_summary, 0, sizeof(heap_summary)); HANDLE h = GetProcessHeap(); ...
63,259,165
63,259,197
Rvalue references, copy and move
Consider following section of code for swap : //for some type T void swap(T& a, T& b) { T temp = a; a = b; b = temp; } and this one below : //for some type T void swap(T& a, T& b) { T temp = static_cast<T&&>(a); a = static_cast<T&&>(b); b = static_cast<T&&>(temp); } I have following doubts : W...
What is the difference between them? I mean why the first swap is more expensive than the second one ? The second one enable move for types that support it (ie having move assignment operator). Those types include standard vector, string, etc. For basic types (int, bool, etc.) that does not support move semantic, the...
63,259,214
63,259,370
How to legally declare vector variables in C++?
I'm new to C++ and trying to understand how declaring vectors work. Below are some examples: std::vector j; std::vector<char[256]> k; std::vector<double> v; std::vector<std::vector<int>> s; My thoughts are only the std::vector<double> v is legal and I tested it myself such that only this line of code compiles without ...
A fixed array template for a std::vector was not allowed up to and including C++03. This is because arrays are neither CopyAssignable nor CopyConstructible. So std::vector<char[256]> k; is invalid pre-C++11. From C++11 onwards you can declare such a type, although you'll have difficulty using such an instantiation - e....
63,259,278
63,267,195
[leetcode 5 ]Can't really find what's wrong in my solution for longest Palindrome substring problem
input: babad abbd output: ad bb expected: bab bb Code: #include<iostream> using namespace std; class Solution { public: string longestPalindrome(string s) { int maxlength=1; bool ispalindromic[1000][1000]={false}; for(int i=0;i<s.length();i++) ispalindromic[i][i]=1; ...
There are some problems with this code. Indices of your for loops When you consider the length l of a possible substring, your l should go between 2 to s.length(), so the outer for loop should be: for(int l=2;l<=s.length();l++){ You see I changed l < s.length() to l <= s.length() Then your i index of inner loop shoul...
63,259,644
63,298,899
Allocating Memory to a Program Upon Initialization in C++?
I would like to allocate a set amount of memory for the program upon initialization so that other programs cannot steal memory from it. Essentially, I would like to create a Heap for my program (without having to program a heap module all for myself). If this is not possible, can you please refer me to a heap module th...
What you ask is not possible with the features provided by ISO C++. However, on most common platforms, reserving physical RAM is possible using platform-specific extensions. For example, Linux provides the function mlock and Microsoft Windows provides the function VirtualLock. But, in order to use these functions, you ...
63,259,972
63,262,580
Find all logical drives from a unitmask
I have wrote a program to detect usb drive whenever it is inserted. I want to know all the partitions on the usb. If my drive has one partition (example E:/), then the program detects successfully. But if the usb drive has two partition (example: E:, F:) then only first partition E: is detected but I do not know how to...
The following function could be helpful: std::string DrivesFromMask(ULONG unitmask) { char i; std::string drv = ""; for (i = 0; i < 26 && unitmask; ++i) { if (unitmask & 0x1) { drv += i + 'A'; } unitmask = unitmask >> 1; } return drv; } And then read ...
63,260,636
63,263,187
C++ passing a funtion returning a structure to thread-pool creates erratic results and "hangs"
I am a hobby programmer learning C++ and multi threading. After some troubles getting started on my first thread-pool attempt. Thanks for the suggestions I received in this forum. I have come to a point where the principals are working. What I am trying to achieve is to extract 20 tags from a music file (FLAC). There m...
HTags Tags in ExtractTrackTags looks suspiciously like a global variable. If that's actually the case, then that's the cause for your issues. Reduce it's scope to ExtractTrackTags (so each thread has its own, isolated copy), and the issues should resolve themselves.
63,260,695
63,260,791
Regex to match sql where conditions
What should be my Regex to match fetch the WHERE condition without (GROUP\\ BY|HAVING|ORDER\\ BY|ASC|DESC|LIMIT)? It works fine if I have any of the described params. It should also work for both the cases (with or without these parameters) I need to get id=1 or id=2 QString query = "SELECT * FROM users WHERE id=1 or i...
You may use QRegularExpression whereListRegex(R"(\sWHERE\s+(.*?)(?:\s+(?:GROUP\s+BY|HAVING|ORDER\s+BY|ASC|DESC|LIMIT)\b|\s*$))", QRegularExpression::CaseInsensitiveOption); See the regex demo The regex matches: \s - a whitespace WHERE - a string \s+ - 1+ whitespaces (.*?) - Capturing group 1: any zero or more chars o...
63,260,754
63,277,970
SWIG: avoid C++-to-Python aliasing
I am building a library in C++ which is interfaced to Python 3 using SWIG 4.0.1. After some time developing I noticed a problem with (what I think is called) aliasing. I prepared a minimal example which this also happens. Consider the class dummy with a single (private) attribute attr which is initialized at 0. Now, I ...
So, thanks to a few comments in the original post, a possible solution is to add a clone() method. One could do this by simply extending the C++ header. But, since this may seem weird to some people as in many cases a clone() method in C++ is not necessary at all, we can extend the python class using SWIG. Simply take ...
63,260,896
63,260,947
How does double data type change the answer compared to int, by a huge amount in C++?
I was solving a problem "Count the number of digits in a factorial", and stored the answer in two data types int and double. The answers from both the datatypes are different, and the one stored in double was finally correct. How is this happening? Here's the code: int n; cin>>n; double ans; ...
Converting a double number to int rounds it down to the nearest integer first. So if you add up say log10(x) for x ≤ 10 ≤ 99, the logarithm is always between 1 and 2, but converting to int will only add 1, instead of the correct value.