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 |
|---|---|---|---|---|
66,786,501 | 66,786,599 | Using std::enable_if with constexpr argument for overload resolution doesn't work as expected | I'm trying to add function overload for a function template based on the type of one of the template parameters and passing an argument defined as consexpr somewhere else to aid in overload resolution.
Here's a code sample for what I'm trying to achieve:
struct use_my_impl_t {};
constexpr use_my_impl_t use_my_impl;
te... | The issue here is what T is being deduced as. In foo(42, use_my_impl_t{});, use_my_impl_t{} is an rvalue so T gets deduced as use_my_impl_t and the parameter becomes use_my_impl_t&&.
With foo(42, use_my_impl);, use_my_impl is an lvalue. That means T is deduced as use_my_impl_t & to preserve that lvalueness. That mean... |
66,786,672 | 66,788,771 | Optionally-uninitialized class: std::is_trivially_constructible seems incorrect for non-default constructor? | I feel like std::is_trivially_constructible<T, Arg> isn't telling me the truth. First, context:
I have a small-vector class, VectorND<T, N>. Default-constructing it default-constructs its members, so VectorND<float, 2>{} == VectorND<float, 2>{float{}, float{}} == VectorND<float, 2>{0.f, 0.f}. This is the desired behavi... | Short Answer
This doesn't work because this isn't how trivial constructors are defined by the standard.
Trivial has nothing to do with initialization (or lack-thereof), it's just a set of requirements that the standard lays out to define a constructor as being trivial -- a state which enables better code gen by the com... |
66,786,695 | 66,902,073 | print a list of struct | Im new and need you help !
I created a struct and would like to print it however I have difficulties.. First print function printstruct print each member of my struct and i would like the second to print each struct i add in the list...
#include <iostream>
#include <list>
#include <vector>
#include <stdint.h>
typedef... | You have passed the wrong arguments, with my fix the code works.
printstruct(i); and print(listbizar); should be right.
Note that I also changed the definition of void printstruct(const ChanAccessReq& demande) with reference argument to avoid unnecessary copy.
I also suggest you using vector instead of list for contai... |
66,787,248 | 66,787,543 | Can't get my FPS number to show with SFML |
I am making a program that needs to have my FPS counter listed on the top left of the screen. I am using SFML to output my program into a window.
I have an FPS.cpp file that contains the class for my FPS counter. There are two methods in this class, "getFPS()" and "update()".
fps.cpp
#include <SFML/Graphics.hpp>
#inc... | Did you tried to just put a plain text instead of your fps count ? You could try to check if another font would work, or just throw an error if the file does not load.
if (!font.loadFromFile("fonts/KOMIKAP_")) {
std::cout << "Error with the file" << std::endl;
}
If you have an error, just try adding a .ttf to the ... |
66,787,397 | 66,790,006 | Why is the local variable copied despite being returned by name? | In the following code snippet, the return s gives the warning local variable 's' will be copied despite being returned by name [-Wreturn-std-move]. Why is this the case?
My goal with this lambda function is to take ownership of the input string and then return it after modification through RVO or move semantics. I woul... | There's a rule that allows local variables (including function parameters) to be implicitly moved (instead of copying) when returning, if the function returns by value, and variable that's being returned has the same type as the return type.
The warning tells you that such implicit move will not happen in this case, be... |
66,787,539 | 66,788,875 | Rational Zero Theorem in C++ | So I've been trying to make a program which asks for the coefficients of a grade 3 polynomial function, returns the factors of the first and last coefficient, and then applies the theorem to list the possible cero rationals of the function
I have managed to ask for the coefficients, and list the factors, but I'm having... | This is not a full solution, but should give you an idea of how to start:
// Notice I am passing the integer values of p and q in here.
// We could just pass the decimal fraction instead.
bool ZeroCheckFunction(int a, int b, int c, int p, int q);
...
if(a>d)
{
for(int i=1;i<=a;i++)
{
if (a%i==0)
{
... |
66,787,752 | 66,788,238 | Difficulties while trying to delete a dynamic array | I am trying to create my own array within a class, with functions to insert into it, delete etc.. My array has capacity - max array's size, size - how many elements it holds, *data - a pointer to data. So when the user tries to insert an element and the array is full, the capacity would double in my resize() function, ... | In resize, the delete[] newData; statement deletes the memory you just allocated, leaving data as a dangling pointer because it now points at memory that has been deallocated.
The solution is to remove the delete[] newData; statement from resize.
You should also add code to the destructor to free up the memory you've a... |
66,787,921 | 66,794,118 | How to add a UFunction to an interface's delegate with parameters in UE4 C++? | I am looking use web sockets in Unreal. I am following the tutorial found here: Web Socket Tutorial
Most notably I am trying to bind to the events before connection. In the example, they use .AddLambda however, I would like to try to use .AddUFunction. It seems the function takes in the Object, the function name, and V... | Works for me!
SandboxGameInstance.cpp
#include "SandboxGameInstance.h"
#include "WebSocketsModule.h"
#include "IWebSocket.h" // Socket definition
void USandboxGameInstance::Init()
{
Super::Init();
FWebSocketsModule& Module = FModuleManager::LoadModuleChecked<FWebSocketsModule>(TEXT("WebSockets"));
c... |
66,787,962 | 66,821,483 | C++ WindowsApp LNK2028Error | When I compile the following code in Visual Studio 2019 I receive the following error code: code of the error output. It seems to be a LNK2028 error but I do not understand what is happening. Can someone explain why I receive this error?
Here is my code:
#include "MyForm.h"
#include <windows.h>
#include <windowsx.h>
#i... | As mentioned in this and this post it seems like the issue is due to a linker error which is caused by (I believe 8 function calls) that are depending on libraries implemented by the User32.dll located in C:\windows\system32 more info about this.
In this current project it seems like you are missing to include addition... |
66,788,078 | 66,788,388 | QT Creator accessing pointers to objects | Very new to QT but basically I have a class called object and on my GUI is a one button and one text browser. Now in my class object I have one private QString variable called name and its constructor assigns a value (QString) to the variable called name . The object class has one function called QString getName() cons... | The pointer (o) outlives the object that it points to (o2). One way to fix it is by allocating new memory for the object:
o = new object("Name");
And then you'll need to remember to delete that memory later.
|
66,788,851 | 66,788,957 | How to cout int like a double | I'd like to display some integer with currency index (I mean dot and double zero)
For example like here:
#include <iostream>
int main() {
int w1=700,c1=99,c2=98;
double noh2o=w1*(100.0-c1)/100.0;
double w2=noh2o+noh2o/(100.0-c2)*c2;
std::cout<<w2<<std::endl;
}
If somebody can help me I will be thankfu... | Use std::fixed and std::setprecision.
Try it online!
#include <iostream>
#include <iomanip>
int main() {
int w1=700,c1=99,c2=98;
double noh2o=w1*(100.0-c1)/100.0;
double w2=noh2o+noh2o/(100.0-c2)*c2;
std::cout << std::fixed << std::setprecision(2) << w2 << std::endl;
}
Output:
350.00
|
66,789,087 | 66,789,174 | Make ++o++ complain for types with user defined pre- and postfix increment operators | I'm looking for a way to prevent ++x++ from working for types with user defined prefix and postfix increment operators.
For builtin types the result type of the postfix operator is not an lvalue but a prvalue expression and the compilers complain nicely.
The simplest thing i can think of is to return const for the post... | You probably want S& operator++() & and S operator++(int) &. You're missing the & at the end that makes the operators only work on lvalues.
|
66,789,377 | 66,789,544 | Passing std::unique_ptr to a function by using a variable that is already created using new X() | I am new to C++ and have some confusion regarding what happens in the following 2 scenarios.
I create the variable using new key word and then pass that variable as std::unique_ptr<>(x) to a function. When I do this, I can still access this->handler_ from the class that I passed.
Note: Y is the super class of X
this... | In the first case, this->handler_ ends up containing a pointer that it does not own (the unique_ptr owns it, and will delete it when the unique_ptr is destroyed unless it's extracted from the unique_ptr manually). If anything tries to delete this->handler_ (e.g. what the destructor would do normally on reasonable class... |
66,789,487 | 66,791,846 | Do all transient allocations have unique address? | While reading comments of a C++ Weekly video about the constexpr new support in C++20 I found the comment that alleges that C++20 allows UB in constexpr context.
At first I was convinced that comment is right, but more I thought about it more and more I began to suspect that C++20 wording contains some clever language ... | The result here is implementation-defined. res1 could be false, true, or ill-formed, based on how the implementation wants to define it. And this is just as true for equality comparison as it is for relational comparison.
Both [expr.eq] (for equality) and [expr.rel] (for relational) start by doing an lvalue-to-rvalue c... |
66,789,902 | 66,790,900 | is there any way to adopt a memory resource for a vector? | I have started using pmr::allocators in my project, and I have seen a lot of performance boost and advantage from using them. I use allocator very similar to what I show int the simple example below:
#include <array>
#include <boost/container/flat_map.hpp>
#include <cassert>
#include <iostream>
#include <memory_resourc... | What you want is not to adopt the memory resource - because you can and do - but to also store the vector itself there.
You can, e.g. using a helper to create unique_ptr's with custom deleters:
template <typename T>
inline static auto make_T(Mem& mem) {
std::pmr::polymorphic_allocator<T> alloc(&mem);
return std... |
66,790,033 | 66,790,237 | Assigning a int to a double& | I would like to understand why this doesn't compile:
int main()
{
int a = 1;
double& b = a;
std::cout << b;
}
While using double const& b = a instead of double& b = a works fine.
| A double and an int have different alignment requirements and different representation in memory. Reading a variable as one type through the eyes of another type would also make your program have undefined behavior.
When you do something like
int a = 1;
double b = a; // note, not a reference
then a is implicitly conv... |
66,790,109 | 66,790,400 | c++ program, text constantly shaking in cmd | This program is supposed to have a map made out of dots and a player which you can move around.
But when I opened this program one day, the text was flickering and moving up and down.
It uses Windows.h to redraw on the console without flickering and to hide the cursor
Does it have to do something with the cmd propertie... | In the DrawMap method, when you have the two for loops, you are checking width in the outer loop and height in the inner loop, while it should be the other way round. Note that the outer loop controls the number of lines, and as you are limiting it to the width (100) you are displaying 100 lines most of which are empty... |
66,790,318 | 66,790,369 | std:hash with access to private members of a class | I would like to hash a class that has two private members e.g.:
foo.h
class Foo {
private:
std::string a;
std::string b;
public:
Foo (std::string a, std::string b);
bool operator==(const Foo& other) const;
bool operator!=(const Foo& other) const;
std::size_t oper... | What you can do is declare std::hash<Foo> as a friend of Foo:
class Foo {
private:
std::string a;
std::string b;
public:
Foo(std::string a, std::string b);
bool operator==(const Foo& other) const;
bool operator!=(const Foo& other) const;
std::size_t operator()(const Foo&) const;
friend std::hash<Foo>;... |
66,790,395 | 66,790,737 | Partial template specialization with second template type | Its simplified version of my real problem. Why in the first case template specialization doesn't work?
If I swap first two functions then it will work.
Strange, but it works with msvc 19...
#include <string>
#include <vector>
#include <iostream>
template<typename T, typename M>
void write_impl(T &result, M m) {
fo... | The first case isn't a case of template specialization; it's function overloading.
Doesn't works because the first function call the second one that isn't declared. Switching the order, as you can see, works because the first (now second) know the declaration (and the definition too) of the second (now first).
You can'... |
66,790,637 | 66,790,856 | How to find Minimum Cost Path in a directed graph | I was researching code about finding Minimum Cost Path in a directed graph online and I came across this code in geeksforgeeks here is the code.
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Stores minimum-cost of path from source
int minSum = INT_MAX;
// Functio... | minPathSum is implemented incorrectly. Seems as if it was improperly refactored at some point and was not even attempted to be compiled.
The lone visited occurrences should be visited[source]. and for (auto node : graph) should be for (auto node : graph[source]). Altogether:
void getMinPathSum(unordered_map<int,
... |
66,790,730 | 66,790,924 | Confused on why i have an std::logic_error in my hashtable code | I'm trying to show the index structure of my hashtable by organizing a struct "Student" by age. I don't know how to debug what I have because all I'm left with when trying to run the code is:
"terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_M_construct null not valid"
which I d... | Immidiate problems:
You calculate the number of elements in array erroneously.
int n = sizeof(array) / sizeof(array[0].age);
should be
auto n = sizeof(array) / sizeof(array[0]);
or better
auto n = std::size(array);
You don't delete[] HT; in the destructor
~Hash() {
delete[] HT;
}
I recommend using a std::v... |
66,791,163 | 66,791,700 | OpenGL -- Explicit specialization in non-namespace scope -- Function templates | Recently I was learning OpenGL basics from YouTube and while I was working with VS C++ compiler, everything worked like a charm, but since I moved to Clang I get error "explicit specialization in non-namespace scope" from the code below:
class VertexBufferLayout{
private:
std::vector<VertexBufferElement> m_Elements... | The error says that it wants you to provide the specialization at a namespace scope. This compiles:
class VertexBufferLayout{
std::vector<VertexBufferElement> m_Elements;
public:
VertexBufferLayout(){}
template< typename T >
void Push(GLuint count){}
};
template<>
void VertexBufferLayout::Push<GLfloat... |
66,791,493 | 66,791,545 | when I use the c++ STL sort function in string sort,there is some problem | C++ code
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <fstream>
using namespace std;
int
main ()
{
vector < string > elem (4);
ifstream infile ("test.txt");
if (!infile)
{
cerr << "Oops! unable to save session data !\n";
}
int i;
for (i = 0; infile >> ele... | Your usage of std::sort is C-ish. You have to supply iterators to begin/end, i.e., write something like
sort(elem.begin(), elem.end());
Besides, your program will crash if the test.txt file is more than 4 lines (trying to read into non-existent elem[4]).
Be careful though, check that the default comparison does what y... |
66,791,884 | 66,791,921 | Math: How to optimize this if so it looks cleaner and faster? | This solution looks ugly. I've tried to simplify using a vector and cycling a vector but would it be faster? I tried making up a formula to retrieve these numbers but I'm terrible at math!
if (SkillValue > 115 && SkillValue <= 135)
{
return 100 / 2;
}
else if (SkillValue > 135 && SkillValue <= 160)
{
return 100... | There doesn't appear to be any pattern to the bounds for each if condition, or at least any pattern that would let you write this as a closed form check.
However, you are currently checking all the if conditions, which is O(n) where n is the number of conditions. You can do this in O(log(n)) by using std::lower_bound o... |
66,792,095 | 66,792,256 | How do you specialize a member function inside a template class? | Let's say I have the following class:
template <typename T>
class SomeClass : Parent<T>
{
public:
// I have a function such as this one:
T DoSomething(const T &t)
{
return t.DoSomething(some_data);
}
// But `T` might be a pointer, so sometimes I will need something like the following
//... | You can avoid writing any specializations, and use a type trait like std::is_pointer along with if constexpr to decide what code to execute depending on the whether the type is a pointer type or not:
auto DoSomething(const T &t)
{
if constexpr (std::is_pointer_v<T>)
return new T(t->DoSomething(some_data));
el... |
66,792,498 | 66,800,976 | How to add OpenMp to triple nested for-loop | The goal is to add as much OpenMP to the following Cholesky factor function to increase parallelization. So far, I only have one #pragma omp parallel for implemented correctly. vector<vector<double>> represents a 2-D matrix. I've already tried adding #pragma omp parallel for for
for (int i = 0; i < n; ++i), for (int k ... | I don't think you can parallelize much more than this with this algorithm, as the ith iteration of the outer loop depends on the results of the i - 1th iteration and the kth iteration of the inner loop depends on the results of the k - 1th iteration.
vector<vector<double>> cholesky_factor(vector<vector<double>> input)
... |
66,792,890 | 66,792,920 | Why string data is not moved to target but vector was | I have below code:
class string
{
std::string data;
public:
string()
{
data = "Hello";
}
string(const string& that)
{
data = std::move(that.data);
std::cout << data << " and that.data " << that.data;
}
};
int main()
{
std::vector<int> vec = { 1, 2, 3, 4, 5 };
... | You're declaring the parameter that as const. As the result, data = std::move(that.data); calls the copy assignment operator, not move assignment operator. Move operation is supposed to perform modifications on the object to be moved, which shouldn't be const.
You could change the parameter type to rvalue-reference (to... |
66,793,431 | 66,793,765 | Why does the output of my count change depending on whether or not I utilize std::cout? | I feel like I'm going crazy. I am trying to test logic for a bitmap I am implementing which is used to track frames in memory.
int main(){
unsigned char mask = 192; //1100 0000
unsigned char* bitmap;
bitmap[0] = 0x80;
bitmap[1] = 0xC8;
bitmap[2] = 0x2F;
bitmap[3] = 0x0;
int num_frames = 16;
int frame_size_in_bits = 2;
... | You never allocated memory to "char* bitmap"
in C you can do it like
char *bitmap= NULL; /* declare a pointer, and initialize to NULL */
bitmap= malloc (5 * sizeof *bitmap);
in C++
unsigned char* bitmap= new unsigned char[4];
int main(){
unsigned char mask = 192; //1100 0000
unsigned char* bitmap= new unsigned cha... |
66,793,795 | 66,797,241 | How to call class A's method 1 which invokes class B's method 2 in C++? | I have a base class A and hope to create a class B with very similar functionality. I want class B to have a function to call class A's func1(), but when calling it, the func2() is replaced/over-rided by class B's func2(). My goal is to avoid repeated code and not modify class A. The inheritance implementation below do... | You should use virtual function for that. When a function is declared as virtual, the compiler only uses the implementation of the virtual function that is present in the derived class.
The function in the base class cannot be used directly from the base class. As in, if you create an object for the class A, you won’t ... |
66,794,280 | 66,794,404 | C++ String input in Vector | I want to input multi-word strings into vector "name". Using cin works fine for single word inputs.
What i want is :
Take number of string inputs from the user. for example : "Random Name"
Store all the String value into the vector names
Here is the code i wrote
#include <iostream>
#include <vector>
using namespace s... | Try this:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<string> names;
string user;
int n;
cout << "Enter number of Users : ";
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> std::ws;
getline(cin,user);
names.push_back(user);
}
... |
66,794,703 | 66,795,353 | Why the return view of C++20 range adaptors is not a constant expression? | Consider the following code:
#include <ranges>
int main() {
constexpr int a[] = {1, 2, 3, 4};
constexpr auto r = a | std::views::take(3);
static_assert(*r.begin() == 1);
}
msvc accept it, gcc rejects it with:
<source>:5:44: error: 'std::ranges::take_view<std::ranges::ref_view<const int [4]> >{3, std::ranges::re... | The ranges bit is a red herring. It can be boiled down to this
int main() {
constexpr int a[] = {1, 2, 3, 4};
constexpr auto r = a ;
}
We cannot form a constexpr pointer to the first element of a. Such pointers are constrained to hold only the addresses of objects with static storage duration. The view object (as ... |
66,794,843 | 66,795,500 | Why destructor is not called? | I wrote two programs to understand the concept of copying objects.
First one:
#include<bits/stdc++.h>
using namespace std;
class myInt
{
int x;
public:
myInt()
{
cout<< "default constructor is called" << endl;
}
myInt(int x)
{
cout<< "constructor is called with initializer" << e... | As pointed out in the comments, due to copy elision, creating temporaries may be omitted when they are only used to initialize another object. Compile your code with -fno-elide-constructors to turn it off and you will read destructor is called four times. Here is a demo.
However, in c++17 things are different. It gua... |
66,795,198 | 66,795,589 | How to use strptime(fromdate.c_str(), "%Y-%m-%d %H %M %S", &tm); on windows | I have a code that works fine on windows, and I have to make it compatible with Linux.
Can anyone help me configure the following code snippet to windows?
MongoDB* db = MongoDB::getInstance();
mongocxx::pipeline p{};
struct tm tm;
strptime(fromdate.c_str(), "%Y-%m-%d %H %M %S", &tm); //this line gives m... | If you can't get the BSD version of strptime working, you could try Howard Hinnant's date.h
Or you could create a simple conversion function for this particular format yourself. Example:
#include <cstdio>
#include <ctime>
#include <cerrno>
#include <iostream>
#include <stdexcept>
#include <string>
#include <string_view... |
66,795,605 | 66,795,882 | Sorting a 2D vector in C++ | I was trying to sort a two vector first based on values of 1st column and then sort the 2nd column of the sorted vector based on the corresponding values of first column. That is first sort 1st column in decreasing order then sort 2nd column in increasing order where corresponding values of 1st column are same . Exampl... | The problem is that you cannot use 2 compare functions and sort it twice, that will revert the first sort. Why don't you do it in 1 step?
bool sor_col(const vector<int> &v1, const vector<int> &v2){
if(v1[0]>v2[0]) return true;
if(v1[0]<v2[0]) return false;
return v1[1]<v2[1];
}
Sorting for the first value ... |
66,795,710 | 66,795,785 | Reverse Iterator not working as expected C++ | Hey i was wondering why this code doesnt give 1 to output.
vector<int> myVector{1, 2, 3, 4, 6};
cout << *myVector.rend() << endl;
Output should be 1 but it gives random numbers.
But in this example everything is okay.
vector<int> myVector{1, 2, 3, 4, 6};
cout << *myVector.rbegin() << endl;
Output ... | end() points to the memory location after the last element. Similarly, rend() points to memory location before the first element. They are supposed to be used as sentinel values ─ i.e. to iterate until that point is reached.
So, to print 1, you should use:
cout << *(myVector.rend()-1) << endl;
|
66,795,799 | 66,795,953 | Sum series using function and loop (C++) | I am writing some code that prints out a sum series using a loop and a function.
I intend the equation to look like this
m(i) = (1/2) + (2/3) + ... (i / i + 1)
The problem is that my code always gives me incorrect answers and not printing what it's supposed to. For example, when I input 1 into 1 the answer should be 0.... | What you want is:
void sumSeries(int x){
double sum = 0;
for(int i = 1; i <= x; i++){ // include i in the list
sum += static_cast<double>(i)/(i + 1); // force the operation as double
}
cout<<sum;
}
|
66,796,737 | 66,810,420 | build chromium on Mac then I got cannot execute binary file | I am trying to build Google Chromium on a Mac.
To get Chromiumum I did the following steps:
fetch chromium on a Google Cloud Ubuntu Server.
git fetch origin tag <tag> on the server.
Zip the downloaded source and then download the zipped source to my local machine
Unzip the source on my local machine.
This process is ... | It works, I found a solution.
I remove src/third_party/llvm-build directory, then gclient sync again.
It will download executable clang program.
thx everybody.
|
66,797,170 | 66,797,986 | complex number wrong output | I write this code with a class named Complex with the following methods:
a. Complex() // Default constructor returning 0
b. Complex(float im, float real)
c. float getImaginary() const
d. float getReal() const
e. Complex add(const Complex& rhs) const
f. Complex subtract(const Complex& rhs) const
g. Complex multiply(cons... | 3 issues in your code:
Complex::Complex(float realpart, float imaginarypart)
{
SetReal(realpart);
SetImaginary(imaginarypart);
}
causes the warning:
<source>:24:28: warning: unused parameter 'realpart' [-Wunused-parameter]
24 | Complex::Complex(float realpart, float imaginarypart)
|
Fix it b... |
66,797,326 | 66,797,766 | (C++) How can I keep track of how many objects of a class I declare? | Let's say I have a class like this one, and I want to keep track of how many employees there are and who they are using an account number system. I want to know if this is a dumb idea or if this is good, just not (so far) implemented correctly.
class Employee {
private:
long int accountNumber;
static int currentTot... | Depends a bit on what you want to achieve:
a. Keep track of how many objects of a specific class (here: employee) are currently instantiated. You would implement a static member counter that's incremented in all constructors and decremented in the destructor.
b. Keep track of how many employees your company has (which ... |
66,797,808 | 66,797,916 | Is it good practice to use unique_ptr as an alternative to my own move constructors? | I'm making a card game using C++. It's similar to solitaire, i.e. there are different stacks and piles and the cards are moved from one to another.
I'm using std::vector for the various piles, but instead of std::vector<Card>, I'm using std::vector<std::unique_ptr<Card>>. My rationale for doing this is that:
It ensure... |
It ensures that the ownership responsibility is with the vector that it is currently in.
This makes little sense to me. Vector owns all its elements, so unique pointer adds nothing of value in this regard.
It makes sure that I never accidentally have more than 1 copy of the same card when transferring between sta... |
66,798,653 | 66,798,728 | What is wrong with my template specialization? | I want to provide several conversion functions that transform my custom struct into other types. These functions should be overloaded by the return return type. I have tried template specialization like follows.
I get this compiler error message:
class cv::Rect __cdecl convert<class cv::Rect >(struct MyRect const &)" ... | Full specializations are no longer template functions, so no longer implicitly inline.
You have to add inline
template<> inline cv::Rect convert<cv::Rect>(const MyRect& r)
{
return cv::Rect(r.lux, r.luy, r.width(), r.height());
}
or split declaration in header and definition in cpp file
// Declaration: in header
t... |
66,798,968 | 66,829,273 | How much abstraction do I need for my code to be properly testable? | I'm currently working on an language interpreter, more specifically on the data model of that language, my data model should be able to understand expression and interpret them eg: "cos(a + 4)" should be interpreted as the cosinus of the value in the variable a plus 4, I'll keep this example to explain my how it works.... | That depends on the actual code and on your personal preference. Splitting the parser up into several stages or modules sure makes testing and mainting easier. How much modularization makes sense for you is not something that can be answered by anybody but you. If you choose the granule of your modules and it turns out... |
66,798,972 | 66,799,288 | How do I double each character in a file? | #include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define FILE_READ "prive.txt"
int main() {
FILE * filp;
int count = 1;
char c;
filp = fopen(FILE_READ, "r");
if (filp == NULL)
printf("file not found\n");
while((c = fgetc(filp)) != EOF) {
for (int... | This program opens the file input.txt and prints each character twice into output.txt. That also means that each line break is duplicated though.
Example of the input.txt file:
Hello, World!
Example of the output.txt file:
HHeelllloo,, WWoorrlldd!!
Using <iostream> and <fstream>
#include <iostream>
#include <fstream... |
66,799,309 | 66,799,539 | What is the simplest way of filling in a map within a map that contains `std::variant` in C++? | So I want to have a variable that is of type map < string, map<string, variant<bool, vector<int>>> > args.
How can one go about filling this in, not just on the first level (i.e. the first map) but the second level (i.e. the second map) which in fact is of type std::variant which doesn't support the typical args['level... | The problem here is that braced initialization lists will not survive a trip through a forwarding reference that's used to construct a variant.
You'll have to be a little bit more explicit:
#include <variant>
#include <map>
#include <string>
#include <vector>
std::map <std::string, std::map<std::string,
... |
66,799,371 | 66,799,573 | How to print all permutation using backtracking? | This code prints all the permutation of N-1 items. But I could not understand one thing:
when n=N, it is returning where it is called and make flag[n-1] = false. Thus, i = N-1 and breaks the loop. But how is the rest of the permutation printing or returning when n=N-2 to 0?
void perm(int n) {
if (n == N) {
... | You need to consider that function calls ended up nested.
Each indentation below shows a nested call:
main()
entering perm(0)
entering perm(1)
i = 0
entering perm(2)
let's say N is 2, this will print and return
now perm(1) continues
i becomes 1
... |
66,799,396 | 66,799,587 | Concatenate function calls with a template lambda C++20 | I have a template function that concatenates function calls:
template<typename Callable, typename... Callables>
decltype(auto) concat_callable(Callable callable, Callables... callables)
{
if constexpr (sizeof...(callables) > 0) {
return [=]
<typename... Args>
(Args&&... args) {
r... | Add -> decltype(auto) as trailing return type to lambda. Without this, reference from return type is discarded.
return [=]
<typename... Args>
(Args&&... args) -> decltype(auto) {
return callable(concat_callable(callables...)(std::forward<Args>(args)...));
};
Invocation concat_callable with f1,f... |
66,799,707 | 66,801,272 | What does a for statement with an ellipsis after the keyword 'for' do? | I have seen this code:
template <class... TYPES>
constexpr void tuple<TYPES...>::swap(tuple& other)
noexcept((is_nothrow_swappable_v<TYPES> and ...))
{
for...(constexpr size_t N : view::iota(size_t(0), sizeof...(TYPES))) {
swap(get<N>(*this), get<N>(other));
}
}
What does the construct for... do?
| This is not standard C++ as of 2021.
This is a proposed syntax (named an ‘expansion statement’) meant for what can be described as a more-or-less loop analogue of if constexpr: a compile-time loop construct, unrolled syntactically. Its advantage over ordinary loops is that it allows iterating over heterogeneously-typed... |
66,799,917 | 67,063,214 | Shared Variable in pthread | #include<iostream>
#include<pthread.h>
#include<chrono>
struct Arg1{
int x,y;
};
void * process(void * threadarg){
int x,y;
Arg1 * myArg1;
myArg1 = (Arg1 *) threadarg;
x = myArg1->x;
y=myArg1->y;
int i=0;
while(i<500){
x+=1;
y+=2;
i++;
}
myArg1->x=x;
... | Unless we use a mutex or some method to ensure atomicity of write, we can not guarantee that we would get a correct value in pthreaded applications. This is because, simultaneous writes can lead to a race condition, with only one of the write affecting the shared variable.
|
66,800,168 | 66,800,477 | c++ std::map `emplace` and `emplace_back` overloading | My problem is the following:
I have a pair of functions:
using my_map_t = std::map<int, double>;
using my_map_iterator_t = my_map_t::iterator;
my_map_t my_map;
...
void func1(int a, double b) {
...
my_map.emplace(a, b);
...
}
void func2(int a, double b, my_map_iterator_t hint) {
...
my_map.emplac... | You might factorize with a common method:
template <typename F>
void func_impl(int a, double b, F emplacer)
{
// ...
emplacer(my_map, a, b);
// ...
}
void func1(int a, double b) {
func_impl(a, b, [](auto& my_map, int a, double b) { my_map.emplace(a, b); });
}
void func2(int a, double b, my_map_iterator_t hint... |
66,800,315 | 66,800,738 | Can I manually access fields by their raw offset in C++? | Does the following snippet utilize undefined/unspecified/etc. behavior?
#include <cstddef>
#include <iostream>
#include <string>
class Test {
std::string s1{"s1"}, s2{"s2"};
std::ptrdiff_t offset = (char*)(&s2) - (char*)(this);
public:
std::string& get() { return *(std::string*)((char*)(this) + offset); }
... | Your proposed solution contains multiple instances of Undefined Behavior related to pointer arithmetic.
First (char*)(&s2) - (char*)(this) is Undefined Behavior. This expression is governed by expr.add#5. Since the pointers aren't nullptr and they don't point to elements in the same array, the behavior is undefined.
Se... |
66,800,562 | 66,800,795 | How do i name a tab/column in CPP? | I'm a new coder. Not really a coder yet just a freshman(1st semester) varsity student. So please forgive me if this is a stupid question....
how do i name a tab or column in cpp? I'm to make a program that collects names of students in my class along with their emails, phones and cgpas... i have to print the code in a ... | Before you print the student informations:
cout<<"Name\tEmail\tPhone\tcgpa\t"<<endl;
There are columns only because you are printing out some. There will be headers if you print out some.
|
66,800,751 | 66,801,442 | Calling a pointer-to-member function from a struct array | I'm running into what seems like a syntax problem.
Looking at the other StackOverflow answer doesn't give me an answer applicable to my problem.
At least not one which I can understand.
My scheduler class:
#define MAX_TASKS 10
typedef struct taskProps {
int interval;
int elapsedTime;
int (Controller::*task... | When you want to call a member function pointer the syntax you use is
(object_of_type_mem_func_pointer_points_to.*function_pointer)(parameters)
or
(pointer_to_object_of_type_mem_func_pointer_points_to->*function_pointer)(parameters)
Unfortunately, (scheduledTasks[i].*taskFunction)() isn't going to work, as taskFuncti... |
66,801,021 | 66,802,415 | Using bit operations to fill an int set | Let's say we have a function in a form of void Fill(char *in, int *out) in C++ that is supposed to read binary sequences of 5 characters from char *in, convert them to int = i and switch int *out's ith place from 0 to 1.
Example: char *in is:
' 00101 10010 ', so the values are 5 and 18.
int *out is primarily empt... | I have come up with an idea!
void Fill(char *in, int *out, int i){
if(*(in+i) != '\0'){
if(*(in + i) != ' '){
int temp_int = 1;
if(*(in + i) == '1')
temp_int <<= 16;
i++;
if(*(in + i) == '1')
temp_int <<= 8;
i++... |
66,801,383 | 66,802,008 | node js callback from native C++ code is throwing errors | I am trying to implement event listeners. Node js will subscribe to the events (using C++ function). When the event occurs, C++ should inform node js.
JS code:
pal.subscribeEvent("ONSTATECHANGE", function(a) { console.log("Event received for ONSTATECHAN";});
function kcb (a) {
console.log("KCB .....ONSTATECHAN"+JS... | Napi::Env doesn't have a default constructor so your deviceNapi struct's default constructor cannot initialise the env member so the compiler didn't generate it, but you try to call it on this line:
deviceNapi obj;
You can fix this by initialising it like this:
deviceNapi obj = {env, info[1].As<Napi::Function>()};
|
66,801,942 | 66,947,335 | C++ Error: Undefined Reference When Initializing a Class Object | This is my first step into the world of C++. I am experimenting with a simple program that is using a class. The program is to prompt the user for a username and age, then create a class object with the given data and then return the greet method which takes in the class object of Person and returns a greeting. Howe... | As pointed out by Drew and Useless, I needed to compile my program first to resolve the error. I compiled the program and it ran smoothly.
|
66,802,124 | 66,802,194 | Is there an efficient way to initialise the size of a multidimensional vector when only known at runtime? | I have a class that has a 3D vector as one of it's variables. This size of this vector won't be known until runtime. Is there an efficient way to initialise this vector?
For example, my class may be
class Foo {
public:
std::vector<std::vector<std::vector<float>>> x;
std::vector<std::vector<std::vector<float>>>... | This is how you could do it (but don't miss to read the end):
#include <vector>
class Foo {
public:
std::vector<std::vector<std::vector<float>>> x;
std::vector<std::vector<std::vector<float>>> y;
std::vector<std::vector<std::vector<float>>> z;
int ni;
int nj;
int nk;
using inner_type = s... |
66,802,132 | 66,802,340 | How to compare two std::any? | There's no operator== for std::any
Am I missing something obvious or do I need to actually earn my living?
Is there some simple way to provide the operator?
https://godbolt.org/z/rdoWrcnTs
// Example program
#include <iostream>
#include <string>
#include <any>
int main()
{
auto str1 = std::make_any<std::string> ("... | There's no direct way to compare two objects of std::any because the underlying types may not be the same. If you know they're the same, you can write:
if(std::any_cast<std::string>(str1) == std::any_cast<std::string>(str2))
// ...
|
66,802,137 | 66,803,259 | Printing addresses with 0x notation | Currently when I print an address of a variable,
cout << &a, its displayed as a simple hexadecimal number, let's say: 008FFBB8.
How can I print an address with the 0x notation? e.g. 0x6FFDF4.
I tried doing:
cout << hex << &a;
but it doesn't seem to work.
| There are many different solutions, the first two that came into my mind are the following:
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
int main()
{
std::cout << std::hex
<< "showbase: " << std::showbase<< 42 << '\n'
<< "noshowbase: " << std::noshowbase << 42 ... |
66,802,369 | 66,802,413 | How to replace the using pattern in specialization for template template argument | I have this chunk of code that is a common pattern to do template specialization. To remove the requirement of specifying DataType1 for Processor1<DataType1> in the first line of main function, I want to receive a template template argument instead. Looks like the using directive does not support assigning an "open" te... | Processor1 is not a type, you probably mean
template<>
struct FindDefaultProcessor<DataType1>
{
template <typename U>
using type = Processor1<U>;
};
and you need extra keyword template:
template<class TResult,
template<class> class TProcessor = FindDefaultProcessor<TResult>::template type>
... |
66,802,814 | 66,803,543 | Using Boost::Asio for http client connection with my RestAPI server, things are good but somehow 1/20 times I hit with heap corruption | Below is code snippet from the actual code base. Please assume host, port, ioc, all are available and initialized.
// Connection establisher class
class CSSLConn: public std::enable_shared_from_this<CSSLConn>
{
:
:
};
// Class for maintaining the thread pool
class CHttpClient
{
// vector to hold connction o... |
I see multiple shared objects being accessed from multiple threads
without any synchronization in place:
void WorkerThread() {
auto client = std::make_shared<CSSLConn>(ioc, m_ctx, sHost, sPort);
client->connect(sHost.c_str(), sPort.c_str());
m_sslConnObj.push_back(client);
ioc->run();
}
Here m_sslConn... |
66,802,837 | 66,810,115 | C++ Winapi - How to draw a fill shape rectangle and set the border thickness? | I'm trying to draw a rectangle with a border.
RECT rect;
GetClientRect(hwnd, &rect);
FillRect((HDC)wParam, &rect, CreateSolidBrush(RGB(0,0,0))); //black fill
FrameRect((HDC)wParam, &rect, CreateSolidBrush(RGB(255,0,0))); //red border
The above code works, though I'm not actually sure if that's the ... | If GDI+ is allowed then this is how I'll do it
int width = 100; //set the width.
int height = 100; //set the height.
int borderSize = 5; //set border size.
HDC hdc = GetDC(hwnd); //don't forget to release later when done.
Graphics g(hdc);
SolidBrush brush((Color(255, 241, 103... |
66,802,843 | 66,803,098 | Is there a way to parallelize a lower triangle matrix solver? | The goal is to add OpenMP parallelization to for (i = 0; i < n; i++) for the lower triangle solver for the form Ax=b. Expected result is exactly same as the result when there is NO parallelization added to for (i = 0; i < n; i++).
vector<vector<double>> represents a 2-D matrix. makeMatrix(int m, int n) initializes a ve... | You could try to assign the outer loop iterations among threads, instead of the inner loop. In this way, you increase the granularity of the parallel tasks and avoid the reduction of the 's' variable.
#pragma omp parallel for
for (int i = 0; i < n; i++){
double s = 0.0;
for (int j = 0; j < i; j++){
... |
66,803,489 | 66,803,941 | Problem with esp8266 sending large JSON Document via MQTT | I developed a little application that read data from a sensor, store them in SPIFFS memory of my wemos D1 mini (esp8266) and then create a JSON Document and send it via MQTT to my topic. The problem is that as long as I send a JSON Doc with 10 object everything works great, but when I increase the size of the doc over ... |
I search the internet for wdt error but I don't get what they are and how to solve my problem
WDT stands for a Watch Dog Timer. https://os.mbed.com/cookbook/WatchDog-Timer#:~:text=A%20watchdog%20timer%20(WDT)%20is,a%20software%20or%20hardware%20fault.
A watchdog timer (WDT) is a hardware timer that automatically gen... |
66,803,785 | 66,804,454 | Incremental by kernel thread | Let’s say that I want to increment a property var incremental:Int32 every time a kernel thread is executed:
//SWIFT
var incremental:Int32 = 0
var incrementalBuffer:MTLBuffer!
var incrementalPointer: UnsafeMutablePointer<Int32>!
init(metalView: MTKView) {
...
incrementalBuffer = Renderer.device.makeBuffer(bytes... | The reason you are seeing this problem is because ++ is not atomic. It basically comes down to a code like this
auto temp = incremental;
incremental = temp + 1;
temp;
which means that because the threads are executed in "parallel" (it's not really true cause a number of threads forms a SIMD-group which executes in ste... |
66,804,089 | 66,804,141 | How to create a vector of unique pointers of a class | I am looking at a code which uses new and delete to create pointers for classes and I am trying to update the code to use unique pointers. Here is my code.
#include <iostream>
#include <memory>
#include <vector>
class Algorithm
{
private:
public:
virtual void runn_algo() = 0;
virtual ~Algorithm... | As the error message indicates, unique_ptr doesn't have a copy constructor and so cannot be passed by value to a function. You can change the signature to accept a const std::unique_ptr<Algorithm>& reference instead:
class runner
{
public:
void runn_algo(const std::unique_ptr<Algorithm>& upa)
{
upa->run... |
66,804,628 | 66,805,825 | avoid vtable mixup in c++ variadic template inheritance | I have an idea to architecting classical entity-component in a better way with variadic template inheritance. This question stems from funky experiments in the context of 3d-graphics but i believe i have it broken down to a very abstract question about C++. I am able to use C++20 in the scope in which it is currently... | You have to use static_cast or dynamic_cast to move within an inheritance hierarchy, and static_cast can’t descend virtual inheritance or cross-cast (in one step) because the layout of different classes that derive from the source and destination types may differ. As it is, you’d have to know the actual type (not just... |
66,804,776 | 66,804,895 | Add GroupBox in a layout | I am using Qt 5.15.3, with Qt cretor.
I tried to add a QGroupBox in a QVBoxLayout but apparently, it is impossible. Does anyone have an idea to add it in the layout ?
Also, here is my code :
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QCheckBox>
#include <QGroupBox>
QVBoxLayout *layoutO... | I would try this way:
//trying to add optionGB in globalLayout
QVBoxLayout *globalLayout = new QVBoxLayout;
globalLayout->addWidget(optionGB);
|
66,805,125 | 66,805,363 | Adding a node to the end of a linked list but not able to access the last node | I have been having troubles adding a new node at the end of a singly linked-list.
When I print the list out, I don't seem to be able to access the last node.
if (head == nullptr)
{
head = newNode;
}
else
{
record* current = head;
while (current->next != nullptr)
{
current = current->next;
}... | While the other answer is good and necessary, I think it can be handled in a simpler manner. Here's an example Node.
struct Node {
int data;
Node* next = nullptr;
Node(int val) : data(val) {}
}
By default-initializing the pointer to nullptr, you don't have to constantly worry about it throughout your list class... |
66,805,129 | 66,805,159 | Should I check if a vector is empty before I use std::transform | Would it be a good idea to check if a vector is empty or not before using std::transform and back_inserter or could nothing wrong happen since the vector.begin() will be the same as vector.end() and will not insert nothing in the new vector ?
| This is unneeded. If empty() is true, then begin() == end() and transform will become a non-op as it works in the range [begin, end)
|
66,805,605 | 66,806,945 | 2D Dynamic Allocation in C++ Using New with Spatial Locality | My apologize for asking a basic question but I really could not find a suitable answer for this. I have inherited a C++ code where a part of it has a 2D allocation function Allocate2D in the form of:
float** Allocate2D(long long sizeX, long long sizeY)
{
float** p = new float*[sizeY];
p[0] = new float[sizeX*siz... |
Yes. It does depend on what exactly you mean by "2D array". There is more than one way to create a data structure for storing data that is indexed by two dimensions. One can dereference A with two dimensions, as in A[y][x], and it will work as expected. Also, there will be a pointer in A[0] that points to a contigu... |
66,805,799 | 66,805,877 | Optimization: Can I avoid a dynamic allocation of a vector in this loop? | I would like to understand whether I can avoid a dynamic allocation of a vector in the following code:
#include <vector>
int main() {
std::vector<int> vec;
while (predictate()) {
int curr_size = foo();
vec.resize(curr_size);
bar(vec);
}
};
perf shows that about 30% of the time withi... | Reallocations are expensive. You can avoid any reallocations to happen inside the loop if you reserve enough space upfront:
#include <vector>
int main() {
std::vector<int> vec;
vec.reserve( max_size ); // reserve enough space
while (predictate()) {
int curr_size = foo();
vec.resize(curr_... |
66,805,845 | 66,808,397 | Why is my C++ code returning some weird numbers even though everything is correct? | Why is this program returning random letters after output?
#include <iostream>
using namespace std;
int guessIt(int num) {
if(num == 27) {
cout << "You Won";
}
else {
cout << "You Lost";
}
}
int main() {
cout << guessIt(27);
}
| There are some problems in your code:
#include <iostream>
using namespace std;
int guessIt(int num) { //when you make the function guessIt(int num) you say it returns an int
if(num == 27) {
cout << "You Won";
}
else {
cout << "You Lost";
}
} //code finished without returning an int
int... |
66,806,245 | 66,814,753 | recvfrom non-blocking returning BAD ADDRESS error in c++ | I'm getting a "BAD ADDRESS" error when trying to listen and not when sending. Sending works perfectly with sendto().
Here's the function that creates the socket to listen. IP and Port are local (this is intented to execute in the same local network, in fact, in the same pc using a linux virtual machine and a windows ma... | Just for everybody to know about this.
In case you have BAD ADDRESS, as IBM documentation depicts:
When calling recvfrom: It is a problem with the buffer (pointing to NULL), the address (pointing to a wrong place or you are not passing the reference to the actual place and not a pointer), or the size of the address (t... |
66,806,304 | 66,806,319 | How to access a specific index in a array of pointers to objects? | struct A
{
int a;
};
int main()
{
A* ptr = new A[3];
ptr->a = 3;
return ptr->a;
}
The code above returns '3' as expected, and it evaluates to the first index. But how can I access the second index using the member selection operator? I could get it to work this way:(*(ptr+1)).a=5
But the code wouldn... | ptr is a pointer to an array of A objects. You can apply the [] index operator directly to the pointer to access specific objects in the array, eg:
A* ptr = new A[3];
...
ptr[index].a = 3;
...
delete[] ptr;
pointer[index] (and even index[pointer]) is exactly the same as doing *(pointer+index).
|
66,806,316 | 66,806,515 | Combining two dynamically allocated arrays | There are two dynamically allocated arrays, and I need to merge them into one. Here is the code, but it is not correct:
#include <iostream>
using namespace std;
int main(){
system("chcp 1251>null");
int n, m;
cin >> n;
cin >> m;
int* a = new int[n];
int* b = new int[m];
int* w = new int[n ... | Your example shows A and B containing duplicates that don't exist in the combined W, but your code does not ignore duplicates when populating W.
Try this instead:
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
system("chcp 1251>null");
int n, m;
cin >> n;
cin >> m;
int* a ... |
66,806,639 | 66,806,750 | Best way to call AWS Lambda in C++? | I have an AWS Lambda and am creating a simple C++ application to call it.
Based on the AWS Docs, I went and installed the SDK here https://github.com/aws/aws-sdk-cpp but that seems to add nearly a full GB if I include the whole thing.
Is there something like boto3 for C++?
If not, what is the accepted best way of integ... |
Is there something like boto3 for C++?
That's literally the thing you linked to. Boto3 is the AWS SDK for Python. This is the AWS SDK for C++.
What you are missing is that you can install just the packages you need from the SDK, instead of the full SDK.
|
66,806,874 | 66,807,426 | How to convert dd-mmm-yyyy and now() to days? | I need convert a dd-mmm-year string to epoch days to do some simple math. Specifically, calculate the number of days from now() to the date of the string.
I'm looking at <chrono> and <ctime> but am not seeing an obvious way to do that? How do you convert dd-mmm-year and now() to epoch days?
| This can easily be done with this free, open-source, header-only preview of C++20 , which works with C++11/14/17:
#include "date/date.h"
#include <iostream>
#include <sstream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
string s1 = "25-Mar-2021";
string s2 ... |
66,807,138 | 66,808,093 | How do you get the max value of a given column of a 2D std::vector? | I know how to get the max value of the row of a 2D std::vector as follows:
std::vector<std::vector<int>> a = {{ 1, 45, 54}, {71, 76, 12 }, {74451, 756, 125 }};}
std::cout << " The max value of row 0 is: " << *max_element(begin(a[0]), end(a[0]));
How do you do call max_element to get the max value of a 2D vector colum... | What you can do is provide std::max_element with a user-defined comparator that compares each std::vector<int> in a by the values in the desired column to search.
Like this:
std::vector<std::vector<int>> a = {{ 1, 45, 54}, {71, 76, 12 }, {74451, 756, 125 }};
std::cout << " The max value of row 0 is: " << *max_element(... |
66,807,718 | 66,808,014 | Process finished with exit code -1073741819 (0xC0000005) C++ clion | I'm following this tutorial but when i run at the time stamp I get the error:
Process finished with exit code -1073741819 (0xC0000005)
my code is
#include <windows.h>
bool running = true;
void* buffer_memory;
int buffer_width;
int buffer_height;
BITMAPINFO buffer_bit_map_info;
LRESULT CALLBACK window_callback(HWND ... | buffer_height and buffer_width are both 0 until a WM_SIZE message is received, so the pixel loop won't try to access buffer_memory until a bitmap is actually created. However, you are not validating that VirtualAlloc() is successful.
0xC0000005 is an Access Violation. Somewhere you are accessing invalid memory. You n... |
66,807,848 | 66,808,342 | I'm stuck on how to make a sorting algorithm in a doubly linked list using a person's first name and last name in C++ | So I made a doubly linked list which stores a person's first name, last name, address and age and I am currently stuck on making a sorting algorithm for the list. So far I've managed to create 3 functions, one that adds a node to the list, one that deletes a node from the list and one which prints the list.
Here's what... | To use custom sorting for a doubly-linked list, overload operator<:
struct Person
{
std::string first;
std::string last;
std::string address;
unsigned int age;
bool operator<(const Person& p) const
{
bool is_less_than = false;
if (last == p.last)
{
is_less_than = first < p.first;... |
66,808,434 | 66,808,522 | Optimizing the usage of std::vector with other vectors | I want to know what the most efficient way to set one vector equal to another and free the memory in the first vector after its changed. I can't imagine that resizing a vector to the other one and iterating over it and setting each index is the most efficient way,
std::vector< int > a, b;
//Stuff happens
//Swap
b.resi... |
I want to know what the most efficient way to set one vector equal to another and free the memory in the first vector after its changed.
Simply move one vector into the other so ownership of the source vector's existing memory gets transferred, while also freeing the existing memory of the target vector.
b = std::mov... |
66,808,567 | 66,808,690 | Implementing interfaces in c++? | So I saw this thread: What does it mean to "program to an interface"?. Which talks about declaring a Parent, but initializing it as a Child. Is it possible to do the same but with c++? For example: I have an interface Shape which can be implemented as Triangle or Square.
I tried to do the following but my program didn'... | This is a simple polymorphism example. Yes it is possible in C++ and is actually the heart of the benefits of Object-Oriented design
With C++ it isn't as simple as you might hope. You need virtual functions to do what you want. Modifying your example to be "good" C++.
class Shape {
public:
Shape(){}
int heig... |
66,808,765 | 66,809,255 | Using DirectWrites SetCharacterSpacing function | I'm having a hard time grasping this problem getting the newer/extended functions in dwrite_1.h to work with my existing code and hope that someone might be able to help.
This is my existing set up...
// In the .h file
IDWriteFactory* pDWriteFactory_ = nullptr;
IDWriteTextFormat* pTextFormat_ = nullptr;
IDWriteTextLay... | After you get the IDWriteTextLayout do a QueryInterface for the IDWriteTextLayout1.
IDWriteTextLayout1 * pLayout1 = nullptr;
hr = pTextLayout->QueryInterface(IID_PPV_ARGS(&pLayout1));
if(FAILED(hr))
{ /* handle error */ }
|
66,809,280 | 66,809,325 | Why is default construction disallowed in std::span with static extent? | Take a look at this example:
#include <span>
#include <vector>
class Data
{
public:
Data() = default;
template<class R>
explicit Data(R& r)
: buf_(r)
, header_(buf_.first<4>())
{}
private:
std::span<char> buf_;
// compile error
// std::span<char, 4> header_;
// co... | A default-constructed std::span<T> successfully refers to 0 objects of type T starting at nullptr. To what 3 objects of type T does std::span<T,3>() refer?
The size_ member always being present is purely a narrative device to simplify the specification; it means nothing and really isn’t there in practice for static-ex... |
66,809,317 | 66,809,404 | Typecast callback functions | Can I typecast callback functions?
I like to write a library that registers and calls certain callback functions.
int MyCaller::add_callback_function(int (*callback_function)(), byte behaviour) {
this->callback = callback_function;
}
void MyCaller::run() {
int result = this->callback();
}
// ....
int get_num... | You can cast one function pointer type to another, but you can only call it if you cast it to the real function pointer type. You can only store them as the wrong signature.
Calling them any other way results in undefined behavior. The most likely symptom will depend on your platforms current calling convention. But... |
66,809,373 | 66,809,615 | efficent way of casting or converting vector of atomic int to vector of int | I do have a vector of integer that I want to ensure increment operations happening thread-safe, so I used std::vector<std::atomic<int>> after all parallel increments I need non-atomic vector std::vector<int>. Is there an efficient way to do so, without copying? The vector is very large and performance is very important... | In C++, atomic operations are a property of the object itself, not of how you access it. As far as the object model is concerned, atomic<int> has no real relationship to int save the fact that you can convert one to another. You cannot transform an atomic<int> into an int; you can only create a new object with the same... |
66,809,884 | 66,809,962 | Does destructing objects stop the late binding? | Consider the following C++ classes inheritance hierarchy and their intended polymorphic behaviour.
#include <iostream>
using namespace std;
class A
{
public:
A () { cout << "A constructor\n"; }
virtual void display() { cout << "A display\n"; }
virtual ~A() { cout << "A destructor\n"; }
friend ostream& operator... | Destroying an object makes it illegal to continue calling member functions of that object. Your code's behaviour is undefined, and whatever behaviour you are observing cannot be relied upon to persist across even runs of the same program, let alone different compiler flags or entirely different implementations.
However... |
66,810,079 | 66,810,190 | C++20 ranges - How to assign composed views to a variable? | Is there a way to make this work with C++20?
auto view = std::views::all;
if (condition1) {
view = view | std::views::filter([](int i) {
return i%5 == 0;
});
}
if (condition2) {
view = view | std::views::filter([](int i) {
return i%10 == 0;
});
}
/* Do something with the view */
for (... | No, this is not viable code. C++ is a statically typed language, and each view you're conditionally constructing is of a different type. C++ doesn't allow you to change the type of an existing object (at least, not like that).
As such, these kinds of runtime conditional things cannot easily be done. Your case is easy e... |
66,811,619 | 66,811,786 | Can I stop other recursion tree branches from executing? | I am given a vector of integers and a sum, and if that sum can be generated from any combination of the elements in that vector, I need to return that combination. If more than one such combinations is possible, I may return any one.
For example,
sum = 20, vector = {6,25,8}, we may print 8 6 6 as 8+6+6 = 20
sum = 10, v... | You need to end the recursion when you find a match, in this case that's when flag == true.
if (flag) {
howSumVector.push_back(i);
memo[targetSum] = true;
return true; // We found a match! Stop searching!
}
Edit:
You are not using memo correctly. Since you only want one of the possible solutions, you don't... |
66,811,766 | 66,811,912 | What is happening in this fuction? | #include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
int print_vector(vector<int> &data) {
int size = data.size();
cout<< "size " << size << endl;
for(int i = 0;i < size;i++) {
if(data[i] == 3) {
return i;
}
cout<< data[i] << endl;
}
cou... | If we trace the flow of control in your program it should become obvious what's happening:
From main we call print_vector(data)
The first output is size 5 from cout<< "size " << size << endl;
We enter the for-loop:
First iteration (i == 0, data[i] == 1)
if(data[i] == 3) evaluates to false
We get the output 1 from co... |
66,812,476 | 66,813,169 | Are there any ways to use function_Pointer in this case? | i'm struggle to know how ios::hex function works.
#include <iostream>
#include <string>
#include <ios>
#include <ostream>
#include <istream>
class A {
public:
A& operator >> (std::ios_base& (*pf)(std::ios_base&)) {
(*pf);
return *this;
}
A& operator >> (int& a) {
std::cin >> a;
return *this;... | std::hex is used to set std::ios_base::flags. Your class A isn't derived from std::ios_base, nor does it have a member that's derived from std::ios_base. So there's indeed no obvious place to store the std::ios_base::hex flag.
The code suggests you want to affect std::cin::flags. That's a bit strange, as cin doesn't re... |
66,812,491 | 66,845,543 | Atomic: if statement is entered even though the conditional is false | Edit: minimal reproducible example
#include <atomic>
int main()
{
std::atomic_uint atomic_write_position{ 0 };
unsigned write_position = atomic_write_position.fetch_add(1);
bool b = false;
b = atomic_write_position.compare_exchange_weak(write_position, 0);
if (b);
{
auto x = 0;
}
}
... |
Remove the semi-colon ; in the if-statement
|
66,813,141 | 66,905,513 | Adding Custom c++ function in chromium and call them in browser | I am trying to write custom function in bootstrapper.cc under v8/src/init.
int helloworld(){
return 0;
}
When it try to call it from chromium console, it throws undefined.
| Look around bootstrapper.cc to see how other built-in functions are installed. Examples you could look at include Array and DataView (or any other, really).
There is no way to simply define a C++ function of a given name and have that show up in JavaScript. Instead, you have to define a property on the global object; a... |
66,813,240 | 66,814,301 | infinite for loop with correct limits | can you please explain why this code is going in infinite loop? I am unable to find the error. It is working fine with small values of n and m.
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long n=1000000, m=1000000;
long long k = 1;
for (long long i = 0; i < n; i++)
{
for (lo... | when I Run this code I got this as my output
1000000000001
reference : I had run this code in the code chef IDE(https://www.codechef.com/ide)
you can try in this IDE once, I guess there is some problem with your IDE
or might be some other issue
it took me less than 20 sec to run this(on clock)
But when I put the same ... |
66,813,347 | 66,814,146 | Find the Nth term of the fibonacci sequence | I am writing some code that uses multiple functions. One is to generate the Fibonacci sequence up to the Nth term that the user inputs. The other function is to find the largest/last number in the sequence.
I currently have the sequence printed out just fine, but my main problem is that I cannot find a way to print out... | Here is the Code After Modification:
#include <iostream>
#include <ctime>
#include <time.h>
using namespace std;
int printSequence(int x);
int maxInput(int n);
int main() {
int x;
cout<<"Enter an integer: "<< endl;
cin>> x;
int max = printSequence(x);
// max is the last Integer in Set
cou... |
66,813,373 | 66,814,844 | No content was rendering after getting events | I have this code writen in C++ and I'm using OpenGL as the render API
int main()
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Test OpenGL", NULL, NULL);
if ... | Currently, the application only renders the triangle in frames where the user presses the key.
You have to render the triangle unconditionally, and only adjust the index based on the user input:
unsigned i = 0;
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
/* Pol... |
66,813,402 | 66,813,977 | Frobenius Inner Product between two matrices in Eigen3 | Is there a simple and quick solution to calculate the Frobenius Inner Product between two 3x3 matrices in Eigen3?
| If you are searching for the inner product of matrices, a possible (maybe not optimal) solution may be
#include <iostream>
#include "Eigen/Dense"
int main()
{
Eigen::Matrix3d A, B;
A << 1, 2, 3,
4,5,6,
7,8,9;
B << 10, 11, 12,
13,14,15,
... |
66,813,421 | 66,813,458 | How to initialize a vector of struct inside another vector of struct? | I try to initialize structures of vectors that contains vector:
struct productionCanvas
{
int canvasID;
int indexXmlJob;
};
struct productionArea
{
int areaID;
std::vector<productionCanvas> canvasList;
};
The first level is correctly initialized but not the ... | You can zero-initialize any POD struct or array by simply adding {}:
productionArea area{};
// Or
productionArea area = {};
// Or
auto area = productionArea{};
Unless you are working in C/C++ environment, there is no need for typedef struct in C++. The symbol namespaces are not separate. This is equal to your current ... |
66,813,961 | 66,815,875 | C++ constexpr constructor for colours | I have a class Colour:
class Colour {
public:
std::byte r;
std::byte g;
std::byte b;
std::byte a;
};
Now if I have a function
void foo(const Colour& c);
I want to be able to call it by passing a string that represents the colour:
foo("red"); // become (255, 0, 0, 255)
foo("#00ff00"); // become (0, 255, 0, 255... |
I don't want to parse the string everytime,
Even with a
constexpr InternalColour parseString(const std::string_view& str)
None of the calls are in constant expressions, so apply at runtime (optimizer might help):
foo("red"); // become (255, 0, 0, 255)
foo("#00ff00"); // become (0, 255, 0, 255)
foo("hsl(240, 100, 50)"... |
66,814,328 | 66,819,929 | Why the standard defines borrowed_subrange_t as common_range? | C++20 introduced the ranges::borrowed_range, which defines requirements of a range such that a function can take it by value and return iterators obtained from it without danger of dangling. In short (which
refer to P2017R1):
A range is a borrowed_range when you can hold onto its iterators after the range goes out of ... | To quote Alexander Stepanov, in "From Mathematics to Generic Programming":
When writing code, it’s often the case that you end up computing a value that the calling function doesn’t currently need. Later, however, this value may be important when the code is called in a different situation. In this situation, you shou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.