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 |
|---|---|---|---|---|
69,045,144 | 69,047,819 | Adding over 30 days to 1900-01-01 | How can I add over 30 days in C++ to 1900-01-01 date approx. over 1000 days and then format the time_t after the addition to get a non-broken date.
This is what I have tried so far:
int tmp = 1000;
struct std::tm tm;
std::istringstream ss("1900-01-01");
ss >> std::get_time(&tm, "%Y-%m-%d");
tm.tm_mday = tm.tm_mday + tm... | In addition to Joseph Larson's very good suggestion to check out the date/time library to use, I'll show how you could get further using your current idea.
You also have much support in std::chrono nowadays so read about that too.
You try to add the days in the wrong domain, to std::tm. Instead, convert the std::tm to ... |
69,045,163 | 69,045,272 | Why it needs a rvalue copy constructor even it won't be called? | I've wrote a shared_ptr the class definition is as below:
template <typename T>
class shared_ptr {
private:
...
public:
shared_ptr(T* p);
shared_ptr(shared_ptr& src);
shared_ptr& operator=(shared_ptr const& src);
};
shared_ptr<T> make_shared(Args&&... args) {
return shared_ptr<T>(new T(std::forward<Args>(args).... | The issue is that your copy constructor accepts a non-const lvalue reference for some reason, which can't bind to an rvalue. Just make it const:
shared_ptr(shared_ptr const& src) noexcept;
and the move constructor won't be required. However it's a good idea to implement the move constructor/assignment anyway, to not p... |
69,045,544 | 69,045,600 | C++ is there a difference between dereferencing and using dot operator, vs using the arrow operator | Let's say I have the following variable:
MyObject* obj = ...;
If this object has the field foo, there are two ways of accessing it:
obj->foo
(*obj).foo
Are there any differences between using one method over the other. Or is the first method just syntactic sugar for the second?
I was thinking maybe the first one cou... | There is no difference when obj is a pointer.
If obj is an object of some class, obj->foo will call operator->() and (*obj).foo will call operator*(). You could in theory overload these to do totally different behavior, but that would be a very badly designed class.
|
69,046,232 | 69,046,502 | How to start a Win32 GUI application as a background process? | When COM starts an out-of-process server via CoCreateInstance() with a CLSID derived from ProgId (eg "Excel.Application"), how exactly does this happen?
I can see entries in the Registry which give the command line:
When COM starts a new Excel server (if one is not already running), the excel.exe process is in the bac... | Command-line switches for Microsoft Office products
/e or /embed
Prevents the Excel startup screen from appearing and a new blank workbook from opening.
Example
excel.exe /e
|
69,046,565 | 69,046,842 | How do I convert a string containing one number into a vector in C++ where all the digits are the elements of vector | Suppose I have a string containing 00101 and I need to convert it to a vector containing each single digit as an element, like vector<int> num{0,0,1,0,1}.
I looked up many solutions but the numbers in the string were space-separated.
| It may not be the best solution...but a solution nonetheless, please feel free to reply and improve my code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<int> v;
string s = "101010";
for(char c : s)
{
v.push_back(((int)c - 48));
}
... |
69,046,609 | 69,046,844 | Struct doesn't print with cout | I'm trying to print the structure in an array whose int prejetih member is highest.
#include <iostream>
using namespace std;
struct Tekma {
int prejetih;
};
Tekma najvec_kosev(Tekma tekme[]) {
int maksi = 0, index = 0;
for (int i = 0;i < 2;i++) {
if (maksi < tekme[i].prejetih) {
index ... | Here using a solution with std::vector and fixing your cout problem:
#include <iostream>
#include <vector>
using namespace std;
struct Tekma {
int prejetih;
};
Tekma najvec_kosev(vector<Tekma>& tekme) {
Tekma lowest = tekme[0]
for(auto& t : tekme) {
if(lowest.prejetih < t.prejetih) {
l... |
69,047,028 | 69,047,116 | Why Friend Function cannot access private members of a class | class A{
public:
void printer(){
B obj;
obj.private_data = 10; // <- fails, says member inaccessible
}
}
class B{
friend void A::printer();
private:
int private_data;
}
is it possible for printer function to access private members of class B? i tried to pass an obj of B as arg to printer bu... |
Why Friend Function cannot access private members of a class?
They can, but you may need to split the definition of the class up a bit.
Imaginary files added:
Define A (file a.hpp):
class A {
public:
void printer();
};
Define B (file b.hpp):
#include "a.hpp" // B must see the definition of A to befriend a member... |
69,047,064 | 69,047,727 | How to make explicit instantiation of template constexpr variable in C++? | If one has a template constexpr variable (e.g. for computing Fibonacci sequence) and would like to instantiate it for some template argument, must constexpr keyword be repeated during instantiation?
template<int N> constexpr size_t fib = fib<N-1> + fib<N-2>;
template<> constexpr size_t fib<1> = 1;
template<> constexpr ... | This is probably a Clang bug. From temp.explicit#3
... An explicit instantiation of a function template, member function of a class template, or variable template shall not use the inline, constexpr, or consteval specifiers.
(emphasis mine)
Which is exactly what the GCC error message says.
Clang's error message says ... |
69,047,244 | 69,051,560 | Perfect forwarding variable with unnamed type | Are the following two versions always equivalent?
for (auto&& elem : elems) {
using E = decltype(elem);
f(static_cast<E&&>(elem)); // 1
f(std::forward<E>(elem)); // 2
}
| Yes, these are the same.
The rules for auto&& deduction mean that E is always a reference type here, so E&& is the same type as E. That makes the static_cast “reassert” the xvalue status of elem if it has that.
It’s unusual to write std::forward<T&&> explicitly, but it works because that’s how std::forward<decltype(x)... |
69,047,620 | 69,047,911 | Is there anything like C++ default object method | I have the following templated merge sort program:
#include <iostream>
#include <vector>
#include <string>
// trying to create a default method call
class CInstance {
private:
std::string str_;
public:
CInstance(const std::string& str) : str_(str) {}
bool const operator>(const CInstance& that){ return (t... | As already mentioned in the other answer you can create your own operator<< function:
std::ostream & operator<<(std::ostream &stream, const CInstance &obj) {
// stream << whatever you want to output
return stream;
}
You could also define a conversion operator. But you should think twice before you use t... |
69,047,789 | 69,047,823 | Why does (0 && 1 == 0) not evaluate to true? | In my if statement, the first condition for && is 0 (false), so the expression 0 && (a++) is equal to 0, right? Then 0==0 it should be true. Why am I getting else here? Please explain!
int a=0;
if(0 && (a++)==0)
{
printf("Inside if");
}
else
{
printf("Else");
}
printf("%i",a);
| The == operator has a higher priority than the && operator, so this line:
if(0 && (a++)==0)
is treated like this:
if( 0 && ((a++)==0) )
So the whole expression under the if is false, and a++ is not even evaluated due to short circuitry of the && operator.
You can read about Operator Precedence and Associativity on c... |
69,048,105 | 69,048,185 | How to deal with long floating numbers the program doesn't support? | I'm trying to read a bunch of constants of a text-file in C++ using the <fstream> library. The constants are 16 decimal places long, or 16 digits after the decimal point. Now, whenever I try to read those digits, the program truncates it to 6 decimal places whether I use the datatypes double or long double.
The progra... | Use std::cout.precision(). The limit precision of long double is 18.
long double number = 0.2599210498948732;
cout.precision(16);
cout << number;
|
69,048,326 | 69,051,288 | wxButton covering entire client area C++ | I have made an application using wxWidgets 3.1.5 in C++ and everything is working fine except a test button that I have on my main window.
Here's a pic:
The menubar, menus and their functions work perfectly but the button covers the entire client area.
Here's the code:
main.h
#pragma once
#include <wx\wx.h>
#include "... | That is how a wxFrame with only one child behaves.
If you don't want that, use a wxSizer to layout your button (position, align, expand etc).
Reference:
if the frame has exactly one child window, not counting the status and toolbar, this child is resized to take the entire frame client area. If two or more windows are... |
69,049,148 | 69,049,311 | Constraint a template parameter to only accept std::vector and std::list with C++20 concepts | I am trying to write a program that sort only numbers in a std::vector or a std::list
for which I did 2 concepts:
template<typename T>
concept ValidContainer = requires(T a) {
std::same_as<T, std::vector<typename T::value_type>>;
std::same_as<T, std::list<typename T::value_type>>;
};
And:
template<typename T>
... | This:
template<typename T>
concept ValidContainer = requires(T a) {
std::same_as<T, std::vector<typename T::value_type>>;
std::same_as<T, std::list<typename T::value_type>>;
};
is checking to see if the expression std::same_as<T, std::vector<typename T::value_type>>; is valid, not that it also is true. Which i... |
69,049,226 | 69,049,484 | Why this pointer pass a value not address in calculating sum? | I am confused about the pointer when passing to functions in C++, when put *arr in the parameter(line 3), is it means int *arr = balance , I know balance can refer the first element address in the array, but the problem is why arr[i] refers the first element value?
I think *arr means value, while arr means address...
#... | An array identifier cast to a pointer when used with brackets [] or when dereferencing with *, so in main balance is treated as a pointer when not using brackets.
When the brackets are placed after a pointer, they will add an offset to the pointer, based on the size of the object type in memory, then dereference the po... |
69,049,359 | 69,049,371 | Why I'm Getting Garbage Value as output? | Why the output is not 10 or even 5??
void main()
{
int a=10;
goto here;
{
int a=5;
here:
printf("%i",a);
}
}
output: Garbage Value
| Because there are two a variables, the second shadows the first in the print statement. Since you skipped its initialization, the output is garbage.
Note it is a compiler error to skip past initialization in C++, in C you just get the uninitialized value as you have observed.
Also, it is int main(), not void main().
|
69,049,745 | 69,050,184 | Why do std::variant implementations take more than 1 byte for variant of empty types? | This is mostly trivia question, as I doubt that I will ever need this space saving.
While playing around on godbolt I noticed that both libstdc++ and libc++ implementations of std::variant require more than 1 byte to store variant of empty structs.
libstc++ uses 2 bytes
libc++ uses 8 bytes
I presume it is just not wo... | Every object takes up at least 1 byte of space. The counter itself needs to take up at least 1 byte, but you also need space for the potential choices of object. Even if you use a union, it still needs to be one byte. And it can't be the same byte as the counter.
Now, you might think that no_unique_address could just c... |
69,050,714 | 69,051,555 | Observing the state of a variant during construction | Consider the following code:
#include <variant>
#include <cassert>
struct foo {
foo() noexcept;
foo(const foo&) noexcept = default;
foo(foo&&) noexcept = default;
foo& operator=(const foo&) noexcept = default;
foo& operator=(foo&&) noexcept = default;
};
std::variant<std::monostate, foo> var;
foo::foo() ... | The standard doesn't currently provide an answer to your question, but the direction that LWG appears to be moving in is that your code will have undefined behaviour.
|
69,050,734 | 69,057,663 | Set snd_pcm_sw_params_set_stop_threshold to boundary, still getting underrun on snd_pcm_writei | The question says it all. I am going in circles here. I set snd_pcm_sw_params_set_stop_threshold to boundary (and zero too just for fun) and I am still getting buffer underrun errors on snd_pcm_writei. I cannot understand why. The documentation is pretty clear on this:
If the stop threshold is equal to boundary (also s... | Okay I figured it out. To anyone who runs into this issue who also has pipewire or pulse (or any other thirdparty non-alsa audio card) enabled as the "default" card the solution is to not use pipewire or pulse directly. It seems that snd_pcm_sw_params_set_stop_threshold is not implemented properly in pipewire/pulseaudi... |
69,050,852 | 69,051,038 | How can I make child constructor if parent doesn't have constructor without params | I have library which I can't modify with parent class:
class A {
public:
A(immpl i) { /* do smth */ }
}
I want to write child-class:
class B : public A {
public:
B(FSImplPtr impl) : A(impl) {};
};
All works fine. So I can create child-class by:
B(SomeFunction(new VFSImpl()));
So, I want to make constructor w... | Does VFSImpl exists? I didn't see it in the git-file. I think it is a typos and you need FSImpl.
|
69,051,181 | 69,051,191 | Setting pointer to NULL fixes project | On a semi-large project (~5000+ lines of code)...
I have a class with a pointer as one of its fields. The pointer was declared but not initialized:
Apple *apple;
In the class's constructor, I initialized the pointer if it was NULL:
if (apple == NULL) {
apple = new Apple();
}
Further down in the project's code, I ... | It's hard to tell decisively, but probably yes, the program worked by sheer luck.
If you don't explicitly initialize a pointer you can't assume anything about it, and TBH, it's not surprising that the program started crashing, but that it worked up until now.
|
69,051,193 | 69,051,392 | Seeing unexpected data on a shared pointer | I'm trying to convert a nlohmann::json object to a std::shared_ptr<char[]>. I'm running into an issue where the data inside the shared pointer seems to have extra junk attached that i did not have in my original object.
The function below is not as condensed as it could be because I wanted to show what I am seeing in t... | The problem is here:
ds.copy(rd.get(), ds.size() + 1);
std::string::copy does not copy a null terminator, so when you construct a string here:
std::string p = d.get();
You read past the end of the array and invoke undefined behavior. This probably could have been avoided by just using std::string; std::shared_ptr<ch... |
69,051,830 | 69,051,902 | Solution to mimic enum inheritance in cpp | I know that enum inheritance is not possible in c++, but I am looking for specific data structure that simply fit into my case. Suppose I have these two enums:
enum Fruit { apple, orange};
enum Drink { water, milk};
I want a parent for these two that I can use as parameter in this abstract method
void LetsE... | Speaking very generally, enums are just dressed up ints.
enum Fruit { apple, orange};
If you look at the compiled code, you will discover that an apple will be represented by the value 0, and an orange will be represented by the value 1.
enum Drink { water, milk};
Same thing here will happen here. water will be repre... |
69,051,954 | 69,052,192 | error: call of overloaded function ambiguous | I am trying to compile ustl C++ library with MinGW GCC compiler on Windows 10.
The 41st line in the C++ header below was able to solve thanks to this answer, but there is a problem at line 43. How should I solve it?
https://github.com/msharov/ustl/blob/master/fstream.h#L41
// int ioctl (const char* rname, ... | You can find in the last few words that
fstream.h:43:132: error: call of overloaded 'ioctl(const char*&, int&, uintptr_t)' is ambiguous 43 | inline int ioctl (const char* rname, int request, void* argument) { return fstream::ioctl (rname, request, uintptr_t(argument)); }
intptr_t is actually a uintptr_t in your environ... |
69,052,010 | 69,052,527 | How to send WM_COPYDATA from C++ to AutoHotKey? | Trying to SendMessage with WM_COPYDATA from a C++ application to an AutoHotkey script.
I tried to follow the example found in the docs:
https://learn.microsoft.com/en-us/windows/win32/dataxchg/using-data-copy
Then I did:
HWND htarget_window = FindWindow(NULL, L"MyGui");
std::string str = "Hello World";
COPYDATASTRUCT... | Your use of StrGet() is wrong:
You are not including the std::string's null terminator in the sent data, but you are not passing the value of the COPYDATASTRUCT::cbData field to StrGet(), so it is going to be looking for a null terminator that does not exist. So you need to specify the length that is in the COPYDATAST... |
69,052,064 | 69,052,229 | Correctly setting up MMDevice in a DirectX project | I am currently trying to piece together a shader-based music visualizer. The plan is to read data from the current MMDevice, which I'm trying to follow the documentation for, but I must be doing something wrong because I had to jump through all sorts of hoops to get even just the MMDeviceEnumerator to compile.
In order... | You are writing a Universal Windows Platform (UWP) app because that's what the "built-in" DirectX 12 App project template creates in Visual Studio. UWPs do not have access to all the same APIs and IMMDevice is not part of the UWP API surface area.
The fact that you defined WINAPI_FAMILY_GAMES means you hacked the API F... |
69,053,232 | 69,053,901 | How do I locate the data of host and kernel in two different locations | I have wrote the kernel code that will be run on FPGA device. Currently, I am writing the host code which will be run on CPU. In the last meeting with my professor, he told me that the data (arrays in my case) in the host should not be located in the same memory space of that for the device. Thus, he asked me to use po... | You currently have allocated your arrays on the stack. This limits the maximum error size. It is better to use heap allocation with (1-dimensional) pointers:
int* array_X_set = new int[5430*20]; // linearize 2D array
int* array_Y_set = new int[5430];
for (int i = 0; i < 5430; i++) {
for (int j = 0; j < 20; j++)
... |
69,053,248 | 69,083,215 | Why can't I run some programs after using unshare(CLONE_NEWUSER) | I'm working on adding some restrictions to my build process - to detect cycles, specifically. To achieve this I've been experimenting with user namespaces.
Here's my 'hello world' program:
#include <sched.h>
#include <unistd.h>
int main()
{
if( unshare(CLONE_NEWUSER) != 0)
{
return -1;
}
execl... | This error was due to my failure to set up the uid_map and gid_map. I have not produced a satisfactory, explicit, minimal example of the error, but I have written a working minimal solution, that I will share here. Notice that int main() is identical, except before exec'ing the target command we first set up the uid_ma... |
69,053,270 | 69,056,091 | visual C++ string subscript out of range | I am stuck with the error "string subscript out of range".
After testing, I am pretty sure that it's because of this function, which is used for reading values in a file, but have no idea what's wrong:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string read(string value) {
ifstre... | Thank you for your comments. I solved this by editing the for loop:
string read(string value) {
ifstream input;
int olength;
string line = "", output = "";
size_t pos;
bool a = true;
int i = 0;
input.open("pg_options.txt");
if (!input.is_open()) {
cout << "pg_options.txt missing.... |
69,054,073 | 69,054,136 | Implementing an Assignment Operator | I am trying to write an overloaded operator= to assign copy the content of an object studentA to studentB. After compiling, it just crashes and as usual "stops working".
#include <cstdlib>
#include <iostream>
using namespace std;
class STUDENT {
public:
string ID;
string name;
unsigned int... | Your operator= is implemented all wrong. Your res pointer does not point anywhere meaningful when you dereference and assign to it. That is why your code is crashing.
You need to actually copy the individual members yourself from obj to *this, similarly to how you are doing so in your constructor, eg:
#include <iostr... |
69,054,321 | 69,054,380 | How to initialize a two dimensional array using initializer_lists? | I've coded this constructor to initialize my two-dimensional array using initializer_lists.
using namespace std;
class TwoArray{
int** array;
public:
TwoArray(initializer_list<initializer_list<int>> list_){
const size_t row_size = list_.size();
const size_t column_size = list_.begin()->size();... | You need to create one array of pointers first, then initialize them with arrays of int. Note that this may leak if any allocation throws an exception.
array = new int*[row_size];
for(std::size_t i = 0; i < row_size; ++i)
array[i] = new int[column_size]{};
And then analogously delete each sub-array.
for(std::size_... |
69,054,502 | 69,054,567 | Valgrind, Blocks Are Definitely Lost even though I free? |
Small Note, Please Ignore the use of malloc instead of new and the use
of my own containers instead of vector etc... The point of this code
was to practice the basics.
When I ran Valgrind I get:
==24855== HEAP SUMMARY:
==24855== in use at exit: 0 bytes in 2 blocks
==24855== total heap usage: 12,999 allocs, 12,9... | What happens if (*numOfSegments) == 0 is true in GetAllSegmentsByLabel?
In that case you have still allocated 2 blocks of 0 bytes and they are lost because you set both pointers to nullptr before exiting the function in the if statement.
Every malloc including malloc(0) must be freed.
|
69,054,560 | 69,055,129 | Find the minimum time | The problem statement is ->
We want to scan N documents using two scanners. If S1 and S2 are the time taken by the scanner 1 and scanner 2 to scan a single document, find the minimum time required to scan all the N documents.
Example:-
S1 = 2, S2 = 4, N = 2
Output: 4
Explanation: Here we have two possibilities.
Either ... | Well, I'm sharing the O(log n) approach. With binary search on ans / time, we could find the optimal time.
For binary search, we need upper bound & lower bound. Let's assume lower bound as 0. Now we need to find out the upper bound.
What will be the minimum time required if we scan all the documents in one scanner. It ... |
69,054,561 | 69,054,924 | The difference between two declarations of deleted function | I have this class widget:
class widget_11 {
public:
template<typename T>
void process_pointer(T* ptr)
{
std::cout << *ptr;
}
};
my issue is that I don't understand whats the difference between
these two declarations:
template<>
void widget_11::process_pointer(double*) = delete;
template... | Both of those are declarations and definitions for an explicit specialization of process_pointer for T = double so they would define the same thing the same way.
When you write out the declaration for an explicit specialization, template argument deduction can be used to fill in types not specified. In the case of your... |
69,055,115 | 69,060,991 | How to use std::any_of inside a class with lambda expression? | I'm coding a small simulation in c++ with robots and I need to check if the robot are colliding. I implemented this function in my simulation's class:
bool World::isRobotColliding(Robot *r) {
for (Robot *other_robot: robots) {
double d = distance(r->getX(), r->getY(), other_robot->getX(), other_robot->getY(... | Thank you everyone for your advise,
The issue was the pointer passed by reference.
return std::any_of(robots.begin(), robots.end(), [r, this](const Robot *other_robot) {
double d = distance(r->getX(), r->getY(), other_robot->getX(), other_robot->getY());
if(d == 0) return false;
return
... |
69,055,226 | 69,055,276 | Is there an actual security risk with using public for a certain class attribute? | I understand that public private and protected serve the programmer to not get mixed up regarding the right way to modify data. Is there some sort of security risk associated with making some data public ? For exampl, let's say i make a game that uses the following class :
Class A
{
public:
int speed;
Vector2 position;... | public access is purely a compile-time concept/control - it doesn't make it harder or easier to modify the value at runtime in e.g. a debugger. The memory layout of an object of class A will have speed and position sitting there regardless. Compared to having the members private, the main difference is whether some c... |
69,055,519 | 69,055,631 | How do you safely clear an object from memory (with attributes) which was created using the new keyword? | As far as I know on this topic, every "new" call needs a corresponding "delete" call to that object. So is this really correct?:
using namespace std;
class Box {
public:
double length;
char letters_in_box[80];
};
int main() {
Box *b = new Box;
b->length = 2.0;
b->letters_in_box = "Hello world"... | Yes. When you delete b it deletes also letters_in_box array.
But, for your b->letters_in_box = "Hello world"; you will get a compile error: "error C3863: array type 'char [80]' is not assignable"
#include <memory> // For 'memcpy_s' (since C11)
class Box
{
public:
double length;
char letters_in_box[80];
};
int... |
69,056,089 | 69,056,428 | Predicate function with counter | How to make predicate function that counts number of iterations in sort algorithm ?
I guess I'm supposed to make a functions that returns lambda becausee of: auto p1 = predicate_with_counter(predicate1, counter); .But I have no idea how to do it.In text of problem it says that main function should remain as it is, so ... | Based on the requirements discussed in the comments I will present 2 solutions. The first one does not use lambdas and will work in all versions of C++
struct predicate_with_counter {
// typedef for the function to be passed as argument
typedef bool(*predicate)(double, double);
predicate_with_counter(pre... |
69,056,172 | 69,128,419 | How do you compile ImGui on Windows vscode MinGW? | Right, so I have been trying for weeks now to get ImGui to work with my windows OpenGL project. I have tried everything. So, can someone please show me how to compile ImGui with the rest of my project. Like how to add it to the vs code task file or how to add it to my makefile. Also when I have asked before people have... | As ImGui is a separate library your project should link against it rather than compiling it with the rest of your project each time.
Here's how I build the library (both static and shared) in MSYS2 shell:
# change the next value to where you want to install it
export INSTALLPREFIX=/D/Prog/3rdparty
# fix DLL exports in ... |
69,057,184 | 69,057,243 | Why is C++'s NULL typically an integer literal rather than a pointer like in C? | I've been writing C++ for many years, using nullptr for null pointers. I also know C, whence NULL originates, and remember that it's the constant for a null pointer, with type void *.
For reasons, I've had to use NULL in my C++ code for something. Well, imagine my surprise when during some template argument deduction t... | In C, a void* can be implicitly converted to any T*. As such, making NULL a void* is entirely appropriate.
But that's profoundly dangerous. So C++ did away with such conversions, requiring you to do most pointer casts manually. But that would create source-incompatibility with C; a valid C program that used NULL the wa... |
69,057,498 | 69,057,554 | How to pass const struct pointer to a setter method in C++ | I am trying to pass a const struct pointer to a setter setContainer of an auto-generated C++ API code so I can't change the class:
#include <iostream>
#include <memory>
class Class // Class definition
{
public:
struct Container // Container definition
{
double value = 0.0;
};
Class() { } //... | Your setter function expects a pointer to a Container object, so give it one: just add the & operator to your argument:
objClass.setContainer(&container2);
|
69,057,831 | 69,058,224 | CRTP vs template specialization and tag dispatching | I am trying to figure out the advantages and disadvantages of the CRTP idiom as opposed to template specialization. Let's say I want to create a "Renderer" class, and the renderer will either be implemented using "Vulkan" or "OpenGL".
With CRTP:
template <typename T>
class Renderer
{
public:
void draw(Shape s) { st... | With CRTP, you can put any shared code/types/constants etc. into the base template, supporting both implementations. If you don't have things to share, there's no point using CRTP. It does have the usually easily managed downside that dynamically created derived objects risk accidental or careless deletion via a base... |
69,057,936 | 69,058,329 | Wrong memory usage information of C++ program by valgrind? | I was using valgrind to find memory usage by my program using this command
valgrind --tool=memcheck --leak-check=full -s --track-origins=yes ./memoryProblem
it shows that the total heap usage by my program was 72,704 bytes
this is my program
#include <iostream>
int main(int argc, char const *argv[])
{
int a[32768... |
why is it showing 72,704 bytes?
You can run gdb and set break malloc and then you'll get:
Breakpoint 1, 0x00007ffff7ae1320 in malloc () from /usr/lib/libc.so.6
(gdb) bt
#0 0x00007ffff7ae1320 in malloc () from /usr/lib/libc.so.6
#1 0x00007ffff7e2326b in (anonymous namespace)::pool::pool (this=0x7ffff7f93240 <(anonym... |
69,057,971 | 69,058,090 | How to use named parameters in c++ | In python we can pass arguments to called function using argument name like in the following code , how can we do the same thing C++ ,
I needed this because ,if we have too many parameter it easy to mess up the location of the argument passed in called function and calling function
def calendar(year,month,day):
re... | Neither C nor C++ supports named parameters.
The closest you can come to this is to define a struct with all of the parameters:
struct cal_params {
int year;
int month;
int day;
};
Define the function to take an instance of that struct:
char *calendar(struct cal_params params)
{
...
}
Then call the fu... |
69,058,298 | 69,058,469 | How to make a program work regardless of the user's pwd when using file streams? | Consider project in ~/my/computer/my_project with files:
main.cpp
input
We want the project to be usable on ~/your/computer so we use relative paths when dealing with file streams:
// main.cpp
#include <iostream>
#include <fstream>
int main ()
{
std::ifstream stream("input");
if (!stream.is_open())
... | You need to build a relative path from the location of your executable file.
This depends on the OS, and here are a few ways to do that:
Finding current executable's path without /proc/self/exe
|
69,058,631 | 69,058,691 | Can't create constructor for template type with template type parameter | Disclaimer: I'm very new to C++.
I have a Container class and an Item class. Both of them are generic with the same Type:
container.h:
template<typename Type>
class Container
{
public:
Container(Item<Type> item);
}
container.cpp:
#include "container.h"
#include "item.h"
template<typename Type>
Container<Type>::Co... | Usually it is done like this, container.h
template<typename Type>
class Container
{
public:
Container(const Item<Type>& item)
{
// implementation goes here
}
};
|
69,058,642 | 69,058,771 | How does vectors in C++ use memory? | #include <iostream>
#include <vector>
int main(int argc, char const *argv[])
{
std::vector<int> a(32768, 0);
std::cout << "Size " << sizeof a << "\nCapacity " << a.capacity() << "\nElements " << a.size();
return 0;
}
for this program im getting the output:
Size 24
Capacity 32768
Elements 32768
using valg... | As addressed in the comments by Kamil, a std::vector keeps track of three pointers internally. One pointer to the begin, one to end and one to the end of allocated memory (see stack post). Now, the size of a pointer should be 8 bytes on any 64-bit C/C++ compiler so, 3 * 8 bytes = 24 bytes (see wiki).
|
69,058,869 | 69,059,055 | How to define a concept for positive number? | I'm trying to create a compile-time sum function, and I want it to make sure that all its given arguments are positive:
template<typename T>
concept Positive = requires(T t) {
{ /*what should be here?*/ } ;
};
template<Positive... T>
int sum(T... x) {
return (x + ...);
}
But I wasn't able to figure out how to... | The obvious answer to your question would be std::is_unsigned.
However using unsigned integer types should be avoided. They interact weird with signed types.
So if you use signed integers (as you should) concepts can't help with that because concepts are compile-time checks while the value of an integer is known at run... |
69,058,973 | 69,059,186 | The best practice to avoid warning C26451 [Typecast error] | I am working on coding exercises for C++ beginner on Windows 10 Pro (64 bit) with Visual Studio Community 2019. I would like to know the best practice for typecast. Below is what I tried. Could you please anyone give me some advice? Thank you in advance.
I initialized as below:
// "long int" 4 bytes
long m = 2;
// dou... | The first thing to keep in mind is that C26451 is not a "compiler warning". It's from the C++ Core Guidelines checker which is a modern lint-style tool.
IOW: It's extremely fussy by design. The code you wrote is in fact valid source code.
The C++ Core Guidelines are a great guide for C++ developers and a great resource... |
69,059,062 | 69,062,931 | How to optimize this graph/tree problem counting distance between two nodes in C++? | Problem is to find sum of distance between two nodes in a tree
INPUT: 6 [[0,1],[0,2],[2,3],[2,4],[2,5]]
shows nodes
OUTPUT: [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.
Th... | As I can see you are using bfs for every node to find the distance.
What you can do is use dynamic programming
Follow the steps below to solve the problem
Initialize a vector dp to store the sum of the distances from each node i to all the leaf nodes of the tree.
Initialize a vector leaves to store the count of the le... |
69,059,099 | 69,059,601 | `for` loop to avoid writing same thing multiple times |
const double weight1{result["w_group_1"]};
std::string weight_bar1;
GetData(weight1, weight_bar1);
weight_bar1 += " ";
const double weight2{result["w_group_2"]};
std::string weight_bar2;
GetData(weight2, weight_bar2);
weight_bar2 += " ";
const double weight3{result["w_grou... | IIRC those elements are called associative arrays. Those are not allowed in C++. C++ has std::map to facilitate such a thing.
std::map<std::string,int> result;
result["abcd"] = 55;
to achieve number after string use std::to_string(<number>)
so to put it in your code:
std::string name ("w_group");
std::string nameNum;... |
69,059,141 | 69,059,462 | C++ - Function with multiple parameter packs and a std::function as argument | I am trying to create an IoC Container in C++ that resolves dependencies automatically.
For that I created a function with two variadic parameter packs that is declared like this:
template <class T, typename ... TDependencies, typename... TArgs>
void Register(std::function<std::shared_ptr<T> (std::shared_ptr<TDependen... | Rather than trying to deduce TDependencies directly from the pFactory parameter type, I'd write a type trait to get the dependencies from the whole parameter pack instead. With boost::mp11:
template <class>
struct is_shared_ptr : std::false_type {};
template <class T>
struct is_shared_ptr<std::shared_ptr<T>> : std::tr... |
69,059,828 | 69,059,917 | Segmentation fault with const string& constructor and templated std::set find | The following code encountered a segment fault with the const string& constructor, and exit with 0 with the string_view constructor. I know the const string& is not the best way to do so. But from my understanding, without optimization, a temp string is constructed from const char*, then it's value gets copied in the P... | Your free-standing operator< calls itself recursively (and infinitely). This is because there is no in-built < operator that compares a string_view to a string, yet there is an implicit conversion from string to const Person&.
Although there is also an implicit conversion from string to string_view, because there is an... |
69,060,025 | 69,060,629 | why cuda kernel can access host memory? | I directly access the host mem in the cuda kernel, and found no error, why is this?
I tried to get smarter from the documentation.
Allocates size bytes of host memory that is page-locked and accessible to the device. The driver tracks the virtual memory ranges allocated with this function and automatically accelerates... |
Why do many cuda programs add cudaMemcpy after cudaMallocHost?
Because many CUDA programs were written before the appearance of the unified memory system, and at that time cudaMallocHost allocated page locked memory. That page locked memory still requires an API call for copying. "...accessed directly by the device" ... |
69,060,087 | 69,060,124 | clang-format does not modify file on disk | I have the following badly formatted file, test.cpp
#include "maininclude.h"
int main() {
class SIMPLE smpl;
for (int i = 1; i < 100;
i++) {
printf("Printing %d", i); // Trying out different stuff...
getchar();
}
}
on which I want to run clang-format. Prior to running this, to visually see ... | From man clang-format:
-i - Inplace edit <file>s, if specified.
|
69,060,639 | 69,060,711 | Does std::move called on a prvalue deconstruct the object? | I 've wrote such code applying std::move to a prvalue from a temporary constructor.
// a std::string instance in class Obj
Obj&& myObj1 = std::move(Obj(1,"lost"));
print(myObj1);
Obj&& myObj2 = Obj(2,"keep");
print(myObj2);
And the print effects is like that (print also in constructor and destructor):
Cons... | std::move is a function call; it's not a magical operator of C++. All it does is return a reference to the object it is given. And it takes its parameter by reference.
In C++, if you have a prvalue, and you pass it to a function that takes a reference to it, the temporary created by that prvalue will only persist until... |
69,061,007 | 69,062,139 | Trying to get user input to move sprite in Cocos2D-X | I'm trying to make user input of WASD move a sprite around in Cocos2D-X. I'm pretty sure I'm doing everything correct but it gives me this error:
expression must be a modifiable lvalue.
Here is my code (Note: I'm new to Cocos2D-X, so it might be a bit messy)
float playerX = visibleSize.width / 2 + origin.x;
float playe... | Try to use mutable specifier(which allows lambdas body to modify the objects captured by copy, and to call their non-const member functions):
float playerX = visibleSize.width / 2 + origin.x;
float playerY = visibleSize.height / 2 + origin.y;
auto player = Sprite::create("sprites/player.png");
if (player == nullpt... |
69,061,614 | 69,061,701 | how to create factory function (returning rvalue) | I wrote this piece of code:
class widget_12 {
public:
//reference qualifiers example
void dowork()&
{
std::cout << "*this is lvalue\n";
}; // this version of dowork applies when *this is lvalue
void dowork()&&
{
std::cout << "*this is rvlaue\n";
}; // -||- *this is rvalue
... | Were you trying something like this?
https://godbolt.org/z/TPEWe3eKv
#include <iostream>
class widget_12 {
public:
//reference qualifiers example
void dowork() &
{
std::cout << "*this is lvalue\n";
}; // this version of dowork applies when *this is lvalue
void doword() &&
{
std... |
69,061,633 | 69,061,820 | Can't use if constexpr | My code below produces the following error:
C2131: expression did not evaluate to a constant.
template<int32_t M, int32_t N>
[[nodiscard]] constexpr double determinant(const Matrix<M,N> & m)
{
double det = 0;
if constexpr(m.rows() == 2)
{
return m[0][0]*m[1][1] - m[0][1... | If Matrix<M, N> defines rows() to return M, just replace
if constexpr (m.rows() == 2)
with
if constexpr (M == 2)
m.rows() does not produce a constant expression even if rows() is marked as a constexpr because m is a reference. Here is an explanation why.
|
69,061,756 | 69,061,828 | How to add string to stringstream? | I need to merge a lot of strings into one.
Something like this
stringstream ss;
string str_one = "hello ";
string str_two = "world!\n";
ss.add(str_one);
ss.add(str_two);
string result = ss.str();
but there is no add function into stringstream. How do I do this?
| stringstream has operator<< overload to insert data into the stream. It would return a reference to the stream itself so you can chain multiple insertions.
ss << str_one << str_two;
std::cout << ss.str(); // hello world!
As an alternate, you can leverage fold expression(since C++17) to concatenate multiple strings.
te... |
69,061,874 | 69,062,001 | Get the remainder with the % operator | I’m a beginner to programming & C++.
I’ve recently been learning about the basic arithmetic operators and just got to the end of the chapter, where it was a project exercise.
The exercise:
You are making a program for a bus service.
A bus can transport 50 passengers at once.
Given the number of passengers waiting in t... | Let's say for example that each bus has 50 seats, and your input is 110. When you divide the input by the max_cap, you will get 2. than, when you multiply the result (2) by max_cap, you will get 100. When you substract the result from the input, you will get 10.
int main()
{
int input = 110; // the number of pa... |
69,061,997 | 69,127,823 | CUDA separable compilation + shared libraries -> Invalid device function / segfault | I'm trying to use CUDA separable compilation in my project. The project is composed of a binary that depends on a few shared libraries (all built in the same build system). These shared libraries in turn use common CUDA code. When running the binary, I get a segfault similar to here. When I create a minimal example, I ... | After contact with Nvidia, I finally found the solution to the problem:
Add -Xcompiler -fvisibility=hidden to each of the dlink commands
$NVCC -gencode=$GENCODE -dlink -Xcompiler -fvisibility=hidden common.cu.o a.cu.o -o a.dlink.o
$NVCC -gencode=$GENCODE -dlink -Xcompiler -fvisibility=hidden common.cu.o b.cu.o -o b.dli... |
69,062,232 | 69,062,488 | Why can't I update my class properties in C++? | I'm making a Wizard game prototype and I came across an issue:
I created a class called Wizard and a class called Goblin:
class Wizard
{
public:
int damage;
int health;
int stamina;
Wizard(int d, int h, int s)
{
d = damage;
h = health;
s =... | In your constructors and set* methods you need to assign input parameter values to the member variables of classes. Not vice versa.
#include <iostream>
class Wizard
{
public:
int damage;
int health;
int stamina;
Wizard(int d, int h, int s)
{
damage = d;
... |
69,062,533 | 69,062,757 | C++ Inheritance: arguments of derived class type in virtual function with base class types | I'm having a rough time with a particular C++ inheritance problem. Say we have two abstract classes, one using the other as argument type for one of the pure virtual functions:
class Food {
public:
int calories=0;
virtual void set_calories(int cal)=0;
}
class Animal {
public:
int eaten_calories=0;
vi... | If you pass around a polymorphic type (like Vegetables) as a base type by value (like Food f), you will slice the object, which prevents overriden methods from being called.
You need to pass such types by pointer or by reference instead, eg:
class Food {
public:
virtual int get_calories() const = 0;
};
class Anima... |
69,062,579 | 69,062,924 | Is using placement new with variable on the stack is correct? | Let's take a look to this code:
A a(123);
new(&a) A(124);
Test says that in this case when program is shutting down destructor ~A() will called once. So if in A we has some pointers as fields we will get memory leak.
A a(123);
a.~A();
new(&a) A(124);
Here all will be correct. But according to standard using object a... |
Can I take an address of object which destructor has been called?
[edited:]
Such an address is valid so if you have a pointer to it, it is valid.
Can you take its address after the fact, I am not fully sure.
basic.life.6 […] After the lifetime of an object has ended and before the storage which the object occupied i... |
69,062,842 | 69,063,411 | format_to_n result size type should be std::size_t instead of int | I am experimenting with std::format_to_n and when I tried to compile example from:
https://en.cppreference.com/w/cpp/utility/format/format_to_n
in VS2019:
#include <format>
#include <string_view>
#include <iostream>
int main()
{
char buffer[64];
const auto result =
std::format_to_n(buffer, std::size... | Your std::format_to_n returns a std::format_to_n_result<char*>. The type of the result is defined like this:
template<class OutputIt>
struct format_to_n_result {
OutputIt out;
std::iter_difference_t<OutputIt> size;
};
And std::iter_difference_t<char*> is std::ptrdiff_t (which is evidently the same as int on yo... |
69,063,263 | 69,067,345 | How to implement insertion linked list sort - sort by age | How would I implement a sort insertion here, I've been trying for a while to no success.
The 'isEmpty' method checks if the head == NULL, and insert at first method points the pointer to NULL after inserting the details entered by the user.
void insert(Person *&head, Person *&last, int age, string name, string surname,... | Avoid creating an unsorted list in the first place: make sure any new node is immediately inserted in the right spot, keeping the list sorted.
Assuming all your other code is fine, you can do that as follows. Replace these lines:
temp->next = NULL;
last -> next = temp;
last = temp;
...with this:
if (age <= head->ag... |
69,063,434 | 69,063,501 | How to change gl_PointSize in the vertex shader? | I'm optimizing my particle renderer to work with GL_POINTS and now I need to adjust the size of the points using gl_PointSize in the vertex shader to scale the particles the right amount from the vertex shader.
This is the vertex shader I have now:
#version 330 core
layout (location = 0) in vec3 position;
layout (loca... | You have to enable GL_PROGRAM_POINT_SIZE (see glEnable and gl_PointSize):
glEnable(GL_PROGRAM_POINT_SIZE);
|
69,063,548 | 69,063,845 | Can comparison operator be defaulted outside of class definition in C++20? | Starting from C++20, the compiler can automatically generate comparison operators for user classes by means of operator ==() = default syntax. But must this operator be defaulted only inside the class definition or can it be after the class definition as well?
Consider the program:
struct A { friend bool operator==(A,A... | P2085R0 removed the requirement on the defaulted comparison operator to be defaulted on the first declaration. Clang currently doesn't support this proposal:
See also https://reviews.llvm.org/D103929
|
69,063,938 | 69,064,554 | Building a submatrix from a matrix | I'm trying to split a matrix given into 4, but I'm getting some errors and I can't figure out why. I'm kind of new to the language. Does anybody knows what am I doing wrong?
void split_tl(T **matrice, unsigned int dim){
if(dim == 1){
return;
}
T **tl = new T*[dim/4];
for(unsigned int i = 0; i<d... | If dim is the side of a matrix, allocating to a quarter matrix should be dim/2.
Below in the code you are using :
if((i<dim/2) && (j<dim/2)){
tl[i][j] = matrice[i][j];
}
here tl may exceed the allocation
|
69,064,456 | 69,064,559 | Overloading << and >> operators: The program compiles but running it doesn't accept input | I am trying to implement a Fraction class, which calculates the product of two fractions. It compiles fine but doesn't accept input and abruptly ends.
Here is my code:
#include<iostream>
#include<cmath>
using namespace std;
class Fraction{
int m_numerator{0},m_denominator{1};
public:
Fraction(int numerator=... | The problem is the const qualifier on the second argument of your operator>>. First, this seems a bit weird, as you want to modify the values when they are given as input. Second, as there is no default overload for the >> operator that takes a const int operand, the best (only?) match for the internal >> operations is... |
69,064,820 | 69,065,101 | Can I use one lambda function in C++ to get the best and worst score of my array? | I'm practising lambda function in C++, so I'm trying to get the best and the worst score of some students.
I got the best score, but I'm asking myself if I can get the worst score from the same used lambda function, or should I create another score for the worst student?
If I can do this, how can I do it?
Here is my co... | If you want to get both the minimum and maximum value of a container you can simply use the std::minmax_element algorithm, since it is more efficient than calling std::min_element and std::max_element separately.
The code becomes something like
#include <algorithm>
#include <array>
#include <iostream>
#include <string>... |
69,065,093 | 69,065,137 | Fix for C++ Compiler Error - multiple definition | i am trying to make a program that gave you sum of array elements absolute value .
this is the header file :
#include <iostream>
using std::cin,std::cout,std::endl;
#pragma clang diagnostic push
#pragma ide diagnostic ignored "cppcoreguidelines-narrowing-conversions"
void getAbsSum(int arr[10]){
int abs = 0,sum = 0;
i... | The .h and the .cpp files are inverted. The code should be in the .cpp, and the declaration, in the .h header.
getAbsSum.h:
void getAbsSum(int arr[10]);
getAbsSum.cpp
#include "getAbsSum.h"
#include <iostream>
using std::cin,std::cout,std::endl;
#pragma clang diagnostic push
#pragma ide diagnostic ignored "cppcoregu... |
69,065,307 | 69,065,439 | How to change the type/typedef of a class member dynamicly? | Follwing Problem. I am working on a bigger c++ project. That project has a central dataClass: mal::FrameAudio and the data class looks like this:
class FrameAudio {
public:
typedef Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic> pluginType;
...
const pluginType& getPlug() const;
void setPlug(const plu... | You can not change the type of an object dynamically, C++ doesn't allow that. So much up front.
Now, using a template is probably the right way to go. Point is, you probably can not change this while keeping the code the same, which is what you're effectively asking for. Instead, you can write similar code but with the... |
69,065,399 | 69,065,428 | Timing of std::find() in standard containers | I am trying to time the std::find() function for std::unordered_set, std::set, and std::vector. But the results are strange to me.
It takes more time to find an element in an unordered_set than a vector.
In theory, the time complexity for searching should be O(1) for unordered_set and O(n) for vector.
So, should it be ... |
Did I do something wrong?
You did.
std::find performs the search by iterating over all elements. It doesn't have any special knowledge of std::[unordered_]set and other containers.
To properly search in a set, you need to use its own .find() member function.
|
69,065,454 | 69,083,506 | How to understand destructor of scoped_lock?Does cppreference make a mistake? | ~scoped_lock()
{ std::apply([](auto&... __m) { (__m.unlock(), ...); }, _M_devices); }
How to understand [](auto&... __m) { (__m.unlock(), ...);? I don't understand the ... in lambda and I don't know how this implement release mutexes in reverse order.
Just as @HolyBlackCat say,
(__m.unlock(), ...) means (__m1.unloc... | I believe that cppreference.com is incorrect in this detail. C++17 says:
~scoped_lock();
Effects: For all i in [0, sizeof...(MutexTypes)), get(pm).unlock()
which implies that the locks are released in the same order they were taken.
Note that to prevent deadlock, releasing locks in the reverse order of acquiring them... |
69,065,635 | 69,066,273 | I got red underline on "#include <iostream>" using C++ | I don't know why I got red underline on #include <iostream>. I use VSCode for IDE and C/C++ has installed. My code is very basic but I don't know why it still have red underline.
My code :
#include <iostream> //This line got red underline.
using namespace std;
int main() {
cout << "Hello";
retern 0;
}
Whil... | 'g++' is not recognized as an internal or external command, operable program or batch file.
This is because the g++ compiler is not installed (and/or not added to the PATH environment variable, this will probably help you). MinGW is the GCC (GNU Compiler Collection) adaptation for Windows, and thus should be used.
Con... |
69,065,716 | 69,065,744 | I'm trying to print my array but i'm not getting my desired result | I'm fairly new to programming and was trying to create a program which creates a one dimensional array with random numbers from a certain range and then prints it out. I managed to make a function to create the array but I'm having trouble actually printing out the array I made. I have a general idea of what the proble... | There are two errors in your code:
You are not returning your array from create()
Your loop condition is incorrect.
Fixed code:
#include <iostream>
using namespace std;
int *create(int n)
{
int *arr = new int [n];
for (int i = 0; i < n; i++)
{
arr[i] = rand() % 100;
}
return arr;
}
... |
69,065,747 | 69,065,846 | I am unable to get my code to get the stride of 7 to work properly C++ | The question I am trying to solve is the following:
Write a function that traverses (and prints) the element of an array with stride =7. To do this the update part in the loop will be i= (i+7) % n, where n is the array size.
Would this function visit all elements of the array? Try different array sizes to check when i... | The problem is in StrideArray you read back the modified values of arr.
void StrideArray(int arr[], int n)
{
int i = 0;
int puffer=new int[n];
for (int j = 0; j < n; j++)
{
i = (i + 7) % n;
puffer[j] = arr[i];
}
for (int j = 0; j < n; j++){
puffer[j] = arr[j];
}
d... |
69,065,748 | 69,067,709 | Why can't `ld` find `glfw3` even though my system has `/usr/lib/libglfw.so.3` file? | I was trying to build a file using:
$ g++ tutorial.cpp -lGL -lGLEW -lglfw3 -lm -o tutorial
And was getting:
/usr/bin/ld: cannot find -lglfw3
collect2: error: ld returned 1 exit status
I checked the package and the file were already there:
$ pacman -Ql glfw-x11
glfw-x11 /usr/
glfw-x11 /usr/include/
glfw-x11 /usr/... | Simply because it’s libglfw.so and the linker searches for libglfw3.so because you specified -lglfw3. Use -lglfw instead.
|
69,065,851 | 69,065,994 | msvc and fold expression | I'm having trouble compiling this code on Windows.
This code compile correctly on Linux, both with clang and gcc. I'm using msvc 19.29.
Msvc exit with the not so helpful error C1001.
struct Object{};
class Storage {
Object &createObject() {
qStorrage.push_back(Object{});
return qStorrage.back();
... | C1001 is Internal Compiler Error.
It is used to indicate bugs in the compiler itself, the code being compiled is not necessarily wrong.
Report ICE to https://developercommunity.visualstudio.com/ or via Help > Send Feedback > Report a problem... from Visual Studio
Try to reduce what exactly produces ICE. This will help ... |
69,066,475 | 69,068,500 | range_value_t for reference type | I was playing with C++ 20 ranges and noticed something weird (reproducible at https://gcc.godbolt.org/z/4Ycxn88qa):
#include <vector>
#include <utility>
#include <string>
#include <ranges>
#include <type_traits>
int main()
{
using KV = std::pair<std::string, std::string>;
std::vector<KV> v;
auto r = v | s... |
Is range_value_t supposed to always give me a decayed type?
The value_type of an iterator (and, consequently, a range) should always be a cv-unqualified type, yes. That's just the way that the model works. This isn't really specified in the standard library anywhere to my knowledge, but you can see that the value_typ... |
69,066,546 | 69,066,585 | How to do string concatenation efficiently in C++? | I have a single string that i need to do a couple of concatenations to. This is my first time dealing with strings in cpp and the methods I need to use seems to be taking a char* and not std::string. this is what i need to do:
String folderpath = "something";
folderpath +="/"+dbName;
mkdir(folderpath);
foo(folderpath +... | std::string has a c_str() method for getting a const char* pointer, eg:
std::string folderpath = "something";
folderpath += "/" + dbName;
mkdir(folderpath.c_str());
folderpath += "/" + dbName;
foo((folderpath + ".index").c_str());
bar((folderpath + ".db").c_str());
That being said, in C++17 and later you should use th... |
69,066,787 | 69,066,831 | What is the fastest way to see if an array has two common elements? | Suppose that we have a very long array, of, say, int to make the problem simpler.
What is the fastest way (or just a fast way, if it's not the fastest), in C++ to see if an array has more than one common elements in C++?
To clarify, this function should return this:
[2, 5, 4, 3] => false
[2, 8, 2, 5, 7, 3, 4] => true
[... | (✠Update Below) Insert the array elements to a std::unordered_set and if the insertion fails, it means you have duplicates.
Something like as follows:
#include <iostream>
#include <vector>
#include <unordered_set>
bool has_duplicates(const std::vector<int>& vec)
{
std::unordered_set<int> set;
for (int ele : ve... |
69,066,789 | 69,067,574 | READ_ONCE and WRITE_ONCE in Parallel programming | In the book "Is Parallel Programming Hard, And, If So,What Can You Do About It?", the author uses several macros that I don't understand what they actually do.
#define ACCESS_ONCE(x) (*(volatile typeof(x) *)&(x))
#define READ_ONCE(x) \
({ typeof(x) ___x = ACCESS_ONCE(x); ___x; })
#define WRITE_ONCE(x, val) \
do { ACC... | These macros are ways to enforce some level of atomicy (but no synchronization) on supporting compilers (GCC, maybe some others). They are used heavily inside Linux as it predates C11 by a huge margin.
In GCC semantics, volatile results in emitting exactly one instruction accessing the pointed-to value (at least if tha... |
69,067,210 | 69,067,328 | Can you time when x increments within a for() loop? (Beginner) | I've tried to implement millis(); like such down below, but each variation failed.
void ledMode(byte mode)
{
unsigned long currentTime = millis();
if (currentTime - previousTime >= Interval)
{
switch (mode)
{
case 1:
digitalWrite(RLED, HIGH); //Red
digitalWrit... | You can do such things, but your code doesn't. It doesn't wait until the time you want has elapsed, it just checks – and if that didn't happen, it just moves on: that's literally what you implemented!
This looks a lot like arduino code (this isn't just C++, it uses Arduino functionality; be sure you can tell the langua... |
69,067,307 | 69,067,472 | Compile C++ project with all dependencies into a single binary file | I have a C++ project and I want to compile it into a single binary file which contains all the shared libraries, third-parties, and so on.
I want to move the compiled file into different servers without installing any dependencies. That's why I need an all-in-one/bundled binary file.
For example, I've tried to compile ... | Normally you would use g++ sample.cpp -o sample -static -lyaml-cpp.
But it seems Arch tends to not include static libraries in their packages. Your options are:
Build yaml-cpp yourself to get a static library.
Distribute the dynamic library along with your executable.
To avoid having to install it in system directori... |
69,067,474 | 69,067,619 | C++ Two Classes Template Methods Reference (Not Compose) Each Other | I've gotten into a bit of a design block in a C++ program of mine as two different header files are required to reference each other. Typically a forward declaration would be used here, but since both classes use template functions/constructors a forward declaration cannot be used as methods/variables from both classes... | Forward declarations will indeed work for your problem. The key is that function templates can be defined out of line (i.e., not in your class ... { }; declaration) legally. The same can be achieved for arbitrary functions using the inline keyword.
To now solve your specific problem, just split Application.hpp into App... |
69,067,728 | 69,067,875 | Excess elements in scalar initializer when adding to vector | I have a vector which has the uint8_t type.
std::vector<uint8_t> vec;
I'm trying to emplace back data given in the callback function to this vector using this way,
void callback(const uint8_t data[], size_t size)
{
vec.emplace_back(data, data + size);
}
However, it fails to compile and I'm getting... | emplace_back appends single element to the vector, and its arguments are actually arguments for its constructor. To append many elements at once, use insert, like:
vec.insert(vec.end(), data, data + size);
|
69,067,784 | 69,068,331 | What does this External Linkage directive mean? | Can someone explain this note in C++ primer 5th edition to me:
Note
The functions that C++ inherits from the C library are permitted to be defined as C functions but are not required to be C functions—it’s up to each C++ implementation to decide whether to implement the C library functions in C or C++.
| I will give you an example of one function, that could be "treated" as C or C++. std::toupper() can also be written as toupper(). I believe the first one uses some safety checks of C++, while the other one is strictly C. But what it boils down to is:
#include <cctype>
#include <iostream>
int main (void) {
char c =... |
69,067,872 | 69,068,122 | Reading subclass instance of superclass from iostream. How does >> operator know which subclass? | I have a superclass Element with multiple subclasses, let's call them A and B. I want to overload << and >> so I can save and load my objects.
class Element
{
public:
Element();
int superProperty;
virtual void write(iostream &out)
{
out << superProperty;
}
virtual void read(iostream &in)
{
... | In essence, that’s what any serialization solution will boil down to. Elegance may be improved a bit though but using code generation may still be better (serialization frameworks do that).
The dynamic cast can definitely be avoided using a virtual function or a map (type_index to tag 1). The switch can be replaced wit... |
69,067,984 | 69,068,057 | C++ Heap memory in array assignment only messing up for the first array and not the second | I have an assignment to create two functions in an array class named insert and print. Insert should add elements to the end of the array and when I run the code, I get output that looks fine for the second array but the first array gives strange output. I don't really know where to go from here and any pointers help
... | You do not initialize the allocated array in
arr = new int[capacity];
so its content is garbage.
Then in your insert() you attempt to insert the element in ascending order, but you do NOT move existing elements up; you simply overwrite them.
Your print the prints that garbage.
The second test case works because your e... |
69,068,297 | 69,068,325 | Hide macros from other headers | Suppose I have this:
// test.h
namespace test {
#define TEST_DEBUG !NDEBUG
class TestClass {
#if TEST_DEBUG
// ...
#endif
};
}
The problem is that other files that include test.h will also get the TEST_DEBUG macro, which is not ideal.
If I use #undef at the end of the header,... | Although I'd advise avoiding macros in C++ (eg this could be replaced with a bool parameter to the function), the simplest way to achieve this is to define TEST_DEBUG in test.cpp before including test.h, and removing it from test.h.
A #include directive is replaced by the c preprocessor similar to a "copy the contents ... |
69,068,486 | 69,083,795 | How to interleave 3 float vectors into an array with AVX intrinsics C++ | I have 3 __m256 vectors x, y, z filled with 8 elements of data each (single precision floats),
and I'd like to store them interleaved into memory [x0, y0, z0, x1, y1, z1, ...].
What are the relevant and useful operations to use to store them into a (possibly unaligned) array or std::vector?
The brute force way is obvio... | typedef __m256 f256;
typedef __m256i i256;
#define set8i _mm256_setr_epi32
inline f256 permute8f(const f256 a, const i256 choice) {
return _mm256_permutevar8x32_ps(a, choice);
}
template<bool c0, bool c1, bool c2, bool c3, bool c4, bool c5, bool c6, bool c7>
inline f256 select8f(const f256 tr, const f256 fr)
{... |
69,069,176 | 69,069,332 | constexpr in class without static | I have a situation where I need to store a compile time constant in a header, and I do it in the class I'm using it in as I don't want to expose the constant to other files that include this header. (as well as the fact that it depends on another hidden struct)
Like this:
namespace ns {
class bla {
private:
... | Adding static should be perfectly fine for your use case. That's what the reference states too:
A constexpr specifier used in a function or static data member (since
C++17) declaration implies inline.
And since this is a compile-time constant, you might as well have it shared across all class instances rather than on... |
69,069,571 | 69,069,743 | How does std::bind take variadic arguments by value, even with its universal reference? | The function signature for std::bind() is as follows:
template< class F, class... Args >
/*unspecified*/ bind( F&& f, Args&&... args );
So args is a variadic template universal reference, if I understand correctly. The traditional template type deduction rules for universal references are as follows:
If the argument ... | It has almost nothing to do with the signature, it is a design choice. std::bind must of course store all its bound arguments somehow and it stores them as values. The "universality" is only used to properly construct them - by move or copy.
std::ref is also stored by value but due to its nature, the wrapped object is ... |
69,069,869 | 69,070,113 | UIAutomation GetTopLevelWindowByName | Trying to follow the example found here:
https://learn.microsoft.com/en-us/windows/win32/winauto/uiauto-howto-find-ui-elements
WCHAR window_name[250] = L"tools";
IUIAutomationElement *window = GetTopLevelWindowByName(window_name);
IUIAutomationElement* GetTopLevelWindowByName(LPWSTR windowName)
{
if (windowName ==... | You must create g_pAutomation, it cannot be null, for example like this:
CoCreateInstance(
__uuidof(CUIAutomation),
NULL,
CLSCTX_ALL,
_uuidof(IUIAutomation),
(void**)&g_pAutomation);
|
69,070,129 | 69,070,911 | Does virtual `operator <=>` with default implementation make one more virtual method in C++20? | If one makes virtual C++20 three-way comparison operator <=> with the default implementation, then the compiler silently makes one more virtual operator==, as can be shown by overriding it in a child class:
struct A {
virtual std::strong_ordering operator <=>(const A &) const = default;
};
struct B : A {
virt... |
Is it mandated by the standard or just a common implementation practice?
It is mandated. [class.compare.default]/5:
If the member-specification does not explicitly declare any member or friend named operator==, an == operator function is declared implicitly for each three-way comparison operator function defined as ... |
69,070,233 | 69,070,798 | What should I do to make my container work with ranges? | I have a simple container:
template <class T, class Allocator = std::allocator<T>>
class ring
{
public:
using value_type = T;
using allocator_type = Allocator;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = T &;
using const_reference = const T &;
us... | So... after a lot of investigation:
Your iterator must have a public default constructor.
What should I do to make my container work with ranges?
It should satisfy the concept std::ranges::range:
static_assert(std::ranges::range<ring<int>>);
but it doesn't and the error messages are not helpful. So we look at the c... |
69,070,868 | 69,071,065 | Does stbi_load() have a limit on the number of pixels of the read picture | I use stbi_load() failed to load the picture, but no error was reported.
unsigned char* data = stbi_load("world_test.jpg", &width, &height, &nrChannel, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
cout ... | The header file itself has something to say on this:
// Note that stb_image pervasively uses ints in its public API for sizes,
// including sizes of memory buffers. This is now part of the API and thus
// hard to change without causing breakage. As a result, the various image
// loaders all have certain limits on image... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.