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 |
|---|---|---|---|---|
72,246,117 | 72,246,335 | Does modern compilers use copy elision when using the builder pattern | I am using a few builder patterns in my code base and I was wondering whether return by value should be favoured over the return by reference, given that is the push I am feeling with modern C++. The example, in my opinion, would generate loads of copies if I applied the return by value approach.
class EmailBuilder
{
... | There are many cases where returning by value is favored since it typically side-steps life-time issue. This is not one of those cases because life-time of the builder is usually well defined and well understood. Thus returning by reference should be favored.
Also, in C++20 you can use designated initializers:
#include... |
72,247,050 | 72,247,283 | Vectors in functions | I have these code lines in my .cpp file:
void Student::operator+=(const Subject &a){
vector<Subject> v;
v.push_back(a);
}
and I have this operator overloaded:
ostream &operator<<(ostream &output, Student &a){
vector<Subject>v;
/*for (auto& a:v){
output<<a<<endl;
... | Your vector vector<Subject> v; is in each operator implementation function, and therefore is generated just locally in each function, and will be destroyed by its end.
Think about declaring this vector one time, as a private member of your Student class.
|
72,247,334 | 72,247,589 | using shared_ptr of a type of Class A as a member variable of class B | Assume that my class B is something like this:
class B {
B (double d,double e)
private:
std::shared_ptr < class A > sp;
}
The Constructor from class A looks like:
A(double a, double b){...};
Now, I want to write the constructor function for my class B, in which an object from class A is constructed(initialized or as... |
How can i use the constructor initilizer list using :
If you want to initialize sp you can do it in the constructor initializer list as shown below, (and not inside the body of the constructor as you were doing):
//---------------------vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv-->constructor initializer list
B (double d,doubl... |
72,247,462 | 72,248,214 | write a rolling sd function in R and implement in C++ | I have to write implement R function for C++. for e.g I am trying to calculate rolling SD but below code is not working. any help will be highly appreciated.
#Below code is working fine
library(roll)
n <- 150
x <- rnorm(n)
x
weights <- 0.9 ^ (n:1)
weights
roll_sd(x, width = 5)
#But when I am passing it though the CPP... | This is not how cppFunction works. You cannot simply pass it an R call and expect it to magically transpile to C++.
In fact, it's more like the other way round. You write the function in C++ and cppFunction makes that function available in R.
A crude implementation of a rolling standard deviation that matches roll_sd w... |
72,247,716 | 72,248,109 | Debug Assertion Failed: Expression vector subscript out of range | I dont understand why it says subscript out of range when I have reserved the space in the vector. I have created a short form of my code to explain what the problem is better:
#include <vector>
#include <string>
#include <thread>
#include <iostream>
using namespace std;
class A {
public:
vector<vector<string>> f... | foo.reserve(10)
Reserves space for elements in foo, but it does not populate any of the elements with an empty std::vector.
You can change it to:
foo.resize(10);
Which will reserve the space and create the empty vector< string > elements, so that you can access them.
|
72,247,817 | 72,247,863 | how to write forward iterator using private std::vector base class | I need a vector class that exposes a small subset of the std::vector API. Everything works except range-based for. Here my attempt at implementing a forward iterator, which however does not compile.
#include <vector>
#include <iostream>
template <class T>
class OwningVector : private std::vector<T*> {
using super... | class Iterator : public std::vector<T*>::iterator {};
Why? This looks like a certain other language's way of doing that. It's also not guaranteed to work because vector<T*>::iterator may actually be a pointer type, in which case you can't derive from it.
using Iterator = typename super::iterator;
using ConstIterator =... |
72,247,970 | 72,279,500 | what is multisample per pixel in directx11 DXGI_SAMPLE_DECS | I was reading documentation about DXGI_SWAP_CHAIN_DESC and i came across with DXGI_SAMPLE_DESC
Count
Type: UINT
The number of multisamples per pixel.
now what exactly is multisamples per pixel?
| DXGI_SAMPLE_DESC as you surmised is for specifying Multi-Sample Anti-Aliasing (MSAA).
That said, you should be aware that the SwapChain support for MSAA is not something you should use anymore. As such, just always set DXGI_SWAP_CHAIN_DESC.SampleDesc.Count = 1; and DXGI_SWAP_CHAIN_DESC.SampleDesc.Quality = 0;.
Instead,... |
72,247,990 | 72,261,555 | Remove some, but not all overloaded functions inherited from base class | I am writing a vector class that takes ownership of member pointers. As far as possible, I want to reuse std:vector. I have been trying private and public inheritance; in both cases I am running into difficulties.
For private inheritance, see issue how to write forward iterator using private std::vector base class.
For... | From the comments:
Using v[0]->m will call the const-version of the operator if v is const. Otherwise it calls the non-const operator.
The fact that you don't write to v doesn't affect this.
|
72,248,200 | 72,248,229 | Error: (One function) cannot be overloaded with (other function) | I have the following class structure:
class DBData
{
public:
DBData();
virtual
~DBData() = 0;
virtual
DBData* Clone() const = 0;
virtual
std::unique_ptr<DBData>& Clone() const = 0;
};
This does no compile, and the compiler objects with the following error message:
error: ‘virtual ... | The problem is that we cannot overload a member function(or a function) based only on its return type.
This is because overload resolution takes into account the function's signature.
And from defns.signature.member
signature
〈class member function〉 name, parameter type list (11.3.5), class of which the function is a ... |
72,248,443 | 72,248,487 | Problem with a junk value in a member when using an empty default constructor | I am trying to create a very basic class with a default constructor:
class Point {
public:
Point() = default;//con 1
explicit Point(double x): x_axis(x), y_axis(0){}//con 2
Point(const Point &other) = default;
~Point() = default;
private:
double x_axis;
... | It's because the second constructor initializes the member variables with values while the first constructor leaves the member variables with indeterminate values.
Either do:
class Point {
public:
Point() : x_axis{}, y_axis{} {} // instead of = default
...
or
class Point {
public:
Point() = default;
// .... |
72,248,495 | 72,248,846 | would anything happen if I pass a pointer function as a parameter? | I wonder that what would happen if I pass a pointer function as a parameter, is it valid and is the memory of that pointer function stuck somewhere in RAM?
This is the example:
char* Function1(char *array1, int N) {
...
return newChar;
}
char* Function2(char *array2, int M) {
...
return newChar;
}
char... | It is valid to write these kind of function calls but as you suspected, the memory you've allocated for the character array in subsequent function calls will be stuck in RAM, a memory leak. Let me explain with the following code.
char* Function1(char *array1, int N) {
char *newarray = new char [N];
for (int i =... |
72,248,532 | 72,248,556 | Does definition includes declaration? | int a = 0;
This code can be read either: declaration of a or
definition of a, right?
|
declaration of a or definition of a right?
Note that every definition is necessarily a declaration in C++, but not the other way round. That is, not every declaration is a definition.
Thus,
int a = 0; // A definition and hence also a declaration
The above is both a definition and also a declaration.
On the other ha... |
72,248,803 | 72,248,849 | What is the difference between iterator and &iterator? | vector<int> A = {1, 2, 3};
//case 1
for(auto it : A){
it = 0;
}
print(A) //OUTPUT -> 1, 2, 3
//case 2
for(auto &it : A){
it = 0;
}
print(A) //OUTPUT -> 0, 0, 0
How are 'it' and '&it' different? How exactly are iterator and &iterator working?
| Case 1
The auto keyword(without the use of &) infers a non-reference type. This means in your case 1, auto infers it to be of type int. This is a non-reference type, meaning that the values from the std::vector will get copied into the loop variable it, which in turn means that any changes made to it will not be reflec... |
72,248,910 | 72,249,110 | C++ creating Queue using Dynamic Memory | I am trying to create Queue using standard library for some part of my code. For abstract idea my Queue will have Front, Back pointers which points Front and Back elements in the Queue. So when I push something Back ptr will point to new value that has been pushed. And When I pop something front ptr will point the next... | I rewrite your code:
#include <iostream>
using namespace std;
class Queue
{
private:
struct node
{
int value;
node* next;
node(int value, node* next = nullptr)
{
this->value = value;
this->next = next;
}
};
node* front, * back;
public:
... |
72,249,280 | 72,249,349 | Issue with unique_ptr | Can anyone tell me what the issue is with this code? It throws an error:
cannot convert argument 1 from '_Ty' to 'const day18::BaseInstruction &'
enum Command { snd, set, add, mul, mod, rcv, jgz };
struct BaseInstruction {
Command cmd;
char reg;
BaseInstruction(Command cmd, char reg)
... | std::make_unique() is the smart-pointer equivalent of new, which means it calls the constructor of the specified type, passing the input parameters to that constructor, and returns a std::unique_ptr that points to the new object.
The statement:
std::make_unique<BaseInstruction>(new Instruction<char>(...));
is therefor... |
72,249,892 | 72,250,049 | Building C++ code with different version of Visual Studio produces different file size of .exe? | I can build my own .sln manually on my machine, or have Azure DevOps build it on a remote machine. The software is targeting .NET Core 3.1, and using C++17. I had noticed that building the same code, from the same branch, produced a different size .exe: the remote one had 9 KB less than the local one.
I finally got the... | The C++ standard does not dictate the machine code that should be produced by the compiler. It just specifies the expected observable behavior.
So if for example you have a for loop the standard dictates the behavior (initializing, checking the condition etc.). But you can translate to machine code in various ways, e.g... |
72,249,905 | 72,253,206 | asio::ip::tcp::socket auto reconnect by io_service | Under Ubuntu 2404LTS with boost version 1.65.1.
I use io_service to initiate asio::ip::tcp::socket async_connect and get socket1, then I read several messages from it.
After receving some specific message from socket1, I call io_service::stop() with remaining/unhandler handler in the io_service and explicitly invoke so... | We can't tell without seeing the code, but my suspicion is to undefined behaviour.
Here's a literal implementation of your description:
Live On Coliru
#include <boost/asio.hpp>
#include <iostream>
namespace asio = boost::asio;
using asio::ip::tcp;
using boost::system::error_code;
int main()
{
std::cout << std::boo... |
72,250,228 | 72,250,287 | How should I implement a copy constructor & assignment operator for a matrix class? | I have a matrix class with fields like this:
template <typename T>
class Matrix
{
private:
T **matrix = nullptr;
int rows;
int cols;
At this stage, I have written an assignment operator and a copy constructor. But firstly, there is code duplication, how can it be avoided, and secondly, they seem very sim... | Use a 1D array then. It will be much cleaner and simpler and faster than an array of pointers to arrays... You can do something like:
template <typename T>
class Matrix
{
private:
// Note: Assuming T is a trivial type, most likely a fundamental type...
T* data; // Flattened matrix with size = rows*cols. Be car... |
72,250,271 | 72,280,172 | Barycentric rational interpolation | I'm trying to write a function which returns a function for calculating Barycentric rational interpolation in C++.
Note:
It is not at all a wise idea to recalculate weight coefficients
W, = 1, 2,…, within the function itself that returns as a result of “Barycentric Interpolation”. Namely, in this way, these coefficie... | Here you go. Note that I rewrote basic parts of your code using my own code from the previous edit version. Further, to clarify: You are actually looking for a thing named Floater-Hormann approximation, which is basically an approximation by a rational function without poles in the interpolation region (and that is usu... |
72,250,322 | 72,250,422 | cpp - is vtable pointer being altered during construction/destruction | So, while being in a ctor/dtor of a base class while doing smth with a derived class and calling member functions (including virtual), whether via this pointer or not, the function of the relevant class will be called.
How come? Is vtable pointer of the object being altered somehow during the process? Because, as I may... | An object is the type that it is... until it isn't.
Per C++'s rules, an object's constructors get called in a specific order. Because a derived class instance is a base class instance at all times, the base class instance constructor needs to be called before the derived class instance.
But if that's the case, then wha... |
72,250,680 | 72,250,805 | Inherited Templates - C++ | I have a template base class and an inherited class. There is a function inside the baseclass which can accept difference types, I expected that I would call this from inside the inherited class with 'BaseClass::Add();' but I instead receive the error "expected primary-expression before ‘>’ token".
How do I call BaseCl... | Use this syntax
BaseClass<T>::template Add<U>()
|
72,250,710 | 72,250,913 | Which version of C++ standard allows reuse of storage previously occupied by an object of a class that has const or reference members? | This answer cites some unknown revision of C++ standard draft:
If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a refer... | In terms of the "Major" Standard releases, the clause about the const qualification (which you have emphasised in the excerpt you cite in your question) was present in the final draft for the C++17 Standard (N4659) but not present in that for the C++20 Standard (N4861).
So, from that it would appear that conformance to... |
72,251,287 | 72,252,534 | Why isn't explicit specialization with private type allowed for function templates? | https://godbolt.org/z/s5Yh8e6b8
I don't understand the reasoning behind this: why is explicit specialization with private type allowed for class templates but not for function templates?
Say we have a class:
class pepe
{
struct lolo
{
std::string name = "lolo";
};
public:
static lolo get()
{... | From C++20, using private members in the parameter of a specialization of a function template is perfectly valid, due to PR0692. In particular, the following wording was added to temp.spec.general#6:
The usual access checking rules do not apply to names in a declaration of an explicit instantiation or explicit special... |
72,251,624 | 72,251,708 | Polymorphism produces odd behaviour | I have a vector wrapper class which is aimed to simplify polymorphism:
class Shape
{
public:
Shape(string Name) : name(Name) {}
virtual ~Shape() = default;
string name;
private:
};
class Point : public Shape
{
public:
Point(string Name, float X, float Y) : Shape(Name), x(X), y(Y) {}
float x =... | You can't reassign a reference. ref = v[1] copies the value of v[1] into the object referenced by ref. As the compiler only knows that ref is a Shape it calls Shape's assignment operator and therefore only copies the Shape members leaving the members from Point unchanged.
If you need to change what a reference points t... |
72,252,179 | 72,252,209 | Why does full `constexpr` enabling of a data structure cause the compiled code to be bigger? | At this moment of Jason Turner's 2016 CppCon talk "Practical Performance Practices", he mentions that full constexpr enabling of every data structure that can be (I'm guessing that means making every field and function constexpr that can be) can result in bigger code "because this causes more data structures to be comp... | When implementing a 7-bit cyclic redundancy check (CRC) algorithm on a microcontroller, I find it handy to build a 256-byte lookup table ahead of time, with some code like this:
uint8_t crc_table[256];
for (unsigned int i = 0; i < 256; i++)
{
crc_table[i] = some_crc_function(i);
}
So if you turn crc_table into a con... |
72,252,931 | 72,267,379 | How to determine the first function that gets called when running a program in Visual Studio? | I'm currently working on a project that already has lots of files and functions. When I run the program, it executes properly, but I want to know how to find out the first function that gets called when we initially run the application.
More info:
When you run the application, it opens up a small window, asks the user... | It's the main function (or the WinMain function in my case).
|
72,253,146 | 72,253,400 | Adjust floats to satisfy the condition: abs(float) <= 0.5? | I have got a vector of float of an arbitrary size. I would like to adjust the floats so that they satisfy the condition abs(float) <= 0.5. The fractional part should be preserved although it can differ from the original value, thus setting "x = 0.5" is incorrect. If the float is close to integer, discard it (the input ... | You can use the floor function to reduce the amount of branches:
#include <iostream>
#include <cmath>
float scale(float x) {
bool neg = std::signbit(x);
x -= std::floor(x + 0.5);
if (!neg && x == -0.5) {
return 0.5;
} else {
return x;
}
}
int main() {
std::cout << "-1.23 " <<... |
72,253,393 | 72,253,530 | How do I apply modifications to a locally scoped range and return it? | The code below, when compiled under g++-11.3 using --std=c++20 -D_GLIBCXX_DEBUG and executed, produces a bizarre runtime error about iterators. I'm not exactly sure what it means but I suspect it has something to do with the vector range going out of scope when test() returns: range doesn't get moved or copied, rather ... | First, since the std::vector itself is common_range, transform_view will also be common_range, so using views::common here is redundant.
Second and more important, range is a local variable, so it will be destroyed once it leaves test(), which makes test() return a transform_view that holds a dangling pointer.
Is ther... |
72,253,554 | 72,253,688 | std::array of structures initializater list syntax | Consider the following C++ code:
struct My_Struct
{
int a;
int b;
};
Now I want to declare a constant std::array of these structures:
Option A:
const std::array<My_Struct,2> my_array =
{
{1,2},
{2,3}
};
Option B:
const std::array<My_Struct,2> my_array =
{
My_Struct(1,2),
My_Struct(2,3)
};
Question: why d... | std::array is a class that contains an actual array. It looks something like this:
template <typename T, size_t N>
struct array
{
T _unspecified_name[N];
// Member functions.
};
Note that std::array has no constructors or private data members, so it is an aggregate.
When you brace-initialize a std::array you... |
72,253,644 | 72,253,805 | I want to Display all the strings in my queue | This is my code , I want to display all I put on tail and Head in this c++ program. I want the program display all the queue elements when I click displayAll(). I edited the code, by adding the full details of the code. Not idea to show all elements in the queue , I able to see the size of the queue but not the elemen... | A simple loop like this will do:
void displayAllPatients() {
cout << "Patients are: " << "\n";
auto p = head;
while(p) {
cout << p->name << "\n";
p = p->next;
}
}
or
for(auto p = head; p; p = p->next) {
cout << p->name << "\n";
}
|
72,253,869 | 72,254,000 | Shouldn't there be a copy ctor invocation here? Elision disabled (no named return value optimization) | struct Test {
int field = 30;
Test() { cout << "In ctor" << endl; }
Test(const Test &other) { field = other.field; cout << "In copy ctor" << endl; }
Test(Test &&other) { field = other.field; cout << "In move ctor" << endl; }
Test &operator=(const Test &other) { field = other.field; cout << "In copy ... | C++17
Starting from C++17, there is mandatory copy elison which says:
Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the s... |
72,253,901 | 72,253,947 | Member initialization syntax in C++ constructors | Why does the following not compile?
class A {
public:
A(int a) : a_{a} {}
private:
int a_;
};
|
Why does the following not compile?
Because you're most probably compiling the shown code, with Pre-C++11 standard version.
The curly braces around a in your example, is a C++11 feature.
To solve this you can either compile your program with a C++11(or later) version or use parenthesis () as shown below:
Pre-C++11
cl... |
72,254,064 | 72,268,522 | C++ Recursive Maze Solver looping infinitely | I am new to C++ and am trying to write a program that reads a file, dynamically creates a 2D array, and fills the array with input from the file. Then it solves the maze using recursion. The text file looks like this:
The first 4 numbers dictate the amount of rows, amount of columns, and starting position (X,Y). "S" i... | I figured it out after some debugging. Rewrote the function from scratch. Thank you for everyone for your help. I added an out of bounds check and added a condition for the if statements to check for both 'O' and 'E'. Weirdly the backtracking if statements remained the same, even though I thought they were the issue.:
... |
72,254,293 | 72,254,361 | How can I solve this weird error while using map in c++ | I'm getting stuck in a weird infinite loop while using map in c++.
The first code works good and outputs numbers.
The test cases are:
5 2
1 2 3 4 5
long long N, K, count = 0;
cin>>N>>K;
long long l;
map<long long, long long> mp;
for(int i = 0; i<N; i++){
cin>>l;
++mp[l];
}
for(auto a:mp){
cout<<a.first +... | The problem is that if the key is not found inside the map, a key-value pair will automatically be created and inserted into the map and so you're changing the size of the map while iterating it leading to undefined behavior.
Undefined behavior means anything can happen including but not limited to the program giving y... |
72,255,074 | 72,255,209 | Question marks in wildcard search in Windows | I am using wildcard characters (? and *) to search for files in Windows in a c++ program with _tfindfirst64 and _tfindnext64. I observed the following code
TCHAR root[1024] = L"C:/testData/?????_?????.jpg";
_tfinddata64_t c_file;
intptr_t hFile = _tfindfirst64(root, &c_file);
do
{
wcout << c... | As you've found, a ? in a file search doesn't require a character to be present, but matching will fail if a character is present that your search string doesn't account for. For example, foo?.txt will match foo.txt, foo1.txt, fooa.txt, and so on, but will not match foo10.txt or foo_abc.txt.
About the only way I know o... |
72,255,609 | 72,255,924 | std::unordered_map insert invalidates only iterators but not references and pointers to the element node | Can somebody explain why insertion into std::unordered_map container only invalidates iterators but not references and pointers. Also I am not able to understand what the below statement from https://en.cppreference.com/w/cpp/container/unordered_map/insert mean
If the insertion is successful, pointers and references t... | Insertion of unordered_map doesn't invalidate references because it doesn't move the data, however the underlying data structure might change rather significantly. Details of how exactly it is implemented aren't specified and different compilers do it differently. For instance, MSVC has a linked list for data storage a... |
72,255,969 | 72,328,088 | Fastest way of resizing (rescaling) a 1D vector by an arbitrary factor | I have the following code that does the resizing of a 1D vector with nearest neighbor interpolation in a similar fashion you'd also resize an image. Another term would be resampling, but there seems to be a lot of confusion around these terms (resampling is also a technique in statistics), so I prefer to be more descri... | Since the Cortex-M series is quite limited (even floating point in M7 is optional), I would estimate a reasonable speed-up coming from using Bresenham's mid point line drawing algorithm.
This algorithm always advances either N or N+1 elements based on the sign of the error term. The modulus does not need full length di... |
72,256,050 | 72,256,571 | Does std::mutex enforce cache cohesion? | I have a non-atomic variable my_var and an std::mutex my_mut. I assume up to this point in the code, the programmer has followed this rule:
Each time the programmer modifies or writes to my_var, he locks
and unlocks my_mut.
Assuming this, Thread1 performs the following:
my_mut.lock();
my_var.modify();
my_mut.unlock()... | C++ operates on the relations between operations not some particular hardware terms (like cache cohesion). So C++ Standard has a happens-before relationship which roughly means that whatever happened before completed all its side-effects and therefore is visible at the moment that happened after.
And given you have an ... |
72,256,233 | 72,413,140 | C++ Drogon framework model-based ORM | I've began to learning C++ Drogon framework. I read the official and unofficial documents about the Drogon ORM. But I couldn't realized how can I create a model-based ORM database.
I want to create my models then run a migration command to map models to database tables.
If there is any document and guide about Drogon m... | You can use
drogon::app().loadConfigFile("../config-name.json");
then run your sql command under drogon plugins after the program run. It's also will shutdown your custom plugin after the program exit.
It's require config files, where you can add your plugin on config-name.json.
steps:
1. create plugins
You can run f... |
72,256,636 | 72,275,688 | Connect QTimer with a Slot with parameters | I tried the following:
connext(&timer, &QTimer::timeout, this, &myClass::myMethod(_param1, _param2)); // does not work
timer.setSingleShot(true);
timer.start(100);
The timer of type QTimer is a member element of the class.
Is there a way to connect the timeout() signal of a timer to a method with multiple parameters?
| The QTimer's timeout signal void timeout() does - on its own - not have enough parameters to call myClass::myMethod(_param1, _param2); (where exactly should timeout take _param1 & _param2 from?)
You can either use a lambda function:
//assuming you have _param1 & _param2 as variables before this point
connect(&timer, &Q... |
72,256,657 | 72,257,172 | Do I pass the wrong data to glTexImage2D? | I'm trying to make an OpenGL texture by populating a pixel buffer with data from a baked font. I'm taking each value from the font array and making a bitmap essentially.
The problem is when I'm displaying the full texture I get noise. However by creating an 8x8 texture of one glyph the texture is displayed correctly.
T... | The way you arrange the data makes sense for a tall 8x1024 image where each 8x8 makes up a character.
But you load it as a 1024x8 image instead, putting all the pixels in the wrong places.
|
72,256,729 | 72,256,803 | MSVC - expression must have pointer-to-object type but it has type "float" on generic array? | MSVC on Visual Studio 2019 says "expression must have pointer-to-object type but it has type "float" on generic array" here:
void _stdcall sample::Eff_Render(PWAV32FS SourceBuffer, PWAV32FS DestBuffer, int Length)
{
float gain = _gain;
for (int ii = 0; ii < Length; ii++)
{
(*DestBuffer)[ii][0] = (*S... | Change this:
(*DestBuffer)[ii][0] = (*SourceBuffer)[ii][0] * gain;
(*DestBuffer)[ii][1] = (*SourceBuffer)[ii][1] * gain;
To this:
DestBuffer[ii][0] = (SourceBuffer[ii][0]) * gain;
DestBuffer[ii][1] = (SourceBuffer[ii][1]) * gain;
Explanation:
(I'm guessing you are doing audio processing of a stereo si... |
72,256,841 | 72,257,071 | Are constraints in overload resolution affected by difference it type qualifiers? | Having the following simple code:
#include <concepts>
auto f(const auto&) { }
auto f(std::integral auto) {}
int main()
{
f(5);
}
We have an ambiguous call with clang & gcc but MSVC chooses the more constrained one. So far I found nothing that would support the clang's & gcc's behavior. So is it a bug in both ... | Without considering constraints, the call is ambiguous because the first overload is deduced to a function parameter type const int& and the second to int. Neither will be considered better than the other when called with a prvalue of type int and neither const auto& or auto are more specialized in usual partial orderi... |
72,256,844 | 72,257,083 | Rotation of square by center using rotation matrix | I'm trying to rotate a square using rotation matrix with this implementation.
void Square::rotateVertices(std::vector<float> &vertices)
{
float px = (vertices[0]+vertices[2])/2;
float py = (vertices[1]+vertices[5])/2;
for (int i = 0; i < 4; i++)
{
float x1 = vertices[i*2];
float y1 = v... | That's because your square is a rectangle. My crystal ball knows this because its width and height are calculated separately, and therefore, you meant for them to be different:
// if you wanted these to be the same you wouldn't calculate them separately
float ay = (size / float(height) / 2.f), ax = (size / float(width)... |
72,257,744 | 72,265,498 | dx12) It takes too long to compile Shader |
When profiling, it took about 14 seconds only for shader compile. (Although it took only 7 seconds to load all that obj files.)
how can I optimize this? do I have any option to pre-compile hlsl shaders?
| The recommendation is in fact to compile the shaders off-line (at build time) and then load the resulting binary shader blob at runtime.
You can use the built-in Visual Studio HLSL integration which will generate .cso files (Compiled Shader Object). See Microsoft Docs for details. For notes on using Shader Model 6 DXC... |
72,257,925 | 72,258,036 | using a class n times with a for loop c++ | I'm trying to learn classes, so here I want to create n-number Triangle and Rectangle types, input a,b,c, also input from user and then cout them.. im trying to get n-number of Triangle and Rectangle with for loop but at the end I get print only the biggest S() and P() which user had entered.. for example if I user say... | You are overwriting the same variable every time you call Input(). Instead, create a vector of rectangles.
#include <vector>
class Rectangle {
// ...
};
int main()
{
// ...
std::vector<Rectangle> rectangles(n);
for (int i=0; i<n; i++)
{
rectangles[i].Input();
}
for (int i... |
72,258,278 | 72,259,561 | Catch dll function that does not return | i do have to use a .dll library in order to have access to hardware i want to control.
The problem is, that some functions of that dll sometimes do not return. They seem to be stuck in an infinite loop or something.
My idea was to run the function calls in a different thread and kill the thread if it is stuck/does not ... | Isolating the DLL in its own thread does not really help a lot, but the idea makes sense. It might be better to isolate the DLL in its own helper process. You would then terminate the entire helper process.
This is by necessity not a clean exit. That is inherent in the problem. You don't know how the DLL corrupted inte... |
72,258,758 | 72,258,912 | Anyone can tell me why it is giving runtime error | Question Link: LeetCode, I am getting runtime error but not found where it is causing. why it is giving runtime error any one can explain me. Thanks in advance.
class Solution {
public:
bool dfs(vector<vector<int>>& grid, int row, int col, int color)
{
if(row<0 || col<0 || row>=grid.size() || col>=grid[... | I've wrote test for your code: https://godbolt.org/z/TazozK8xe and enabled address sanitizer.
Without reading your code and just by reading sanitizer logs you can see you have infinitive recursion (note number of stack frames is more then 178, when problem is simple to do it in maximum 4 steps). Basically your conditio... |
72,258,791 | 72,258,873 | How to pass vector of vector as default argument in functions, C++ | IDE showing error at last argument. I am new in C++ and unable to figure it out.
Please help. Thanks in advance.
void Box_2(vector<vector<int>> &v,
string text1 = "",
string text2 = "",
vector<vector<int>> &trace = {}
)
| The problem is that we cannot bind an lvalue reference to a non-const object to a temporary of the corresponding type.
For instance,
int &ref = 5; //THIS WILL NOT WORK
const int &REF = 5; //THIS WILL WORK
To solve this error you can make the last parameter name to be an lvalue reference to a const object which is al... |
72,259,778 | 72,259,970 | how to store sentences (words) wit h spaces in an single array in cpp dynamically | int main()
{
key[100];
int i = 0, t = 0;
cout << "Enter the Keyword :";
while (t < 3)
{
cin.getline(key, 100);
i++;
t++;
}
cout << key[0] << endl;
}
I used this code. But it returns only a character of the word.Please say how to get a single word in array one b... | #include <iostream>
int main()
{
// 3 strings of 100 char max (+1 nullchar)
char key[3][101];
int i = 0;
std::cout << "Enter the Keyword :\n";
while(i < 3) {
std::cin.getline(key[i],100);
i++;
}
for(i = 0; i < 3; ++i) {
std::cout << key[i] << std::endl;
}
return 0;
}
Alternativ... |
72,260,456 | 72,265,274 | C++ STD libraries in C | as the title suggests I am attempting to mix C and C++ source files in a project.
My project has the following files
.
├── comms
│ ├── can.c
├── config_parsing
│ ├── config_parser.c
│ ├── file_operations.c
├── main.cpp
├── scheduler.c
├── signal_handler.c
├── thread_health.c
└── utilities
├── logger.c
├──... |
if you want to provide an answer, I will gladly accept it! The -c c++ option has worked! –
Michael
It is pretty clear that the code in the .c files is C++ code and not C code. This is evidenced by the #include directives you found:
#include <string>
#include <vector>
The compiler front end (e.g. gcc or g++) will try... |
72,260,569 | 72,261,477 | Minimal mutexes for std::queue producer/consumer | I have two threads that work the producer and consumer sides of a std::queue. The queue isn't often full, so I'd like to avoid the consumer grabbing the mutex that is guarding mutating the queue.
Is it okay to call empty() outside the mutex then only grab the mutex if there is something in the queue?
For example:
struc... | As written in the comments above, you should call empty() only under a lock.
But I believe there is a better way to do it.
You can use a std::condition_variable together with a std::mutex, to achieve synchronization of access to the queue, without locking the mutex more than you must.
However - when using std::conditio... |
72,260,589 | 72,277,992 | If the application has two services to send data messages, How will the messages be casted in onWSM function to obtain message content? | I tried to cast two messages in the onWSM function, one of the message is the accident message from TraCIDemo11p example see link; https://github.com/sommer/veins/blob/master/src/veins/modules/application/traci/TraCIDemo11p.cc and the other message I created myself.Simulation stops when handling of the accident message... | It seems that MyClusterApp::onWSM() may handle various types of messages. Therefore, I suggest use dynamic_cast to recognize the type of message - it is safe and returns nullptr when a message cannot be cast.
An example of modification:
void MyClusterApp::onWSM(BaseFrame1609_4* frame) {
joinMessage* wsm = dynamic_c... |
72,260,594 | 72,260,714 | c++20 concepts: How can I use a type that may or may not exist? | I have begun a project that makes heavy use of c++20 concepts as a way of learning some of the new c++20 features. As part of it, I have a function template that takes a single argument and operates on it. I wish to have the flexibility to pass types to this function that specify another type that they operate on, but ... | This has had a solution since C++98: a traits class. Concepts just makes it a bit easier to implement:
template<typename T>
struct traits
{
using type = default_type;
};
template<has_type T>
struct traits<T>
{
using type = T::my_type;
};
Without concepts, you'd need to use SFINAE to turn on/off the specialization... |
72,261,075 | 72,261,155 | How to create const reference to pointer on const? | I want to create the following class, but the compiler gives an error (it tells that the signatures of the methods are the same):
struct entities_set_less
{
constexpr bool operator()(const ContentEntity*& _Left, const ContentEntity*& _Right) const
{ // apply operator< to operands
return (_Left < _R... | First, let's clarify (or attempt to) what you actually want. You say you want a "const reference" … but references are (effectively) const, anyway (i.e., once a reference variable is bound to its target, it cannot subsequently be bound to a different target).
So, what you may have meant is that you want the arguments i... |
72,261,388 | 72,261,576 | Why pass input/output stream in a function? | Why would we want to do this:
#include <iostream>
void print(std::ostream& os) {
os << "Hi";
}
int main() {
print(std::cout);
return 0;
}
instead of this:
#include <iostream>
void print() {
std::cout << "Hi";
}
int main() {
print();
return 0;
}
Is there some certain advantage or functionality that is ... | Yes, the first version is significantly better. Like already mentioned in the comments, it allows you to use any kind of std::ostream, not just std::cout. Some of the most important consequences of this architectural choice are:
You can use your function to print the required data to standard output, a file, a custom ... |
72,261,511 | 72,261,872 | Access violation executing in classes with inheritance/ c++ | I have a base class Participant and I need to sort object in array of participant by quantity of their prizes or diplomas. The virtual function get_data return this number. But whileI try to sort, i've got error Access violation executing in row with comparing 2 numbers.
if (p[j].Get_Data() < p[i].Get_Data()) {
This i... | The issue here is that when you are passing *pa, only the first element is accessible. If you run it in debug mode you will be able to see that inside sort function, p[1] is not a valid object. Basically, only p[0] is passed to the function. You should pass the reference to the array i.e. **pa to the sort function
void... |
72,261,567 | 72,261,958 | C++20 pre-allocate array to store multiple types | I have a Linux code.
I would like to pre-allocate 10000 items of different types as circular array. I always know which object type it is.
Since biggest object takes 54 bytes - I want to allocate 10000 x 54 chunk of memory.
Whats the correct pointer arithmetic to retrieve reference to an object with index i ?
x64 archi... | Use std::array<std::variant<Type1, Type2, Type3, ...>, 100000> cache;
|
72,261,977 | 72,263,350 | c++ IPC Boost::Interprocess vector of classes containing map | I like to create a boost interprocess vector of classes containing maps.
The following code is based on the Container of Container and Creating Vectors in shared memory example, but I feel very overwhelmed by combining these two tutorials. I think im stuck constructing "MyVec" in memory. After that, the code does not c... | You want to create a vector of classes but creating a vector of vector of classes.
All you need is complex_data_vector, your complex_data_vector_vector is not needed.
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/ma... |
72,262,307 | 72,262,422 | How to get out of "std::thread::id" the same id as the "WinAPI thread-id" (on Windows)? | How to get out of std::thread::id the same id as the "Win API thread-id" (on Windows)?
The thread-id is 9120 (id and this_id). I tried a few ANSI C++ ways, but they resulted in a different id:
Code:
int main()
{
// Win API:
const auto id = Concurrency::details::platform::GetCurrentThreadId(); // OK
// AN... | You shouldn't rely on the format or value (see comments below). That being said, you can play with the operator<<:
#include <iostream>
#include <sstream>
#include <thread>
int main()
{
std::stringstream ss;
ss << std::this_thread::get_id();
std::size_t sz;
ss >> sz;
std::cout << std::this_thr... |
72,262,650 | 72,262,739 | Will std::unordered_map::clear() be slower than std::map::clear() because clear operations are "carried on" in the former? | I was reading this and from what I can get is that unordered_map practically works linear in number of elements + number of buckets.
So, let's say, I have code, which
adds arbitrary number of elements to std::unordered_map
then clear() the std::unordered_map
repeat this multiple times.
If I had lot of elements at ... |
When will std::map::clear() going to be faster that std::unordered_map::clear()?
Both have linear asymptotic complexity. You can time your code using both to see if either is measurably faster.
Note that if the destructor of the element is non-trivial, then clear of all containers has linear complexity. If the destru... |
72,262,700 | 72,262,748 | How do I define a member function of a specialized template class? | I have a template class ProcessPromise<T> and its specialization ProcessPromise<void> that depends on ProcessTask<T>:
template<typename T>
struct ProcessTask;
template<typename T>
class ProcessPromise
{
public:
ProcessTask<T> get_return_object();
};
template<>
class ProcessPromise<void>
{
public:
ProcessTask<... | Just remove the template<> prefix as shown below:
//no prefix template<> needed here
inline ProcessTask<void> ProcessPromise<void>::get_return_object()
{
return { };
}
Working demo
Note that the inline keyword is added so that we don't get multiple definition error.
Explanation>
The reason we don't need the prefi... |
72,263,065 | 72,264,562 | QStyledItemDelegate / QAbstractItemDelegate for QListView | My aim is to create something like contact app, where I can list contacts and choose it to see information about person. I figure out that one of the possible solution is to use QListView + QStyledItemDelegate / QAbstractItemDelegate. The information about it is very difficult so I don't understand it clearly;
(Contact... | I suggest you to start with a data model.
Use QStandardItemModel class for beginning and populate it with QStandardItem class instances. It would allow you to set icon, text, font, background, size and other properties for items. Refer to https://doc.qt.io/qt-5/qstandarditemmodel.html#details
Set your model to QListVi... |
72,263,196 | 72,263,654 | parameterized C++ nested struct array initialization | I've checked posts here that I can use template for nested struct. But when I'm trying to initialize an array inside a nested struct, there seems problem during initialization. In the following example, the array size is one of the parameters of the nested struct so Visual Studio complained that the array size is illeg... |
Did I do anything wrong when using the template and initialize the array?
Yes, you do count = new U[T];, but count is not a pointer.
If you want the vector to be initialized to have the size T, provide T to the vector's constructor in the member initializer list:
template<typename U, size_t T>
struct A {
struct B... |
72,263,202 | 72,269,853 | How can I show a comment block inside a code block inside a doxygen block? | Let's say I want to show a /* - */ delimited comment block inside a code block in a
Doxygen documentation block in C++ code. If the Doxygen block, is itself /* - */
delimited, like this,
/**
documentation
\code
/*
comment
*/
\endcode
*/
that's clearly going to be a problem: Doxygen will d... | As it is not possible to have a code block in a comment and I suggested to maybe use the \snippet command I give an example of it usage here:
/// documentation
/// \snippet this S1
void fie();
// [S1]
/*
comment
*/
// [S1]
resulting in:
Note: you can also use e.g.:
/// documentation
/// \snippet this S1
// [S1]... |
72,263,705 | 72,264,024 | Requires clause positioning in C++20 function templates | In C++20, you can write a constrained function template in a couple of different ways:
template <typename T>
concept Fooable = true;
template <typename T>
requires Fooable<T>
void do_something(T&); // (1)
template <typename T>
void do_something(T&) requires Fooable<T>; // (2)
According to the accepted answer in ... | The wording in this area has moved around a bit. In C++20, we had this rule in [temp.over.link]/7:
Two function templates are equivalent if they are declared in the same scope, have the same name, have equivalent template-heads, and have return types, parameter lists, and trailing requires-clauses (if any) that are e... |
72,263,838 | 72,266,972 | ROOT(CERN): Plot an figure with error bars using data from an csv file | I'm trying to read data from a .csv file, which contains 4 columns: "x","y","Standard Deviation" and "Uncertainty". I want to plot a scatter diagram with error bars, which represent the uncertainty red from the .csv file. I run the following codes in root's REPL:
auto rdf = ROOT::RDF::MakeCsvDataFrame("./file.csv")
aut... | GraphAsymmErrors doesn't seem to exist in the v6.26 documentation. The documentation you linked was for the master branch. You'll probably have to update to a nightly-build or wait for the next release in order to use that function.
In the meantime I would recommend you use RDataFrame::Take() on the respective branches... |
72,264,122 | 72,265,312 | Binding rvalue ref to string literal in constructor vs construct in-place | I'm a bit confused about C++ temporaries in regards to string literals and move semantics.
Which one of the following is better, in terms of performance and readability.
Usage: Constructor("string_literal")
Option 1: s is created from the string literal, then it is moved into the member variable.
Constructor(
string... | Option 1 will copy when you have a movable string and construct and move from a literal.
Option 2 will move when you have a movable string and construct and move when you have a literal.
Option 3 is the worst as it will always copy.
As you can see Option 2 <= 1 <= 3.
Also consider
Constructor("string_literal"s)
This i... |
72,264,228 | 72,264,321 | Including a precompiled header and a non-precompiled header in a .cpp file causes the .cpp file to not recognize the non-precompiled header | Visual Studio 2022:
I included a simple header to store basic functions like printing text or executing functions to my .cpp file, but after including a precompiled header that stores Windows.h the .cpp file doesn't recognize the functions/variables inside of the non-precompiled header.
CPP:
#pragma once
#include "basi... | The precompiled header must come first in the include list, because it erases everything that comes before it.
|
72,264,830 | 72,271,752 | How to insert a record into Microsoft Access using MFC? | How can I insert record in Microsoft Access?
CString SqlString;
CString name="I want to add this variable in Table3";
SqlString = "INSERT INTO Table3 (Name,Numbers) VALUES (name,099)";
When I do it that way gives the following error:
Database error:Too few parameters.Expected 1.
| This is a snippet from my own application:
BOOL CCommunityTalksApp::SetRecordForTalkNumber(int iTalkNumber, UINT uID, CString &rStrError)
{
CDatabase *pDatabase;
CString strSQL, strField;
BOOL bOK;
pDatabase = theApp.GetDatabase();
if(pDatabase != nullptr)
{
if (iTalkNumber... |
72,265,055 | 72,270,604 | How does approxPolyDP and epsilon parameter work? | Could someone give a good explanation about how epsilon works?
This is how I use it.
cv::approxPolyDP(contour, approx, cv::arcLength(contour, true) * precision, true);
As default double precision=0.02.
Somthing that doesn't make sense to me is that the lower precision is the less strict the shape detection gets?
For e... | approxPolyDP implements the Ramer–Douglas–Peucker algorithm
The algorithm does not detect shapes, it simplifies contours.
It removes points that contribute very little (epsilon) to the shape of the contour. Colinear points are a trivial case because they contribute zero to the shape of the contour. The most prominent c... |
72,265,116 | 72,265,200 | Is it safe to call <math.h> functions by reference? | Please, tell me is it safe to call math functions the following way:
map<string,double(*)<double> func_map = { {"sin", &std::sin } ... }
...
double arg = 2.9;
double res = func_map["sin"](arg);
| Taking the addresses of functions in the standard library not on the Designated addressable functions list leads to unspecified behavior (since at least C++20). std::sin and the other <cmath> functions are not on that list so, to be safe, wrap them up in functors, like lambdas:
#include <cmath>
#include <map>
#include ... |
72,265,202 | 72,265,737 | Can not call function pointer of a struct to a class method | use C++98. I have a struct t_fd which is used inside a class MS. In the struct there are two pointers to function: fct_read, fct_write. I designed that the function pointers are pointing to the two methods of the class. But then I have this error when trying to call them.
expression preceding parentheses of apparent ca... | The intent of your code is difficult to understand (in its current form). But I would be happy to solve few issues in your code.
MS class needs to be declared before you reference it the type from s_fd structure definition :
class MS; // forward declaration
typedef struct s_fd {
void(MS::* fct_read) (int);
void... |
72,265,207 | 72,265,257 | error C2679: binary '>>' : no operator found | The full error message reads:
Error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Ar<int>' (or there is no acceptable conversion)
How can I fix it?
#include <iostream>
using namespace std;
template<class T>
class Dun
{
private:
T* array{ nullptr };
public:
Dun(T* _array) : ... | You don't need pointers here
int main()
{
int a[4] = { 1, 2, 3, 4 };
Dun<int> ar{a};
Ar<int> ur{&ar};
cout << ur[1];
return 0;
}
otherwise you'd have to dereference your pointer before your operator[] can be used
cout << (*ur)[1];
|
72,265,260 | 72,265,716 | Is there a way to 'reset' a functions variables? | I recently made a function to compare an array of numbers to a single value which returns the closest value to the single value out of the array. This works perfectly well when you only use it only once but if I use it again in another instance of the code, It returns an unexpected value (usually the previous single va... | The problem isn't resetting the variables. The problem is that you are modifying the arguments passed to the function.
To prevent modifications you should use the const keyword:
double closestval (double num1, int amountofnums, const double *comps){
and then fix the errors the compilers throws at you.
If you do want t... |
72,265,277 | 72,265,754 | Can I add a different function that is defined in my code in a vector like arrays that include function adress? | In this code, there are 6 different functions. They create 6 different boards for playing a game. But I don't want to create boards with if conditions, I want to create a vector that includes function addresses in it. For example, if the user wants to create board 4 for playing the game, I want to create the board like... | What you are looking for is std::function
In your case, you'd create a vector of std::function<> for functions that take no parameter and return a vector<vector<cell>>.
#include <functional>
#include <vector>
struct cell {};
//type aliases make code a lot more readable!
using board = std::vector<std::vector<cell>>;
... |
72,265,390 | 72,266,910 | How do I pass the output of a c program which use curses/ncurses to another program? | I have a simple c program which use ncurses to display some text on the screen. When running, it will print out hello, when the user press the arrow key up, it will exit the program printing on screen bye see you soon.
I would like to be able to use the output printed by the program, in this case bye see you soon as in... | initscr does the equivalent of newterm(NULL, stdout, stdin), which pretty well makes it impossible to also pipe output into some other utility. If you want to do both, you can force ncurses to use /dev/tty for both input and output by replacing initscr() with something like:
FILE* tty = fopen("/dev/tty", "r+");
... |
72,265,398 | 72,265,489 | Type punning in a const / static initializer (building a float constant from bits) | Some languages (like Rust, Zig, GLSL, HLSL) have built-in methods to build a floating type from bits supplied as an unsigned integer. However C and C++ do not have standard functions for that.
With C99 we can use anonymous unions with member initialization to implement a type punning macro to the same effect:
#define F... | If you can use C++20 or above, then use std::bit_cast like
auto myvar = std::bit_cast<type_to_cast_to>(value_to_cast);
If you want to support older versions, you can do this same thing using std::memcpy to copy the bytes from one type to another. That would give you a function like
template <class To, class From>
To ... |
72,265,510 | 72,267,325 | Do not-precompiled headers use precompiled headers if they are Included or are they for .cpp files only? | Visual Studio 2022:
I want to Include Precompiled headers in my .cpp file but I don't know if it's worth it since I'll also need to include a non-precompiled header with almost the same headers that are in the precompiled header.
Will the non-precompiled header use the precompiled headers or will it generate the code... | Using pre-compiled headers doesn't change that much. In particular, header guards continue to work. The header guard for <windows.h> is also included in the pre-compiled state. Hence, when the compiler sees <windows.h> for the second time, it's immediately skipped.
In your case, the No-Precompiled.h header turns out to... |
72,266,252 | 72,267,263 | Showing the original index of an element in a vector after bubblesort | I'm new to c++ and i'm having a problem with my code. I need to show the original indexes of a vector before it was sorted, after sorted. I tried it like this:
#include <vector>
using namespace std;
void bubblesort(vector<int> &a, int n) {
for (int j = 0; j < n - 1; j++) {
for (int i = n - 1; i > j; i--) {... | If your goal is to show the indices of the sorted vector, then another approach is to not sort the original vector, but instead to sort a vector of index values based on the original vector.
The index vector would be initialized to 0, 1, 2, etc. up until the vector's size, minus 1.
Here is an example:
#include <vector>... |
72,266,284 | 72,266,475 | error: expected unqualified-id before ‘{’ token on Linux gcc | i get the following error message when trying to compile the following code on linux with gcc (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5) while it works on windows without problems.
...
#include "DDImage/NoIop.h"
static const char* const CLASS = "RemoveChannels";
// -------------------- Header -------------------- \\
clas... | Simple example
// -------------------- Header --------------------\\
class RemoveChannels
{
public:
int operation = 0;
};
int main ()
{
RemoveChannels r;
r.operation++;
}
when a line ends in a backslash, it is continued on the next line. That means class RemoveChannels has accidentally been commented out wi... |
72,266,480 | 72,266,905 | Can `#ifdef` be used inside a macro? | I only found this related question, which isn't quite what I am looking for.
I used to have macros defined inside an #ifdef statement:
#ifdef DEBUG
# define PRINT_IF_DEBUGGING(format) printf(format);
# define PRINTF_IF_DEBUGGING(format, ...) printf(format, __VA_ARGS__);
#else
# define PRINT_IF_DEBUGGING(...)
# ... | You can't use #ifdef inside of #define , so no, this is not possible. The first code you showed is the correct solution.
|
72,266,674 | 72,266,709 | Visual studio "module unsafe for SAFESEH image" occurring when building release in Assembly/C++ | I've been following this youtube tutorial to begin learning about Assembly: https://www.youtube.com/watch?v=W3roB5sRg4o&list=PLRwVmtr-pp05c1HTBj1no6Fl6C6mlxYDG&index=2
And everything's been going fine until I switch the build from debug to release, returning two errors: "module unsafe for SAFESEH image", and "unable to... | I found a comment saying to replace the old build command from ml /c /Cx /coff "%(FullPath)" to ml /c /Cx /coff /safeseh "%(FullPath)" (notice the addition of /safeseh), which resolved the issue.
|
72,266,810 | 72,271,884 | Correcting Node Height for BST in CPP | I just need some help adjusting the height variable of ndoes in a BST, I cannot find out what is wrong with the logic in my code.
void BST<T>::fix_height(Node* node){
Node* current_node = node;
while(current_node !=nullptr){
if(current_node ->right != NULL && current_node ->left !=NULL){
curre... | First of all, the code assumes that the children of the node that is passed as argument to fix_height have their heights already set correctly. If this is not guaranteed, then it already goes wrong there. But without seeing the context of the call of this function we must assume the function is only called on leaves or... |
72,267,542 | 72,267,606 | error: member access into incomplete type''; note: forward declaration of '' | Here is a struct MAIN which have member struct A and struct B, the code is like below
// a.hpp
#ifndef _A_HPP_
#define _A_HPP_
struct A
{
int mem1;
};
#endif
// b.hpp
#ifndef _B_HPP_
#define _B_HPP_
#include "a.hpp"
#include "main.hpp"
struct MAIN;
struct A;
struct B{
int mem2;
MAIN* main;
A *aptr;
... | The definition of the constructor B::B inside the struct definition references members of MAIN, but the latter hasn't been fully defined yet.
You need to move the body of constructor B::B into a separate file, i.e. b.cpp, and link with main.cpp when building the executable.
|
72,267,845 | 72,267,947 | Data in int* argument of function not returned caller | Compiled with g++ on WSL2, sample output of
#include <stdlib.h>
#include <stdio.h>
#include <vector>
using std::vector;
vector <int> powers_2(const int npow) {
vector <int> v;
int j = 2;
for (int i=0; i<npow; i++) {
v.push_back(j);
j*= 2;
}
return v;
}
void pow_2(const int npow, in... | There is a difference between passing function arguments by value, by pointer and by reference.
The line
pow_2(3,y,&ny);
will pass the value of y to the function pow_2, which means that a copy of the value of the variable y will be made, which will exist as the local variable v in the function pow_2. This is not what ... |
72,267,948 | 72,268,114 | how to make terminal ask for string then after string is received remove it | hi so I'm making a mini bank and I want to have the user put in the email and then once they put it in it clears and then moves to the password I'm having trouble doing that please help.
#include <iostream>
#include <windows.h>
#include <String>
#include <thread>
#include <stdlib.h>
int main() {
int money = 10000... | Have you tried using the system function from cstdlib to execute the cls command to clear the console before Asking for Password.
Example Usage:
system("cls");
So Your Code is modified as below to clear the terminal after inputting the email and password.
#include <iostream>
#include <windows.h>
#include <String>
#in... |
72,268,050 | 72,268,172 | Wrong print values while iterating 2d char array | I am trying to run this code in Arduino IDE. It is printing wrong values.
char daysOfTheWeek[7][4] = {"Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat"};
for(int i=0;i<7;i++) {
Serial.print(daysOfTheWeek[i]);
Serial.print(" ");
}
Serial.println();
Printed values
Sun Mon TuesWed Wed ThurFri Fri Sat
I see thi... | All string literals have an implicit null-terminator at the end. So, the biggest ones of yours, the "Tues" and the "Thur", are actually contain five characters, like so: "Tues\0" and "Thur\0".
Thus, you either need to increase the dimension of the character array to [5] (resulting in char daysOfTheWeek[7][5]), or you n... |
72,268,327 | 72,268,525 | I have compiled my cpp code to generate a dll file in visual studio, but I cannot find the generated dll file. Is there any default name for dll in vs | The code compiled:
#include <jni.h> // JNI header provided by JDK
#include <iostream> // C++ standard IO header
#include "HelloJNI.h" // Generated
#include <string>
using namespace std;
// Implementation of the native method sayHello()
JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv* env, jobject thisObj)
{
... | You can check the output directory macros in Properties.
|
72,268,800 | 72,270,859 | Rotate right in a BST using void | I am not implementing an AVL tree but I need to create a method that would rotate the binary search tree to right, However, I used the following code and the solution is not working.
How do I implement the rotate right method including rotating the root node and the non-root node?
void BST<T>::rotate_right(Node* node)... | There are these issues in the outer else block:
move_up_node->parent->right = node is not right, as move_up_node is node->left, and so move_up_node->parent is node, which means you actually set node->right = node, which creates a loop. What you really want here is node->left->parent = node
if(node == node->parent->r... |
72,268,845 | 72,268,943 | How is it determined which memory block to use in c/c++? | This is the code I wrote:
#include <iostream>
using namespace std;
int main() {
int x[3] = {30,31,32}, y[3] = {40,41,42}, z[3] = {50,51,52};
for (int i=0; i < 3; i++) {
cout << *(x+i) << endl;
cout << *(x-(3-i)) << endl;
cout << *(x-(6-i)) << endl;
}
cout << endl;
for (int ... |
Here you can see the array which was declared at last takes the foremost memory address and second last takes memory address after the last one and so on.
No, this is not what is happening. The program has undefined behavior because you're going out of bounds of the array for the expressions *(x-(3-i)) and *(x-(6-i))... |
72,269,321 | 72,271,702 | Prospective destructors in C++ | I have this code and this outputs the following:
link to the following example
https://godbolt.org/z/z8Pn9GsTv
template <typename T>
struct A1 {
A1() {
std::cout << "construction of a1" << std::endl;
}
~A1() {
std::cout << "destruction of a1" << std::endl;
}
~A1() requires (std::is_... | That's indeed a reported Clang bug1, as noted by Quimby.
Note that the second snippet (the one with the the constrained destructor first) doesn't really "work" in Clang, which just ignores the second destructor2.
Also note that, unlike gcc, at the moment I'm writing, Clang doesn't seem to have implemented [P0848R3] (wh... |
72,269,830 | 72,270,155 | Printing time_t in a vector struct member | Sorry, I think this might be a silly question. While trying to use ctime to print a time_t inside a vector struct member, the compiler throws me this error argument of type "time_t" is incompatible with parameter of type "const tm *"
struct Trade_Record
{
std::time_t PASP;
};
std::vector<Trade_Record> Trade_Record... | Quoting cppreference.com on the matter:
This function returns a pointer to static data and is not thread-safe. In addition, it modifies the static std::tm object which may be shared with std::gmtime and std::localtime. POSIX marks this function obsolete and recommends std::strftime instead.
The behavior may be undefin... |
72,269,958 | 72,270,009 | Issue with templated Kernel for Efficient Ransac | I am trying to use the efficient Ransac algorithm of CGAL in a function using a templated Kernel, here is a minimal code to reproduce.
#include <CGAL/property_map.h>
#include <CGAL/Point_with_normal_3.h>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Shape_detection/Efficient_RANSAC.h>
/... | The problem is that the compiler doesn't know that whether the token < that follows the add_shape_factory is a less-than-operator or a beginning of a template argument list.
We can use the .template construct when calling the member function template to solve this problem as shown below:
ransac.template add_shape_fact... |
72,270,503 | 72,272,335 | c++ reinterpret_cast char to int* / adjacent bits are repeatedly set as 1100 | Why does the second example find 1100 instead of 0000 after storing the address in the int pointer and then reading the adjacent bits?
Example 1:
char c = 'a';
int val = *reinterpret_cast<int*>(&c);
val = 97 or 0110 0001
Example 2:
char c = 'a';
int* iptr = reinterpret_cast<int*>(&c);
int val = *iptr;
val = -8589935... | Both have undefined behavior, generally already because accessing a char through a int pointer is an aliasing violation.
Even if that was allowed, the size of int will almost certainly be larger than that of char and trying to read an adjacent byte of a variable clearly causes undefined behavior.
And even further, the ... |
72,270,590 | 72,270,663 | c++ entering values two times instead of one | I have to solve this " create class for describing triangle and trapeze with ability to return values and finding S of the figures.. declare function which allows comparing S of the both figures.. in main function declare object triangle and trapeze and compare their areas .. " - im trying to translate it from Bulgaria... | For the Triangle constructor you have:
Triangle::Triangle():Trap()
{
setValueTriangle();
}
That will explicitly invoke the Trap constructor which read input. Then you will read the input for the triangle.
It's often not a good idea to read input in a constructor. It's usually better to only do basic initialization... |
72,270,600 | 72,270,677 | Fibonacci number overflow in c++ | I am a c++ newbie, and start learning it by learning algorithm at the same time. However, I encountered some problem when writing this algorithm --- the number overflows, which is quite different to the overflow I thought. To solve the problem, I searched for a long time, but end up in no use. Here is my code:
#include... | This line in your function int res = F(N - 1) + F(N - 2); makes your result an int, which is then casted to long long. so the overflow occurs here. Should be flagged by some compilers flags tho.
long long F(int N) {
if (Fs[N] != -1) {
return Fs[N];
}
// int res = F(N - 1) + F(N - 2); // HERE !
l... |
72,270,978 | 72,273,758 | Get wrong value from int* to JintArray in jni | I have a c function int* GenerateIntArray()
it will generate a int array like [0,8,28,108,0,3] and return by Int*
int* GenerateIntArray(){
int rtn[6]={0,8,28,108,0,3};
return rtn;
}
in my jni layer : fun getIntArrayFromJNI:JIntArray
I do this for get Int* from C Lib
jintArray rtn = env->NewIntArray(6);
int *temp = C_... | When you want to do that in this way, you can change your void GenerateIntArray() code to:
int* GenerateIntArray()
{
static int rtn[6]={0,8,28,108,0,3};
return rtn;
}
Because, the int array is allocated on the stack and will be disappear when the function returns.
|
72,271,018 | 72,271,519 | How to use windows api GetPackagesByPackageFamily in CSharp? | API [GetPackagesByPackageFamily] in appmodel.h
#include <Windows.h>
#include <appmodel.h>
...
WINBASEAPI
_Check_return_
_Success_(return == ERROR_SUCCESS)
_On_failure_(_Unchanged_(*count))
_On_failure_(_Unchanged_(*bufferLength))
LONG
WINAPI
GetPackagesByPackageFamily(
_In_ PCWSTR packageFamilyName,
_Inout_ UIN... | You can have a look at this library: https://github.com/dahall/Vanara/ that offers exactly that P/Invoke.
They are implementing it like that:
[DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true, CharSet = CharSet.Unicode)]
public static extern long GetPackagesByPackageFamily(string packageFamilyName, re... |
72,271,558 | 72,272,860 | use fstream to read and write in the same time | I am learning how to read and write from file . There is a problem that when I try to write (--something in the file letter for example--) after reading or read after writing in the file
using fstream
something wrong is happening. I tried to just write or read and it worked. what is the problem?
the file content is ... | Look at this answer: https://stackoverflow.com/a/17567454/11829247 it explains the error you are experiencing.
Short version: Input and output is buffered and interleaving reads and writes only work if you force buffer updates in between.
This works for me:
#include <iostream>
#include <fstream>
#include <string>
int ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.