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
64,261,118
64,261,981
set insert iterator is outside range
My program crashes, when I run this code bellow: std::set<int> m_set = {1, 2, 3, 4, 5 }; std::set<int>::iterator setIt = m_set.begin(); ++setIt; m_set.erase(setIt); m_set.insert(setIt, 25); I have a std::set, which filled by objects Point. The code compiles successfully, but crashes her...
From your comment I think you have a little misunderstanding about std::set. I think you were trying to replace an element like you would do in a std::vector or std::array. But a set is a sorted collection, you can't just take one element out and put another element in exactly the same spot, because most likely it woul...
64,261,360
64,262,452
How are Python's C and C++ libraries cross platform?
Many of Python's libraries, e.g. Pandas and Numpy, are actually C or C++ with Python wrappers round them. I have no experience with compiled languages and don't understand how these libraries are cross platform (i.e. run on Mac, Windows, Linux), since my understanding is that C and C++ need to be compiled for a specifi...
As has been pointed out in comments, Python package using C/C++ compiled code require compilation on the target architecture for them to be cross-platform. Under the hood, when you use pip install pandas for example, pip will look for the requested package on PyPI and, if available, it will install the wheel correspond...
64,261,856
64,262,004
Issue when using std::find with an array of std::string
I'm trying to run this comparator: if (std::find(movements->begin(), movements->end(), commandBuffer) != movements->end()) with: const std::string movements[8] = {"north", "south", "east", "west", "n", "s", "e", "w"}; where commandBuffer is a std::string. On MinGW32 9.2.0, I get the following: error: no match for 'o...
Either use std::cbegin and std::cend, or change your array into a std::array: std::array<const std::string, 8> movements = {"north", "south", "east", "west", "n", "s", "e", "w"}; const std::string commandBuffer = "north"; if (std::find(movements.begin(), movements.end(), commandBuffer) != movements.end()) std::cou...
64,261,873
64,262,000
What does this error mean? C6001: using uninitialized memory 'Rect.'
Visual Studio gave this bizzare error: C6001: using uninitialized memory 'Rect.' #include<iostream> #include<cstring> using namespace std; class Rectangle {public: int length, width; int Area(int length, int width) { return length * width; } }; int main() { Rectangle d1; d1.length = 5...
The object Rect declared in this declaration Rectangle Rect; has uninitialized data members length and width. These uninitialized data members you are passing as arguments to the member function Area. Rect.Area(Rect.legth, Rect.width); So the call does not make a sense. You could write for example Rectangle Rect = { ...
64,262,171
64,262,244
How to write a constructor for a template class using universal reference arguments in C++
I have a C++ template class MyClass with two type parameters: template <typename D, typename S> struct MyClass { private: D d_; S s_; }; I want to add a constructor with D and S references as parameters, so it can get D and S inferred: template <typename D, typename S> struct MyClass { // can bind to lvalu...
In this snippet, d and s are NOT universal references - they are rvalue references (because D and S are already known (deduced) within class by the class instantiation). template <typename D, typename S> struct MyClass { constexpr MyClass(D &&d, S &&s): d_(std::forward<D>(d)), s_(std::forward<S>(s)) {} ...
64,262,591
64,262,939
Unable to implement MaxCLL, MaxFall, MasteringDisplayColorPrimaries parameter definitions using the MediaInfo.h library
I can't implement the definition of the MaxCLL, MaxFall, MasteringDisplayColorPrimaries parameters using the MediaInfo.h library. Calling other parameters works fine. I tried the following commands: std::wstring maxCll = MI.Get(Stream_Video, 0, L"maximum_content_light_level"); std::wstring maxFall = MI.Get(Stream_Video...
Field names are "MaxCLL", "MaxFALL", "MasteringDisplay_ColorPrimaries", "MasteringDisplay_Luminance". Generally speaking, you can get the field names from e.g. the XML or JSON outputs or mediainfo -f --Language=raw. Note: I also answered on the MediaInfo forum topic.
64,263,174
64,263,352
What realization to choose for heterogenous container that uses std::variant for data storage?
For a program which is a simple rogue-like game, I need a container for storing contents of each room be it enemies, loot, traps, lore-entries etc. Since set of types being held in each room is finite and predetermined I've settled for std::variant for data storage. I also will need methods to process the data and here...
Which of the two approaches is better? Neither, see option 3 below. How can I prevent the program from creating a container that holds anything other than std::variant<>? using myVariant = std::variant<TYpe1, Type2 ... TypeN>; using myVector = std::vector<myVariant>;
64,263,259
64,263,634
Converting C union to C++ union
I'm a trying to migrate some legacy C code for Embedded targets to C++ for compatibility issues and I am encountering some issues with unions in C++. in our project we have the following style of union to reduce the amount of RAM usage: typedef union unionTest { struct { uint32_t nField1:5 ; uint32...
I have a "too many initializers" error. The solution to this is simple. You need a set of braces to explicitly express that you are initialising the nested class within the union: { // the union { // the struct .nField1 = 1, // members of the struct .nField2 = 2, .nField3 = 3, } }; I...
64,263,462
64,264,001
How to prevent manually instantiating all template types?
I have a function Foo that gets two template args L3HdrType and L4HdrType. I receive a packet and parse it and then need to call the function. My code currently looks like: ParsedPacket parsed_packet = parser.Parse(packet); if (parsed_packet.ip_version() == IPv4 && parsed_packet.ip_proto() == TCP) Foo(parsed_packet.L...
If inheritance and runtime polymorphism is not an option you can decouple deduction of the two template parameters by doing some acrobatics involving lambdas: template <typename T> struct foo {}; template <typename T> struct bar {}; // the function to be called template <typename A, typename B> void foobar( foo<A>...
64,263,548
64,263,771
Keep open braces on the same line in Visual Studio 2019
By default, my VS 2019 creates new function definitions like this: void somefunction() { } Is there a setting I can change to default it to this? void somefunction() { }
Go to Tools → Options → Text Editor → C/C++ → Formatting → New Lines → Position of open braces for functions → Keep on same line ...
64,264,725
64,281,912
How can I prevent opening a QFile multiple time in parallel
I have written a function to check whether a file on disk is already in use. This is to avoid trying to execute a freshly downloaded installer while the antivirus is checking it, which fails. The (generic) function looks like that: bool isFileInUse(const QString& filePath) { QFile f(filePath); if (!f.exists()) ...
On Windows a file is opened for reading and/or writing and a share mode allowing additional reading/writing/deleting. This can create many interesting combinations, for example a file can be open for writing and allow additional open for reading but not writing. Or a file can be open for reading and allowing renames/de...
64,264,853
64,264,943
C++ How to sum only even values stored in vector?
I am new to C++, and I have run into a total lack of understanding on how to sum only even values stored in a vector in C++. The task itself requests a user to input some amount of random integers, stop when input is 0, and then to return the amount of even values and the sum of those even values. This is as far as I h...
The function to be passed to std::accumulate takes 2 values: current accumulation value and value of current element. What you should do is add the value if it is even and make no change when not. int m = accumulate(vet.begin(), vet.end(), 0, [](int cur, int m) { if ((m % 2) == 0) { ...
64,265,808
64,265,840
c++ type_traits: Why can't I call templated static methods from another template / enable_if line?
I would like to use a static method in a template parameter in my function in an enable_if expression. However, the static method is also a template, and I get compiler errors. The error message: $ g++ test.cpp test.cpp:20:36: error: invalid declarator before ‘(’ token 20 | std::enable_if_t<A::method_a<param>()> C...
In func_a, the name method_a is a dependent name i.e. the meaning of method_a depends on the template type parameter A. If the name is a member template, you need to specify that with the template keyword: template<int param, typename A> std::enable_if_t<A::template method_a<param>()> // ^^^^^^^^ func_...
64,266,025
64,266,079
Passing object of base class to function of reference to derived class
I'm trying to write code which can find the distance between lots of different types of shapes. I've defined a base class Shape with a virtual distance(Shape& otherShape) function to find the distance to another shape and then want to define that for all my derived classes. The problem is that there are lots of possibl...
You would have to cast the Shape& to a Circle& return circleCircleDistance(*this, static_cast<Circle&>(otherShape)); As an aside, I'd handle your types a bit differently class Shape { public: virtual ShapeType get_type() const = 0; // derived classes must override this virtual double distance(Shape& otherShap...
64,266,258
64,266,390
Storing and passing on parameter pack in factory class
I'm trying to write a "factory" class template whose instantiations have variadic constructors which store their arguments in a tuple and later pass on these arguments to the constructors of objects created by the factory. A minimal example might make it clearer: #include <memory> #include <tuple> struct Foo { Foo(i...
All you need to do is wrap the std::make_unique call into a perfect-forwarding lambda: std::unique_ptr<T> create() { return std::apply( [](auto&&... xs) { return std::make_unique<T>(std::forward<decltype(xs)>(xs)...); }, _stored_args); } live example on godbolt.org The reason is that std::make_uniq...
64,266,777
64,266,797
print an array after deep copying in c++ classes
I want to achieve the following behaviour: The class DataSequence has a pointer that points to an array in the main function. print the array when an object in initialised of the class DataSequence create a deep-copy of the same object (via a copy constructor) and print it when the object is formed. The code I have w...
This statement: ptr = new float; only allocates a single float. That means in this loop: for(int i=0 ; i<_size; ++i){ cout << *(ptr+i) as soon as i is greater than 0, you dereference invalid memory, which is undefined behavior. This results in a program that can do anything, including producing the "garbage" outp...
64,267,330
64,267,372
How can I copy a vector to the end of another vector?
I have been working on what I thought would just be a simple function for quite a while now. We are expected to use push_back(), but I haven't been able to get it to work. Here's what I have right now: void append(const vector<int>& v1, vector<int> v2) { for (int x : v1) v2.push_back(x); } void println(con...
v2 in void append(const vector<int>& v1, vector<int> v2) is a copy of what is passed, so modifying it won't affect what is passed. You should use reference (add &) to have the function modify what is passed. void append(const vector<int>& v1, vector<int>& v2) // add & before v2 { for (int x : v1) v2.push_ba...
64,267,460
64,267,593
OpenGL: is there a way to keep only the max value between source and destination?
Let's say I have a pixel value of 100 (out of 255, 1 channel) in a framebuffer, and try to write 80 to it. I would like to keep 100. But if I try to write 120 to that same pixel, I'd want to write 120 to it. dest = max(dest, src) Is there a way this can be done in a single pass, perhaps with a blend function or fragm...
Yes, you are looking for glBlendEquation(GL_MAX).
64,267,575
64,267,614
Float Point Number Rounding with round and pow functions
I am trying to write a program that rounds a number to a certain decimal place that was specified by the user. It is a requirement to do this with both cout.fset and cout.precision, as well as with round and pow functions. In the end, the output of the program should be something like this: 123.4567 2 123.46 123.46 My...
d in the rounding function is not initialized and have indeterminate value. Try this: #include <iostream> #include <math.h> using namespace std; double rounding(double d, int pp){ double k = std::pow(10, pp); return std::round(d * k) / k; } int main(){ double p; double d, round; cin >> ...
64,267,980
64,268,199
Advantages on flattening to 1D
I have questions about the flattening operation I see on forums. People often recommend flattening a multi-dimensional vector, or array to a single dimension one. For example: int height = 10; int width = 10; std::vector<int> grid; for(int i = 0; i < height; i++){ for(int j = 0; j < width; j++){ grid.push_b...
I can think of multiple reasons to do this, in no particular order and there might be more that I missed: Slightly less memory use: each vector takes 24 bytes*, if you have 1000 rows, it's 24K more memory. Not that important, but it's there. Fewer allocations: Again, not very important, but allocations can be slow, an...
64,268,288
64,268,443
std::string as out parameter or return value
Which is the correct way to get an std::string value from a function. The assumption here is that I am writing the function and the caller. std::string foo() { std::string str = "ABC"; return str; } OR void foo(std::string &str) { str = "ABC"; } I understand that in the first method compiler optimizatio...
As said in the comments, using a return by value seems to be preferred nowadays. I find my code to be more readable that way, in that you can see that there is actually a change. With the out parameter foo(str) it's not obvious that str is being changed. I believe all mainstream compilers are clever enough to optimize ...
64,268,826
64,268,955
What's correct format and how organize bytes correctly in a .bin file to set in a char array[]?
Imagine that following byte array contains all bytes of a executable file (.exe) (that on pratice this not is possible set inside source code because there are much bytes in this file type (.exe) and Visual Studio will crashe) char buffer[] = { 0x60, 0x33, 0xC0, 0x33, 0xDB, 0xEB, 0x00, 0x03, 0xC3 }; Then i think that ...
You don't format at all, just write raw bytes. You are reading raw bytes using infile.read(&buffer[0], file_size_in_byte); Similarly, open your output file with ios::binary and simply call outfile.write(&buffer[0], some_number_of_bytes);
64,268,911
64,269,022
Problem with Memory Allocation while Using Threads
I am attempting to use with a structure that uses data allocation. Despite getting the correct outputs within each function, I am getting an overflow error when these functions are ran through a thread. The current code I have is: #include <iostream> // cout, endl #include <thread> // thread using namespace std; //...
You're printing addresses of the values (&avg_v is a pointer to avg_v, which when printed as %d, will print a part of the value of the pointer itself). To print the double values themselves, simply do printf ("The average value is %lf\n", avg_v); printf ("The minimum value is %lf\n", min_v); printf ("The ma...
64,269,137
64,269,182
Im trying to put elements into a multidimensional array
I'm doing a task on codewars and I'm almost done but i get an error with my answer vector. What I want to do here is to put the value of i and sum into a multidimensional array (an array of arrays) if (sum == x*x ){ answer.push_back(i, sum); } But it just throws out an error...
Type of result array (vector) and return type should be matched. You declared an array of vector, but you will need only one array. std::vector don't have push_back that take 2 arguments. You should make pairs to put. You don't need ; after function definition. There is an extra }; after the function definition. Value...
64,269,454
64,269,455
How to install and debug older Qt versions in newer Qt and QtCreator?
When I updated from Qt 5.6 to 5.12, I had to revert one of the projects that I was working to Qt 5.6, and turned out that the two Qt installations where messing with each other. Unfortunately, Qt 5.12 installer does not provide an option to install 5.6 anymore. So I decided to move the Qt 5.6 SDK to inside the Qt folde...
After spending many hours trying to find a workaround, what solved the issue was: Rename the current Qt installation folder (with Qt 5.12 inside) to something else (e.g. from ~/Qt to ~/Qt_); Install the 5.6 version (I got it from here) to the same directory where 5.12 was installed (in my case ~/Qt). During the instal...
64,269,991
64,270,039
Issues with rand and srand
I'm making a program to get the average number of dice rolls to get a 6, but there seems to be an issue with the RNG. I suspect it's the seed, as while the number is different each time I compile and run the code, it doesn't change in each individual attempt, so the average doesn't change. Heres my code: #include <iost...
Notice that roll only gets updated inside this loop: while (roll != 6) { ... } This means that after that loop finishes running with roll set to 6, it will never run again, even if the outer loop executes another time. To fix this, you could either change this to be a do ... while loop so that it always executes a...
64,270,241
64,270,294
BST in c++, return true or false when adding node
I'm learning C++ right now. I want to set the return type of the add function in BST as bool, where it returns true if there is already a same item in the tree, and return false when it has been added to the tree. Here is code, any suggestions on how to achieve this goal? Code in the node class(.h file): node* insert(s...
Easiest approach is to do a search that identifies the parent node to insert at. I could show you tuples, but it's easier for now to just have an out parameter to indicate if the condition of "value already in tree" is an out parameter. node* makeNode(const string& content) { node* n = new node(); n->le...
64,270,242
64,271,589
Is there a way to create a QImage that scrolls infintely?
I'm working on creating this game using QT : https://www.friv.com/z/games/killcovid19/game.html?Desktop-x-x-w-x-x-xx When playing the game, you could see the red background scrolling infintely through the game. I was thinking of creating a QT image that does this but I'm not sure how. Is there a way for this to work us...
The simplest approach I can think about is to create an image bigger than the viewport (say, twice its hight) with a repeating pattern. Start scrolling it and when it reaches the end, start scrolling from the beginning. Widget::Widget(QWidget *parent) : QWidget(parent) , m_background("pattern2.jpg") , m_tim...
64,270,626
64,272,730
Turning a function call which takes a callback into a coroutine
I am exploring and trying to learn C++ Coroutines (added in C++20). An SDK I am using has asynchronous API calls which all take a callback, the callbacks are invoked on some background thread managed by the SDK. namespace third_party { bool api_call(const std::string& some_parameter, const std::function<void(std::err...
There's a really good article by Raymond Chen, you can find it here. In your case, you can do something like this. namespace my_third_party_async_sdk_wrapper { auto api_call_async(const std::string& some_parameter) { struct awaiter : public std::experimental::suspend_always { ...
64,270,697
64,306,998
Reverse C++ vector<char>
I am not that great in C++. Question is a simple reverse string. This is a Leetcode question and I am trying to solve it recursively. void reverse_str(vector<char>& s, int len) { if (len <= 1) return; swap(s[0], s[len-1]); reverse_str(s.front(), len-2); // Compilation error when I call s.front() } v...
You can do that in this way void reverse_str(vector<char>& s, int len = 0) // default params with zero { int n = s.size(); if (len == n / 2) return; // swap last with first upto n/2 swap(s[len ], s[n - len - 1]); reverse_str(s, len + 1); } void reverseString(vector<char>& s) { reve...
64,270,983
64,271,279
c++ lambda auto type deduction
I'm trying to understand why this piece of code will not compile: void test_fff() { auto f1 = [](int x) {return x;}; decltype(f1) f2 = [](int y) {return y;}; } This is the compile error I'm getting: error: conversion from 'test_fff()::<lambda(int)>' to non-scalar type 'test_fff()::<lambda(int)>' requested 177...
What's the difference between the two? The difference between the two is that in the first case: auto f1 = [](int x) {return x;}; decltype(f1) f2 = [](int y) {return y;}; The type of f1 (and thus of decltype(f1), so the type of f2) is the type of the first lambda and, taking into account that every lambda is of diff...
64,271,039
64,273,069
Is there a more efficient way to wrap a float?
I've been looking for examples on how to wrap a float between two numbers, similar to how you can do with integers using modulus. Examples I've found either involve using fmod to just find the remainder past the decimal point, assuming it's for a circle and doing pi-based math, among other things that didn't quite do w...
Is there a more efficient way to wrap a float? Use the fmod() family. #include <float.h> float fwrap_alternate(float x, float min, float max) { if (min > max) return fwrap_alternative(x, max, min); return (x >= 0 ? min : max) + fmodf(x, max - min); }
64,271,208
64,271,269
Does this coding style belong to an older version of C++?
I come across this code in my older books. I tried to run it in Visual Studio 2019, but it gave me an error: volume function does not take zero arguments Is this because the code is old, or the code is wrong? #include<iostream> using namespace std; class Cylinder { private: const double pi = 3.14; double r,...
The code is wrong. The volume function is declared to take two double arguments and the C++ compiler expects it to be called that way. I'm not aware of any C++ compiler of any age that would accept that code. It looks like maybe the function is trying to use the member variables r and h, in which case you should probab...
64,271,214
64,277,220
is there a way to set an "unknown" variable like "x" inside a sine-equation, and change its value afterwards?
I want to write an audio code in c++ for my microcontroller-based synthesizer which should allow me to generate a sampled square wave signal using the Fourier Series equation. My question in general is: is there a way to set an "unknown" variable like "x" inside a sine-equation, and change its value afterwards? What do...
So since I can't use vectors inside Arduino IDE anyhow I've tried the following solution: ... void ComputeBandlimitedSquareWave(int mHarmonics){ for(int i = 0; i < sample_count; i++){ mWavetable[i] = ComputeFourierSeriesSquare(x); if (x < sample_count) x++; } } float ComputeFourierSeriesS...
64,271,461
64,272,133
Trouble to access attributes by using glVertexArrayAttribFormat / glVertexArrayVertexBuffer
I have this code : Upp::Vector<float> verticesTriangle{ 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, }; glGenVertexArrays(1, &VAO); glBindVertexA...
You're putting stuff in the wrong place. glVertexArrayAttribFormat(VAO, 1, 2, GL_FLOAT, GL_FALSE, 3); //Will be texture coordinates The "3" here is being passed as a byte offset from the start of a vertex in the array to the particular data for that vertex in the attribute. Obviously, your texture coordinate is not ...
64,271,841
64,299,975
Unknown CMake command "add_clang_executable"
I am trying to build a clang tool, and I am trying to debug it using CLion. However, I can't get it to compile as a standalone binary. Currently I have this in my CMakeLists.txt: add_clang_executable(clang_my_tool my_tool_util.h my_tool_util.cpp ClangMyTool.cpp) target_link_libraries(clang_my_tool PRIVATE clangTooling...
You need to include the LLVM CMakeLists.txt file which defines add_clang_executable(). Currently that file is here (and may well already be installed on your system): https://github.com/llvm/llvm-project/blob/master/clang/cmake/modules/AddClang.cmake If you figure out the path to that file on your system, add this to ...
64,272,343
64,281,833
C++ FIX Implementation --> Invalid user for session. Username and SenderCompId must match
Im developing a bot in c++ using QuickFix, when I send a Logon message I get a logout response saying "Invalid user for session. Username and SenderCompId must match" This is my message: 8=FIXT.1.1|9=113|35=A|34=1|49=REM4820|52=20201008-22:22:59.886|56=ROFX|553=User|554=pass|98=0|108=30|141=Y|1137=9|10=054| (User and ...
This is definitely a counterparty-specific-logic problem, and not a FIX protocol problem. Let's get extremely literal: Username and SenderCompId must match. Going by that message alone, it seems pretty clear that tag 49 (SenderCompID) and tag 553 (Username) must have the same value. Did they? I'm guessing they didn'...
64,272,794
64,272,861
Why does my template specialisation need to match the originals constraint?
For example, in this code: #include <iostream> #include <type_traits> template<typename T> requires std::is_same_v<T,int> || std::is_same_v<T,float> || std::is_same_v<T,double> bool foo(const T& value) { return true; } template<> bool foo<double>(const double& value) { return false; } int main() { std::...
An explicit specialization of a template is defined relative to a primary template. Specializations cannot exist without a primary template. They are an alternative to that primary template. During template instantiation, if a set of template arguments fail the constraint tests, then instantiating that template fails. ...
64,272,920
64,273,099
What are the rules for namespace search for qualified names?
Can someone explain the behavior I am seeing for namespace search for qualified names in the following example code? See inline comments for the issue. namespace ns1::hw { struct A1 { enum class E1 { E1_1, E1_2, }; }; }; namespace ns1::ns2::hw { struct A2 { enum class E1 { E...
In your first snippet: int I1 { (int)hw::A3::E1::E1_1 }; // <--- this compiles OK // seems to search upwards in the parent namespace, // looking for the relative partially qualified // name. as you seem to...
64,272,952
64,273,203
Prime example of pthreads / fork / and execvp?
I'm looking for a working example of using fork() within a newly created pthread, where the child runs a process using execvp() & the parent thread waits for the child. The program must close without memory leaks. I am close to a solution myself however I've run into a memory leak (valgrind) because the child process l...
I resolved the memory leak after some time searching through possible causes. I found the issue was execvp was returning -1 indicating the command wasn't being called correctly and therefore not replacing the child process stack correctly. After ensuring the correct command was passed the leak was resolved.
64,273,056
64,273,148
Why and when to use clear()
According to this clear() will destroy all the objects, but will not free the memory. Also while I encountered the necessity of removing all elements of a set I found out that the time complexity of set.clear() is linear in size (destructions) whereas constant for set.swap(). (same problem while removing all elements o...
when to use clear() When you want to remove all elements of a container. why use clear() Because it is the clearest and most efficient way to achieve the above. clear() will destroy all the objects, but will not free the memory. This is a desirable feature. It allows clear to be fast, and allows addition of new e...
64,273,172
64,273,483
C++ Parent class Sub class , working with vector
C++ Hi, so basically I made an Animal Parent class and have Mouse as one of my SubClass. The Mouse has a unique function (not in the parent class) get_scare : void get_scare() In main, I created a vector of Animal Object: vector<Animal> list_animal My problem is after Identifying that the subclass mouse is at index i...
First of all, you cannot declare vector<Animal> and store a subclass object in it - this is a bug. For example, if you have vector<Animal> list_animal(1); list_animal[0] = Mouse{}; then any data members of Mouse that are not in Animal are thrown away - this is called slicing. But maybe that was just a typo in your que...
64,273,386
64,273,839
Incorrect rounding on gcc and Ubuntu
I am currently porting some codes from Windows to Linux (Ubuntu) from a MS VS2008 compiler to GCC. The problem is that the following code has different results: double d = 19.53125; std::cout.precision(4); std::cout.setf(std::ios::fixed); std::cout << d << std::endl; Windows output: 19.5313 Linux output: 1...
Bankers Rounding is an algorithm for rounding quantities to integers, in which numbers which are equidistant from the two nearest integers are rounded to the nearest even integer. Thus, 0.5 rounds down to 0; 1.5 rounds up to 2. GCC C++ standard library applies the Bankers Rounding. 19.53125 -> 19.5312, since 2 is the n...
64,273,877
64,274,639
Program execution not stopping at scanf() after first read
I want that at every iteration of the do-while() loop the program stops at the scanf() function, but the program loops the same amount of times as the number of white spaces that the read string contains before stoping again at the scanf() enum Comando { AYUDA, LOGIN, LOGOUT, LISTAR_BUSES, LISTAR_RU...
Here I am posting a proper C++ implementation of your code. I know that code-only answers are not recommended. But here, I don't have much to tell you. You need to yourself check about the things you lack knowledge about. Better search things on this site. #include <algorithm> #include <iostream> #include <queue> #incl...
64,274,156
64,275,124
operator-> for an iterator that returns a temporary
I have a data structure that is essentially a hash table. The keys and values are stored separately for cache reasons. I have an iterator that traverses the container and returns pairs of keys and values when dereferenced. However, I'm having a bit of trouble getting the iterator to behave like others. In particular wi...
If you can't return a pointer from the operator->, return a helper class by value. Make that class store a KeyValuePair and overload its operator-> to return a pointer to the pair. My answer uses the same idea as RedFog's one, but I tried to make the code less convoluted. struct Iterator { KeyValuePair operator*() ...
64,274,305
64,276,346
How Hide/Protect resource files against extractors?
I have a executable file as resource of my main program, there's some way to Hide/protect my resource file against extractors like Resource Hacker, Resource Tuner between others?
You can't do this. There is no way. There is a question that could be useful.
64,274,623
64,274,728
The object a pointer is pointing to changes values every time a get function is called? C++
I have two classes, one for fuel and the other for miles. Every 24 miles you use 1 fuel. For this assignment I am required to have a pointer in my "miles" class to point to a "fuel" class so we can have "mile" class work with the "fuel" class without having to create a whole object "fuel" object inside the "mile" class...
This should be undefined behavior right here. Odometer::Odometer(int currMileage, FuelGauge Gauge) { if (currMileage >= 0 && currMileage <= maxMilage) { currentMiles = currMileage; } else { cout << "Starting mileage is invalid" << endl; } fuelObject = &Gauge; } Once your constructo...
64,275,038
64,275,459
How to use atomic variable as a mutex in C++?
I have a program where 4 threads are running concurrently withdraw / deposit operations on a "bank account" I am supposed to synchronize threads with atomics (school task). Im using currently compare_exchange and it works on deposit (addition) because it does not matter when addition is done. However there is a problem...
Is this what you want? class Account { public: Account(double balance) : m_balance(balance) { } void Deposit(double amount) { double old_amount, new_amount; do { old_amount = m_balance.load(); new_amount = old_amount + amount; } while (!m_bal...
64,275,387
64,278,647
How to make a QStandardItemModel from QStringList of file paths
i'm new to C++ and Qt and can't seem to find the right solution for this. I want to create a QTreeView using a QStandardItemModel. I have a list of file/folder paths (within a QStringList) structured in a format like this: Arena/Main/00078/a.txt Arena/Main/00080/b.txt Arena/Main/00080/collision/c.txt Arena/Main/00080/l...
You can store the created paths in a map like this: mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QMap> #include <QStandardItemModel> class QStandardItem; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow...
64,275,733
64,282,715
Access checking rules for template argument list in (particularly explicit) specializations
All standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS. Consider the following class template A and class B which private defines a nested class C and enum class E: template<typename T, typename U> class A {}; class B { class C {}; enum class E {}; }; According to [temp....
The rule here was changed shortly after C++17 was finished by P0692, replacing what was then [temp.explicit]/14 with what is [temp.class.spec]/10 (for partial specializations) and [temp.spec]/6 (for explicit specializations and instantiations) in C++20. The paper mentions that it was (largely) standardizing existing p...
64,275,924
64,276,409
Find largest number formed with numbers of an array
The task is to find the largest number formed with the numbers of an array. For example: input: 7, 56, 94, 1 output: 947561 In the code, I compare ab and ba, and then sort the numbers using bubble sort. My code works for 80% test cases, but I cannot find the mistake. Where or which case haven't I taken into account? Th...
The greedy approach works fine with your question. Sort the numbers according to the first different digit. Combine them (in descending order) here is the implementation in C# (syntaxes are similar) Note: you can use string for large datasets, numbers works for small datasets. and also consider using a faster algorit...
64,276,550
64,276,755
What can the reason be for making use of this strange namespace trick?
Why would I want to write something like this and fill // STUFF with stuff? // boost namespace another_name {} namespace boost = another_name; namespace another_name { // STUFF }
This is just a regular namespace definition followed by a namespace alias definition aliasing the former. // Namespace definition of namespace 'another_name'. namespace another_name {} // Namespace alias definition, 'boost' aliases 'another_name'. namespace boost = another_name; // Namespace (re-)definition: open u...
64,277,349
64,277,478
Loop over constexpr array
I have the following files: test.hpp class Test { static constexpr const char* array[] { "hello", "world", "!" }; public: void do_stuff(); }; test.cpp void Test::do_stuff() { for(int i = 0; i < 3; ++i) { std::cout << array[i]; } } int main() { Test object; obj...
static members need an offline declaration or explicit inline: From C++17: inline static constexpr const char* array[] { Other solution: #include <iostream> class Test { static constexpr const char* array[] { "hello", "world", "!" }; public: void do_stuff(); }; constexpr...
64,277,401
64,278,108
How to prevent critical section access with atomics in C++
I have a program where 4 threads are doing random transactions between two "bank accounts", at every 100th transaction per account interest of 5% should be added to the account. This is an exercise for school I have to do, and in the previous lesson, we used mutexes which seemed very straightforward in locking a sectio...
One problem is that you increment and read counter separately, and because of this addInterest can be called multiple times. To fix this, you should write and read atomically. const int newCounter = ++m_iCounter; Adding interest: If it doesn't matter when you add interest, as long as it happens after incrementing the ...
64,277,521
64,285,902
Explanation for GCC compiler optimisation's adverse performance effect?
Please note: this question is neither about code quality, and ways to improve the code, nor about the (in)significance of the runtime differences. It is about GCC and why which compiler optimisation costs performance. The program The following code counts the number of Fibonacci primes up to m: int main() { unsigned ...
The important thing at play here are loop-carried data dependencies. Look at machine code of the slow variant of the innermost loop. I'm showing -O2 assembly here, -O1 is less optimized, but has similar data dependencies overall: .L4: xorl %edx, %edx movl %esi, %eax divl %ecx te...
64,277,558
64,281,072
Can I access different template class object via a same pointer?
I am trying to access the data_ member of NDArray class via the getData() member function. typedef void * datahandle_t; enum class typeFlag { kFloat32 = 0, kFloat64 = 1, kUint8 = 2 }; class NDArray{ private: typeFlag dtype_; size_t size_; datahandle_t data_; public: // constr...
you can use std::variant directly, after C++17. if you can't use that or just want to define another one, refer to tagged union.
64,277,989
64,280,002
Why the gs segment register is address is set to 0x0000000000000000 on visual studio x64(MASM)?
I am currently reading "The Ultimate Anti Debugging Reference" and I am trying to implement some of the techniques. To check the Value of the NtglobalFlag they use this code - push 60h pop rsi gs:lodsq ;Process Environment Block mov al, [rsi*2+rax-14h] ;NtGlobalFlag and al, 70h cmp al, 70h je being_debugged I d...
So I still don't understand why the code posted here caused so many problems, As I said I just copied it from "The “Ultimate”Anti-Debugging Reference" push 60h pop rsi gs:lodsq ;Process Environment Block mov al, [rsi*2+rax-14h] ;NtGlobalFlag and al, 70h cmp al, 70h je being_debugged But I've found a simpler sol...
64,278,096
64,284,741
Template specialization with Parameter Packs
I'm quite new to c++ but wanted to try to do some fancy template stuff. I am not sure if it is possible, but I am fairly confident there is a way to achieve that. So here's the Issue: I am calling various Hardware function, which requires a number of parameters and only differ by one parameter type: int Read(HANDLE han...
You can write a type that creates a nested vector of the desired rank, like this: template<typename T,int N> struct VT { using type = typename std::vector<typename VT<T, N - 1>::type>; }; template<typename T> struct VT<T, 0> { using type = int; }; and then write a single function like this: template<typ...
64,278,450
64,279,777
How many pixels do items in QComboBox need?
I would like to know how many pixels need this items in QComboBox: red - checkbox green - distance between end of checkbox and beggining of the text blue - distance between end of border and beggining of the checkbox In doc of QStyle I find two methods: subElementRect() pixelMetric() I think I have to use them, but...
It depends on the style. QCommonStyle for example draws the ComboBox's label like this: if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) { QRect editRect = proxy()->subControlRect(CC_ComboBox, cb, SC_ComboBoxEditField, widget); p->save(); p->setClipRect(editRect); ...
64,278,705
64,279,095
Template parameter deduction problem with C++ concepts and `std::is_same`
If I try to write a function that is restricted by a concept to either std::map and std::unordered_map with Key keys and Element elements it fails to deduce the Key type in the following piece of code. template<typename A, typename B> concept is_same_as = std::is_same<A, B>::value; template<typename T, typename Key, t...
Your map_type_of concept doesn't help you over a simpler concept template<typename T> concept is_map = std::ranges::range<T> && std::semiregular<typename T::key_type> && std::semiregular<typename T::mapped_type>; template <typename T> requires is_map<T> inline std::list<typename T::key_ty...
64,279,056
64,279,207
.Can there be a easier function defining - (to.string()) below
// The function which i was required to make was to.string() in the class,Which i had no idea how to make.This is an odd function(not comparing with the math one.)which returns value in two different types of data types i.e(string,integer).The only thing stuck me was assigning a variable after making (string to.string(...
If you want to create a string with the format age, first_name, last_name, standard then you could do something like class Student { public: ... std::string to_string() const; ... }; std::string Student::to_string() const { return std::to_string(get_age()) + ", " + get_first_name() + ", " ...
64,279,064
64,279,224
call the default constructor for the pointer of class as a value of map in c++
Here is my class struct Node { int val; vector<Node*> children; Node() :val(0), children({}){}; Node(int _val) :val(_val) {}; }; And I build a map map<int,Node*> dict; I know that the pointer object will not call for the constructor of class, so if the key i does not exist in map, we are not allowed ...
No, there is no way to make value initialised pointer to be a valid pointer to object, and that is what you will always get for objects created by std::map::operator[]. Such pointer is always null. Instead of storing a pointer to node, you could store the node itself in the map element. The syntax of accessing the elem...
64,279,384
64,279,480
How to read in binary mode and transfer the information to new file
i tried to open and read an application in binary mode and get 100 characters(For a large file, i did this so that i could read all the characters) in binary mode and then transfer them to new file(in fact, this program will be the same as the previous program, but with a different name ) to find out if it works proper...
The line output.write(ch.data(), sizeof(100)); should be replaced with output.write(ch.data(), count); Since sizeof(100) only returns 4, which is the size in bytes of an integer. You should also remove the line ch[file.gcount()] = '\0'; since file.gcount() might be out of bound. I just tested it and this works for me #...
64,279,523
66,096,062
CreateProcess windows API stores excel in Documents folder
I am working on a legacy application which calls CreateProcess method method1() { BOOL bResult = ::CreateProcess( NULL, // LPCTSTR wctAppPath, // LPTSTR lpszCommandLine NULL, // LPSECURITY_ATTRIBUTES lpsaProc NULL, // LPS...
Legacy application is CATIA. In V5, CATScriptUtilities::ExecuteScript is used to call catvba. In V6, we can use the same API to call catvba. It works fine. There is no need to call .bat->.vba->.catvba
64,279,734
64,280,605
How set std::string type on lldb?
I have the following code: #include <iostream> #include <string> int main() { std::string name = "Foo"; return 0; } When i will debug with lldb i want set a std::string like i set this int: expr int $num = 4 I try: expr std::string $name = "Foo" And i got: error: no type named 'string' in namespace 'std' Doe...
You can use alternatively: expr const char * $foo expr const char $foo[] expr const char $foo[4] Obviously the last one can be used only if you know the dimension of the char-array
64,279,834
64,280,022
using a range-based for-loop to iterate through a list of pointers
Good day everyone, I have been trying the following code to reset all pointers in a list to nullptr as shown below: for (auto item : { ptr1, ptr2, ptr3 }) item = nullptr; the problem is that a copy of the pointer is made to item, so the original ptrs are unequal to nullptr at the end. I would like to get s...
I would like to get some sort of reference You're creating a std::initializer_list with that braced init list. Unfortunately, such list always contains copies and you cannot assign to the variables used to initialise it through that list. You could use reference wrappers: for (auto ref : { std::ref(ptr1), std::ref(pt...
64,279,978
64,280,044
Inheriting from standard library containers results in slicing
I came across an old SO post about inheriting from std::vector. One of the comments made was unclear to me, why does slicing occur when you inherit from a standard library container and use a pointer/reference to the base? Godbolt #include <vector> #include <iostream> using namespace std; class MyVec : public vector<...
Standard library containers have no virtual methods and also no virtual destructor. They completely lack a vtable. Your code fails to test what you want to test.
64,280,354
64,281,235
How to append a text to the end of the file after searching for specific line in c++?
I have a file from which i have to find get the first word and the second word in line, by searching from line to line, then append a text( variable list_of_names) to the end of the line that we found. I have the following code, but it appends a text to the end of the file, and not on the specific line string line;...
This below creates a new file on output (course_students_output.csv) that you can rename afterwards. string line; string courseid, course_section; cout<<"What is a courseID: "; cin>>courseid; cout<<"What is the course section: "; cin>>course_section; //string first; ifstream file("cour...
64,280,889
64,281,014
RegisterHotKey() causes error 1459 (This operation requires an interactive window station) in a service
I've read several similar threads on SO that discuss starting another process and registering a hot key in that child process, but my situation is slightly different. I'm building a Windows service that performs many varied functions, and would like to keep it as a service since I need my code to run on system start up...
Code that interacts with an interactive desktop will need to run in that interactive desktop. Your service runs in isolation in session 0. You will have to separate out those parts of the system that are interactive and run them in an interactive process. You can retain the service to manage these interactive processes...
64,280,925
64,281,037
Passing function reference into template warning: ignoring attributes on template argument 'func signature'
I am trying to create a composite logger which will be selected and defined at compile time. The original implementation is using inheritance and VTable, which is causing some overhead, takes too much code and is ineffective at runtime. This is supposed to be simplification, which accepts basically any stream defined i...
If you check your system header files for the declaration of the syslog function, you will see something akin to the following: extern void syslog (int __pri, const char *__fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3))); Under normal usage, this attribute serves to match the format string against the a...
64,280,975
64,285,429
ImmGetContext returns zero always
I want to make Korean key logger. To do that, I need to check IME mode of the current(foreground) window. I tried to implement this using the ImmGetContext function, but ImmGetContext(GetForegroundWindow()) returns zero always. How can I fix this problem? #include <iostream> #include <stdio.h> #include <Windows.h> #inc...
#include <iostream> #include <Windows.h> #pragma comment (lib, "imm32.lib") #define IMC_GETOPENSTATUS 0x0005 using namespace std; int main() { while (true) { HWND hIME = ImmGetDefaultIMEWnd(GetForegroundWindow()); LRESULT status = SendMessage(hIME, WM_IME_CONTROL, IMC_GETOPENSTATUS, 0); cou...
64,281,644
64,284,806
Regex in C++ with back-references and conditionals
I am trying to match words with optional curly brackets around them. I.e. something like "{word}" or "word". I want to implement it using conditional expressions. ({)?(word)(?(1)?}|) where: ({)? optional 1st group (word) mandatory word (?(1)}|) if-then-else condition, if the first group was found, it matches t...
The default ECMAScript regex flavor used by std::regex (and all other, mostly, POSIX flavors) do not support the conditional construct. The pattern you have in your code snippet will work in Boost. Judging by your examples, your regex should look like (\{)?(word)(?(1)\}|).
64,281,680
64,282,324
error: no template named 'enable_if_t' in namespace 'std'; did you mean 'enable_if'?
I'm compiling with Qt 5.11.3 on macOS 10.13.6. The clang version used by Qt is: $ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -v Apple LLVM version 9.1.0 (clang-902.0.39.2) Target: x86_64-apple-darwin17.7.0 Thread model: posix InstalledDir: /Applications/Xcode.app/Cont...
The template alias enable_if_t is not available in C++11; it was added in C++14, as were most of the other type trait *_t versions (C++17 added *_v versions for boolean traits as inline constexpr variables).
64,281,889
64,281,900
Size of array in C/C++
Consider the following code: int main(){ int arr[] = {1,2,3,7,8}; int size = sizeof(arr); cout << size; } I know that the above code will print the size of the array which is 4*5 = 20 bytes but i have a small doubt in this, arr is a pointer to the first element in the array and the size of a ptr variable i...
sizeof(arr) is one of those instances where arr does not decay to a pointer type. You can force pointer decay by using the unary plus operator: std::size_t/*a better type*/ size = sizeof(+arr);
64,282,046
64,282,135
SCTP recvmsg returns EFAULT (Bad Address)
I'm trying to build a very simple and basic STCP one-to-many server for testing purposes, but for some reason, the socket seems to be able to receive only one message. After receiving one message, each subsequent call to recvmsg returns -1 with the errno being EFAULT. This makes absolutely no sense to me, so maybe you ...
The error is most likely because the first call to recvmsg() overwrites some data on the stack, causing one of the pointers inside mhdr to be invalid. And this is probably because of this line: mhdr.msg_iovlen = sizeof(iov); This should not contain the size of the array iov in bytes, but just the number of elements in...
64,282,233
64,283,952
Auto-resize columns of QTableView programmatically
I have a QTableView in my programm which I want to resize automatically. I used the functions headerViewHorizontal->setSectionResizeMode(QHeaderView::ResizeToContents); headerViewHorizontal->setSectionResizeMode(3, QHeaderView::Stretch); to resize it and it works for when I resize the window. But then I need to insert...
Thanks to @Scheff, my question is answered. The solution is to use resizeColumnToContent() to one of the columns which has not the stretch resize mode. Each other will be updated. Edit : This solution works only when the column on which you call resizeColumnToContent() has to change its width. Otherwise you have to cal...
64,282,322
64,282,521
shared_ptr does not destruct the object at the end of the program
I'm trying to implement a Deque using smart pointers. However, I noticed that at the end of the program the Nodes of the Deque are not destructed properly. Here is the code: #include<iostream> #include<memory> class Node { int value; std::shared_ptr<Node> next = nullptr; std::shared_ptr<Node> prev = nullptr; p...
I assume the problem is that the reference count of node1 and node2 is equal to 3. Your assumption is correct. Shared pointers do not destroy the pointed object until ref count drops to zero. Do you know how I can change my implementation in order to solve this problem? Don't have cycles in your ownership graph. Yo...
64,282,845
64,282,950
Duplicate nodes with positive value in Linked List (C++)
struct Node { int data; Node* next; }; struct List { Node* first; }; void duplicatePositiveNodes(List* list) { Node* current = new Node(); Node* tmp = new Node(); current = list->first; while (current != nullptr) { if (current->data > 0) { tmp->data = current->data; ...
There are a number of issues in your code. Stepping through it with a debugger is a good way to figure out where your code is not doing what you expect. Here's a simple way to duplicate the nodes, as needed: void duplicatePositiveNodes(List* list) { for(auto current = list->first; current; current = current-> next) ...
64,282,968
64,283,002
What does this template parameter mean?
For the following code, what does std::uint64_t = 0 mean? template< class T, std::uint64_t = 0 > struct Dummy { T value; };
It's a non-type template parameter of type std::uint64_t with a default value of 0. Note that the parameter is unnamed, so you can't use it directly in Dummy. However, there are still several uses for this template parameter, e.g. you can use a different value for this parameter to select specializations of Dummy: // s...
64,283,057
64,283,152
glDeleteTextures gives error E0167 (argument of type is incompatible with parameter of type)
I wrote glDeleteTextures(1, &LocalBuffer); and it said: E0167 argument of type "unsigned char *" is incompatible with parameter of type "const GLuint *" It is line 52. I tried: Passing it as LocalBuffer CODE: class Texture { private: unsigned int TextID; std::string FilePath; unsigned char* LocalBuffer;...
You delete texture names, not texture data. Specifically, whatever you glGenTextures, you have to later glDeleteTextures later. glGenTextures(1, &TextID); glDeleteTextures(1, &TexID); I was about to say that you can free your image data immediately after uploading it for DMA transfer to the graphics card (glTexImage2D...
64,283,118
64,283,288
Parameter values messed up when calling native functions from .Net
Right now I have a c++ DLL project, which I use for a wrapper for a lower-level functionality in .Net. C++ code: string testA(uint a) { cout << a; return "egrt"; } bool testB(uint a) { cout << a; return false; } C++ header: #pragma once #ifdef API_EXPORTS #define API __declspec(dllexport) #else #defin...
The default calling convention for DllImport is stdcall, but the default calling convention in C/C++ is usually cdecl instead. The symptom you describe can easily be caused by a calling convention mismatch between the two languages, so make sure both sets of code agree on which calling convention to use. Also, you can...
64,283,192
64,286,669
Methods to further reduce time complexity of this algorithm for Longest Palindromic Substring problem
first time poster here so apologies if there are any issues with my post/question. Please let me know so I can adjust. I'm looking for some help on further improving my solution for the Longest Palindromic Substring found on LeetCode, as it always goes TLE during submission. I think the algo is correct and is around O(...
Your solution seems to be O(n^3) in the worst case. You could use DP and store the previously calculated palindromes in a table. Fill the table in increasing order of substring lengths. A string is a palindrome if the first and last characters are the same and the string with its first and last characters stripped was ...
64,283,475
64,283,876
Output wstringstream by blocks issue
I have some issue with reading wstringstream data. Code like this: #include <iostream> #include <sstream> int main(int argc, char* argv[]) { std::wstringstream buf(L"dsadsadsad dsadsadsad sadsadsadsad sa dsadsadsads dasdsadsa"); wchar_t sendbuf[5]; wmemset(sendbuf, 0, 5); while (buf.read(sendbuf, 5)) ...
The std::wostream::operator<< takes a wchar_t* parameter, so it can't know the length of your buffer. You need an extra space in your buffer for the terminating zero. int main(int argc, char* argv[]) { std::wstringstream buf(L"dsadsadsad dsadsadsad sadsadsadsad sa dsadsadsads dasdsadsa"); wchar_t sendbuf[6]; ...
64,283,821
64,284,632
(C++) Why is my program not outputting average wait time and average time over 1 hour?
This is a program that simulates a line for a teacher's office hours using queues. It generates a random number of students gives them each a random amount of time spent in the office, and adds them to the queue. It is also supposed to calculate the average time each student spent waiting, and whether the office hours ...
You use difftime many times between time variables set to time(0): they end up assuming the same value because they get initialised almost at the same time. Hence I have added rand() terms to them; pick these values more accurately if you wish. Also, inside the while-loop, I have changed the s student items to be point...
64,283,841
64,285,635
Code not running - C++ - exam training tests
I have this very exercise which requires me to use a function named shift, which gets two parameters, one named n, number of items, and an array x, maximum 100 elements, therefor this function moves the array's items one by one. Then I need to inverse the array calling this function. I don't get why my code doesn't wor...
Shift sounds like a primitive rotate, so let's implement that void shift (int arr[], int elements){ int holder = arr[0]; for(int i = 0; i != elements-1; i++){ arr[i] = arr[i+1]; } arr[elements - 1] = holder; } If you take the numbers {1,2,3} and run them through, you should have either {3,1,2} ...
64,283,934
64,284,215
Using -( archives -) gcc commands
In compiling a DLL, I've been running into a lot of undefined reference errors, which I think may be caused by circular dependencies between libraries. To fix this, I've been trying to use the -( archives -) and --start-group archives --end-group options: gcc -Wall -shared Pipeline.cpp -I"C:/Python38/include" -I"C:/Pro...
--start-group and --end-group (and the short forms, -( and -)) are linker options. You'll need -Wl to use them from the compiler driver gcc, so that it passes them through to the linker rather than trying to understand them itself (which it can't, because it doesn't have any such switches). So: -Wl,--start-group -Wl,--...
64,284,649
64,284,798
What's the preferred way to instantiate one class in another?
Pretty basic question. Has to do with design preference but I think there are some caveats that I'm missing. I want to have an instance of some class inside another class. The way I see it, I have 3 options: Have the object class2 inside class1 as I have it below. This means it gets constructed when an instance of cla...
Your examples are a bit backwards. I think you meant this instead: class class2 { public: class2(args) { ... } }; class class1 { protected: class2 class2_inst; public: class1(args) : class2_inst(args) { ... } }; class class2 { public: class2(args) { ... } }; cl...
64,284,699
64,284,758
Difference between while and if when using getline()
I have a .cpp file that reads from two .txt files and outputs them on the screen. Here is the code: #include <iostream> #include <vector> #include <string> #include <fstream> using namespace std; class check { public: void display(); ifstream read_number, read_amount; }; void check::display() { read_numbe...
while is a loop statement, so the execution is looped. Let's see what will happen step-by-step: transfer = true; // (1) while (getline(read_amount, line) && transfer == true) // (2) { cout << "$" << line << endl; // (3) transfer = false; // (4) } transfer is set to true at line (1) Something is read to line a...
64,284,893
64,286,956
libtorch: Why does my Tensor change value when returned from a method into another method?
I'm debugging this error: Unhandled exception at 0x00007FFA0B7D3E49 in AudioPluginHost.exe: Microsoft C++ exception: c10::Error at memory location 0x00000044B4DABDB0. I am trying to train a neural network, mostly based off of this example. Here's what I'm doing: torch::Tensor TrainingSample::getRatingTensor() { c1...
I would say this is because of your use of torch::from_blob though I cannot be sure because I have no computer to test it on at the moment. Basically, torch::from_blob does not take ownership of the underlying data you are giving it. It means that you have to ensure that the data lives for at least as long as the tenso...
64,284,971
64,285,278
C++ Producer-Consumer with condition variable
Looking to synchronize two threads with a condition variable and created a simple example to practice. Think I have messed something up when doing the synchronization, because consumer hangs on waiting on a signal from cv. Even though there is cv.notify_one(), somehow the line return counter != 0 inside the lambda is n...
The problem is clearly fairness, as demonstrated by adding a line like std::this_thread::sleep_for(0.01s); just before the producer acquires the mutex. Most operating systems will not give you any fairness guarantees on mutexes. There are many ways of working around the issue of fairness. If you know how to handle thi...
64,285,244
64,285,362
Default constructor cannot be referenced error (Visual studios 2019)
I am getting an error at the bottom of my code when trying to reference my revised subclass, as follows: default constructor of 'Revisedcipher' cannot be referenced -- it is a deleted function I'm not entirely sure what that means or how to fix that. Any help with this would be greatly appreciated. My code: #include ...
As you have provided a non-default constructor (one with an argument) for your base class, SubstitutionCipher but no default constructor (i.e. one with no argument), the latter is implicitly deleted. Further, as your derived class, Revisedcipher provides no constructor, it does not override the deleted base class const...
64,285,282
66,747,598
How do I reduce time complexity of this substring palindrome?
I am solving this problem, input: a string, output: it's longest substring that is a palindrome I solved it in the below manner in O(n^3). I am trying to solve it in O(n^2). Please help. Here is the code: int isPalindrome(string str){ for(int i = 0, j = str.size()-1 ; i < j ;i++,j--){ if(str[i] != str[j]) ...
pair<int,int> getPalindromeRange(string str, int left, int right){ while(left>=0 && right<str.length()){ if(str[left] != str[right]) break; left--; right++; } return make_pair(left+1, right); } string longestPalindromicSubstring(string str) { pair<int,int>longestR...
64,285,303
64,302,622
How to dereference C/C++ void * to struct or callback in Rust?
I want to write an AI for an old game, in Rust. AI's for this game are libraries, in its Linux port it's just an .so file exporting: extern "C" void client(int Command, int Player, void *Data); void *Data can be either struct (depends on Command) or this function: typedef int TServerCall(int Command, int Player, int S...
You can cast raw pointers in Rust. use libc::{c_void, c_int}; #[repr(C)] struct TNewGameData { // the fields go here } #[no_mangle] pub extern "C" fn client(command: c_int, player: c_int, data: *mut c_void) { // Cast raw pointer to the right type. let game_data_ptr = data as *mut TNewGameData; // Conv...
64,285,588
64,285,820
which one performs better binary search or sequential search on unsorted data
If given an unsorted array which among the following two scenarios would have lesser time complexity or would perform better Binary Search - by sorting the array first and then using binary search algorithm Sequential search - on unsorted array So if given an unsorted array to search an element should we go for sorti...
Both exist because both have their places where they are useful. If you will search only once, sequential search is fastest. But if you do many queries, then binary search is faster. Given that sorting is O(n log(n)), binary search becomes the same number of operations if you have to do O(log(n)) searches. BUT, opera...
64,285,752
64,285,803
Implementation in R with RCPP
I have written a brute force algorithm in R and it does work fine. I want to implement using Rcpp so that my code runs faster however I can't get it to work. for example for a simple example w = [4 2 3] , v = [10 7 4] with maximum weight W=5 it doesn't return the proper Value (11). I appreciate it very much if you co...
The line int n=sizeof(w); is bad because sizeof is not for obtaining number of elements but for number of bytes occupied on the memory. It should be int n=w.length();
64,286,153
64,336,968
Set LLVM assembly output syntax with C++ API
I'm trying to find a way to set the assembly syntax that LLVM outputs (for x86 in particular). Following the Compiling to Object Code section of the Kaleidoscope tutorial, I'm outputting assembly files with TargetMachine->addPassesToEmitFile(pass, dest, nullptr, llvm::CGFT_AssemblyFile)) But there's no option to set ...
Here's a few things I found out by reading the LLVM source: The output assembly syntax is controlled by the AssemblyDialect member in llvm::MCAsmInfo. For x86 the derived classes of llvm::MCAsmInfo can be found in X86MCAsmInfo.h and X86MCAsmInfo.cpp. The member AssemblyDialect is initialized to the value of AsmWriter...
64,286,346
64,503,169
error: no template named 'is_same_v' in namespace 'std'; did you mean 'is_same'?
This is a followup for another question which is already resolved. But then, I receive this error: error: no template named 'is_same_v' in namespace 'std'; did you mean 'is_same'? !std::is_same_v<typename std::iterator_traits<T>::value_type, void>, O ~~~~~^~~~~~~~~ is_same /Applications/Xcode.app/Con...
The tool chain was not capable of C++17. Therefore, eventually, replaced std::is_same_v with std::is_same with this approach ...
64,286,432
64,286,718
"template argument deduction/substitution failed" for Eigen Matrix
I have the following function: template <typename DATA_T, std::size_t K, std::size_t F> void write_raw_file(const std::string& filename, Eigen::Matrix<DATA_T, K, F>& d...
Try changing the Template types of std::size to int. I was able to get the following working on godbolt: #include <iostream> #include <vector> #include <Eigen/Dense> template <typename DATA_T, int K, int F> ...
64,286,458
64,286,710
How do I change my classes private attribute value?
If I use a setter, it should then change my private classes attribute's value right? However that's not the case, it's just giving me the default value of the private attribute when I use the setter. I am finding the distance travelled value with a getter. Player.h #pragma once class Player { public: void setFore...
As Yksisarvinen states in the comments, the problem lays in new instances of the Player object spawning again and again with each recursion of welcomeToForest(). You just want to isolate the recursive bit of that function into its own function, that accepts the Player object as an outside parameter. Something like belo...
64,286,712
64,286,832
Why is the output different from the desired output in the case of class vs Inheritance?
In the code below if statement does not get executed and the desired output is different from the output. using namespace std; #include <iostream> class Person{ public: int age; Person(int initialAge); void amIOld(); void yearPasses(); }; Person::Person(int initialAge){ // Add some more code to ru...
age = initialAge; not other way around. And you better to do more tidy formatting, it's hard to see that part of code, hence mistake might be looked over. E.g. Person::Person(int initialAge) : age(initialAge) { // Add some more code to run some checks on initialAge if (age < 0) { age = 0; co...