question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
64,162,365 | 64,167,012 | Sporadic crash where backtrace shows destructor call at strange line | I have a program that normally runs just fine, but today it crashed on startup. Running it again immediately afterwards worked just fine, so unfortunately I can't get give a minimal example. However, the code looks something like this:
#include "Configuration.hpp"
#include "Program.hpp"
int main()
... | I was actually able to resolve my own problem here, partially in response to a question from PaulMcKenzie in the comments. To illustrate, here's a toy program:
class C { };
class D
{
public:
~D()
{
int * p = nullptr;
int x = *p;
}
};
class E { };
class F { };
int main(int, char **)
{
C... |
64,162,449 | 64,162,796 | How to set "Start without debugging" in VS in topbar | How can I set "Start without debugging " in the top-bar of the Visual Studio 2019 IDE, instead of "Local Windows Debugger". I find it annoying that every single time I need to press CTRL + F5 to start without debugging.
I looked through settings but I didn't see anything. Maybe I missed something.
| You can add virtually any command to the VS-2019 IDE's toolbars. At the right-hand side of the tooolbar where you want your command to go, click the small down-arrow and select the "Add or Remove Buttons" command from the pop-up:
Then, if the command you want is not shown in the list of 'available' buttons, select the... |
64,162,460 | 64,162,566 | What does the syntax of '...' after the call to std::forward mean? | The function std::forward is declared like so:
template< class T >
T&& forward( typename std::remove_reference<T>::type& t ) noexcept;
Meaning it takes a single argument of type std::remove_reference<T>::type&.
However, std::forward can also be used with variadic arguments:
template <typename... Args>
void f(Args... a... | This is what is called pack expansion. It expands the parameter pack out with commas between each member of the pack so
q(std::forward<Args>(args)...);
says that for each member of the parameter pack args apply std::forward to it. The resulting code would look like
q(std::forward<Args>(args1), std::forward<Args>(arg... |
64,162,722 | 64,162,778 | Can't figure out why line is not being drawn in SDL | This program to draw a line in SDL is not working:
#include "SDL.h"
int main(int argc, char** argv)
{
SDL_Window* window = SDL_CreateWindow("A line", 10, 10, 1200, 600, false);
bool running = true;
while (running)
{
SDL_Event events;
if (SDL_WaitEvent(&events))
if (events.... | A few issues:
You're missing a SDL_RenderPresent() so nothing is ever actually drawn to the screen.
As @tkausl points out, don't create (& leak) a SDL_Renderer every frame
Use SDL_PollEvent() in a loop to fully drain the event queue.
SDL_SetRenderDrawColor() affects SDL_RenderClear() as well as SDL_RenderDrawLine(); a... |
64,163,139 | 64,163,572 | Decimal to binary without arrays and binary-operators (like "&") | I have to do a task for the university to write a program that converts a decimal number into binary. As I am only in a preliminary course of computer science, there were no arrays or bitwise operators (like '&') introduced yet. The program needs to be written using basic operators (+,-,*,%) and (if-else,for) only. My ... | Your current code checks for presence of the binary value from LSB to MSB, and prints in that order. One way to approach the issue would be to instead check from MSB to LSB.
#include <iostream>
int main(){
int n, a=1;
std::cin >> n;
while(2*a <= n)
a *= 2; ... |
64,163,621 | 64,174,226 | How can you have multiple lines or statements inside a C++ pack expansion? | Suppose that I have some simple code like the one below, which just prints all of the values in a tuple and keeps track of the current iteration.
#include <iostream>
#include <tuple>
#include <utility>
using std::cout;
int main() {
std::tuple<int, double, size_t, unsigned, short, long long, long> my_tuple(7, 4, 1... | It reads much better if you declare the lambda separately and then fold over invoking it:
auto f = [&](auto& value){
cout << i << ", " << value << "\n";
++i;
};
(f(current_value), ...);
You can also use something Boost.Mp11's tuple_for_each to avoid a layer of indirection:
size_t i = 0;
tuple_for_each(my_tuple... |
64,164,141 | 64,164,303 | Assign custom string to string attribute in C++ | So, I have a struct:
typedef struct _connection {
int socket; // host-to-client socket id.
struct sockaddr address; // address of client.
int address_length; // length of address field.
std::string user;
std::string group;
int connected;
}
and a main code where co... | You can construct a temporary std::string that will be move assigned (instead of copied) into s.user directly like below. The potentially dangerous creation of s from the not necessarily null-terminated buffer is not needed:
#include <algorithm>
#include <iterator>
s.user = std::string(std::begin(buffer), /... |
64,164,250 | 64,164,496 | What is wrong with my 2D Array Gaussian Blur function in C++? | I am making a simple Gaussian blur function for a 2D array that is supposed to represent an image. The function just prints out the array values at the end (no actual image processing going on here). I was pretty sure that I had implemented everything correct, but the values I am getting for (N=3, sigma=1.5) are much l... | Why does s depend on change? I think you should do:
double r, s = 2 * sigma * sigma;
// instead of
// double r, s = change * sigma * sigma;
|
64,164,453 | 64,164,819 | Is there any reason to prefer signed or unsigned integers to represent lists of bits? | Is there any reason to prefer signed or unsigned integers over the other to represent lists of bits?
I believe people tend to use unsigned for this more: for example, C++'s bitset converts to and from unsigned long.
Is this an arbitrary decision, or is unsigned better?
| Using an unsigned type for integers representing bits is preferred. You'll often use the bit shift operators << and >> on these integers, and these operators have well defined behavior on unsigned integers (provided you don't shift more than the number of bits or by a negative amount).
If you use << and >> on signed i... |
64,164,454 | 64,225,356 | Select tab text in QTabBar | How can the text of a tab in a QTabBar be selected using the mouse?
The text within a QLabel can be selected as described here: Make QLabel text selectable?, but I haven't found a similar with to do this for QTabBar tab text.
The documentation for QTabBar can be found here: https://doc.qt.io/qt-5/qtabbar.html. It menti... | Qt does not nativelly propose to make QTabBar text selectable.
However, they let you add your own widgets to the tab itself using QTabBar::setTabButton. Then, you can create the tab with no title (""), and then add a QLabel with your title and make it be selectable.
Note that clicking the QLabel itself does not change ... |
64,164,651 | 64,233,201 | How to reuse Stack Allocator in RapidJSON without reallocating memory | I'm running a single-threaded system in FreeRTOS with limited resources.
I already preallocate buffers for the RapidJSON allocators as so:
char valueBuffer[2048];
char parseBuffer[1024];
rapidjson::MemoryPoolAllocator<FreeRTOSRapidJSONAllocator> valueAllocator (valueBuffer, sizeof(valueBuffer))
ra... | I resolved this by creating a custom allocator. Essentially a copy of rapidjson::MemoryPoolAllocator with the addition of the following method:
void Reset()
{
chunkHead_->size = 0;
chunkHead_->next = 0;
}
Which should be called every time you're done with the last string that was parsed.
|
64,165,156 | 64,176,688 | How to find the point that gives the maximum value fast? Java or c++ code please | I need a fast way to find maximum value when intervals are overlapping, unlike finding the point where got overlap the most, there is "order". I would have int[][] data that 2 values in int[], where the first number is the center, the second number is the radius, the closer to the center, the larger the value at that p... | This can be done with a simple O(n log n) algorithm.
Consider the value function v(x), and then consider its discrete derivative dv(x)=v(x)-v(x-1). Suppose you only have one interval, say {3,3}. dv(x) is 0 from -infinity to -1, then 1 from 0 to 3, then -1 from 4 to 6, then 0 from 7 to infinity. That is, the derivative ... |
64,165,318 | 64,165,461 | Accessing property map for surface mesh | I have a CGAL::Surface_mesh<Point_3> to which I added a property map
Mesh::Property_map<Mesh::Face_index, CGAL::Color>
color_map = tin_colored_mesh.add_property_map<Mesh::Face_index, CGAL::Color>("f:color").first;
I had this map populated.
Afterwards, I try to access this property map again as below:
std::string n... | According to the documentation for CGAL::Surface_mesh the property_map member function is a template just as the add_property_map member function that you use above.
As the error states, C++ fails to infer the template argument I that the function template CGAL::Surface_mesh::property_map expects. A potential solution ... |
64,165,974 | 64,166,071 | std::vector with a number in the second template parameter, can't find the definition on the c++ refernce | I think I have asked this question long time ago, but can't find it.
I see this code snippet.
template <
unsigned int N
>
class pyramid_down : noncopyable
{
public:
COMPILE_TIME_ASSERT(N > 0);
template <typename T>
vector<double,2> point_down (
const vector<T,2>& p
) const
{
... | It is not std::vector.
std::vector does not accept an integer in its 2nd template parameter, nor does it have an operator- defined, so clearly the vector in this example is not std::vector but is a different type of vector. Maybe a mathematical vector, or a graphical vector, who knows. There is no way to know from the ... |
64,166,015 | 64,166,150 | Add method specialization for all enumeration classes in C++ | I have the following methods (broadly speaking) in my bitstream class:
class BitStream
{
void StoreBits( unsigned int data, unsigned int numBits );
public:
template<typename T>
void WriteType( T value ) { StoreBits( value, sizeof(T) * 8 ) );
template<>
void WriteType( float value ) { Store... | Test to see if the type is an enum and if it's not convertible to u32. This allows you to distinguish between normal enum and enum class. If it's an enum but is not convertible to u32, then it's an enum class:
template<typename T>
inline void BitStream::WriteType(T value)
{
if constexpr (std::is_enum_v<T> && !std:... |
64,167,285 | 64,170,966 | What are the rules for a valid dereferencing of a null pointer? | #include <iostream>
struct X
{
bool isNull() { return this == nullptr; }
bool isNullConst() const { return this == nullptr; }
};
bool isNull(X& x) { return &x == nullptr; }
bool isNullConst(const X& x) { return &x == nullptr; }
// always false or exception.
bool isNullCopy(X x) { return &x == nullptr; }
in... |
What are the rules for a valid dereferencing of a null pointer [in C++]?
C++ standard is actually somewhat non-specific about whether indirecting through a null pointer is valid by itself or not. It is not disallowed explicitly. The standard used to use "dereferencing the null pointer" as an example of undefined beha... |
64,167,312 | 64,167,629 | how would you optimize this vectorized sum of harmonics? | I'm summing a bounch of harmonics together, with different phase/magnitude each, using vectorization (only SSE2 max as SIMD).
Here's my actual try:
float output = 0.0f;
simd::float_4 freqFundamentalNormalized = freq * (1.0f / sampleRate);
simd::float_4 harmonicIndex{1.0f, 2.0f, 3.0f, 4.0f};
simd::float_4 harmonicIncrem... | The second part of the question is the easiest. Any harmonic with magnitude 0 does not affect the sine output, so you just pad mMagnitude to a multiple of 4.
As Damien points out, sin(x) is expensive. But by Euler, exp(x)=cos(x) + i sin(x), and exp(x+dx)==exp(x)*exp(dx). Each step is just a complex multiplication.
|
64,167,338 | 64,167,392 | Container contains function? | Sometimes I want check if a std::unordered_map container contains an element, that's all I want to know, I don't want an iterator, I don't want to check the iterator against end(). Say for std::unordered_map<int, int>:
if (mymap.contains(5)) // Do something;
Instead of:
auto it = mymap.find(5);
if (it != mymap.end()) ... | The C++ designers have finally caught on to the fact that this is such a common operation, and have kindly added std::unordered_map::contains to the language in C++20.
If you can't use C++20 yet, you can always write your own implementation as a free function:
template<typename M, typename T>
bool contains(M const &map... |
64,167,417 | 64,171,053 | freading from a file that was fclosed before reading | I spend a sleepless night yesterday trying to track down a bug in my test case. My interface looks something like this:
image read_image(FILE *file) {
if (file == nullptr) {
//throw exception
}
//call ftell and fread on the file
//but not fclose
...
//return an image
}
Turns out one of my test cases t... |
I know calling fread/ftell on a closed file is a dumb idea but could it really cause that kind of memory corruption? I looked around on e.g. cppreference but it was never explicitly specified that passing a closed stream is undefined behavior...
Trying fread or ftell on a FILE* that's been closed will make both fun... |
64,167,637 | 64,167,719 | Is the concept of "reference" different in C++ and Rust? | Code in C++
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Burger";
cout << &food << endl;
return 0;
}
The same code written in Rust:
fn main() {
let food = "Burger";
prinln!("{}", &food);
}
The output for the C++ program:
0x7fff604b2890
The output for the Rust p... | First thing first, in C++ the & (address-of) operator returns a pointer, that is, given T t;, &t will return a T*.
C++ does have references (T&), they are not created via the & operator, I'll point you to this great answer for numerous differences between C pointers and C++ references.
Now to answer your question, the ... |
64,168,193 | 64,168,576 | Using Left Shift operator with ones at the right of the number | I'm not very familiar with bit operators and I have this use case : when we use the left shift operator << in C++ the number will be shifted and 0 will be placed at the right of number, I want to place 1 and not zero at the right.
I mean if I have a number 00000000 and I make << 3 the result need to be 00000111 and not... | Here's a solution that works on any number:
int one_shift(int val, int n) {
return ~(~0 << n) | (val << n);
}
Breakdown:
~0 evaluates to 0xFFFFFFFF e.g. all 1's
~0 << n shifts 0xFFFFFFFF by N places, resulting in a number with N zeroes on the end
~(~0 << n) flips all these bits, resulting in a number with only th... |
64,168,457 | 64,168,707 | Double free or corruption (out) and how to check whether a destructor works properly | I am trying to improve my 2D array to be created using a class. All methods work fine, it is properly printed out and so on, but when I try to create a destructor I either get an error double free or corruption, I am able to get rid of the error message but then I am not sure whether the memory has been de-allocated pr... | Your constructor allocates a top-level array of size rows (3) but then goes on to fill slots (10) elements of it:
cell = new int* [rows];
// Create a row for every pointer
for (int i=0; i<slots; i++)
{
cell[i] = new int[slots];
}
As cell only holds 3 elements, the 7 allocations after firmly corrupt the heap ... |
64,168,594 | 64,169,164 | SDL - Difference between SDL_GetRenderer and SDL_CreateRenderer | Both the functions SDL_GetRenderer(SDL_Window*) and SDL_CreateRenderer(SDL_Window*, int, Uint32) seem to do the same thing: return a pointer to SDL_Renderer from the window. However, what method is more appropriate for the task? The SDL Wiki does not provide much information on where which method should be used, so ple... | SDL_CreateRenderer allows you to create a renderer for a window by specifying some options. It's stored in the specific window data which you can query with SDL_GetRenderer (so the latter is equivalent to (SDL_Renderer *)SDL_GetWindowData(window, SDL_WINDOWRENDERDATA))
If you call SDL_GetRenderer without having created... |
64,168,837 | 64,168,996 | How do I declare and initialize this map<pair<int, int>, bool>? | While I'm trying to create a map data structure with Key as pair<pair<int, int>, bool and Value as int.
When compiled on xcode, build failed with linker errors
When compiled on websites like cpp.sh or godbolt.org, it
throws a template args error
Here's the code:
#include <iostream>
#include <vector>
#include <map>
#i... | There are several syntactic errors in your example, and an ambiguity due to using namespace std; whilst defining an alias in the global namespace with a colliding name (pair).
Here is your code example after:
#include <map>
#include <utility>
typedef std::pair<int, int> Pair;
struct comp {
template <typename T> boo... |
64,169,118 | 64,169,229 | Can GetFileAttributesW handle url-encoded spaces (%20) in file paths? | Function call:
OS_WRAPI::GetFileAttributesW(file_name_str); // file_name_str value is L"C:\\Test%20Tool\\test.exe"
returns INVALID_FILE_ATTRIBUTES.
Function call:
OS_WRAPI::GetFileAttributesW(file_name_str); // file_name_str value is L"C:\\TestTool\\test.exe"
returns valid attributes.
Both paths exist.
How can I get... |
Can GetFileAttributesW handle spaces in filepaths?
Yes.
Note that L"C:\\Test%20Tool\\test.exe" does not contain a space. Probably you should be passing L"C:\\Test Tool\\test.exe".
The documentation says:
If the function fails, the return value is INVALID_FILE_ATTRIBUTES. To get extended error information, call GetLa... |
64,169,258 | 64,169,432 | C++ Print days, hours, minutes, etc. of a chrono::duration | I have the following code:
// #includes for <chrono>, <iostream>, etc.
using namespace std;
using namespace chrono;
int main(int argc, char* argv[]) {
auto sysStart = system_clock::now();
LogInit(); // Opens a log file for reading/writing
// Last shutdown time log entry is marked by a preceding null byt... | When you cannot use fmtlib or wait for C++20 <format>, you at least want to delay the invocation of cout() on durations as much as possible. Also, let <chrono> handle the computation for you. Both measures improve the terseness of the snippet:
const auto hrs = duration_cast<hours>(sysInactive);
const auto mins = durati... |
64,169,693 | 64,169,784 | How to upcast an static std::optional | class Child: public Base {.....}
class Child
{
static std::optional<Base>& Child::GetBaseInstance()
{
static std::optional<Base> instance = std::make_optional<Chid>; \\Does not work. Please help
return instance;
}
}
I'm trying to return an instance but of type of std::optional of it's base... | You cannot use std::optional for references. Instead, either use a raw pointer, a std::reference_wrapper, or boost::optional (which works for references).
That being said, you have another flaw in your snippet: std::optional<Base> suffers from object slicing when constructed from a Child instance. You can read more on ... |
64,170,482 | 64,170,840 | Why is sizeof std::mutex == 40 when cache line size is often 64 bytes | Following static_assert passes in both gcc and clang trunk.
#include<mutex>
int main(){
static_assert(sizeof(std::mutex)==40);
}
Since x86 CPUs have 64 byte cache line I was expecting mutex sizeof to be 64, so false-sharing can be avoided.
Is there a reason why size is "only" 40 bytes?
note: I know size also costs... | Forcing padding where it's not needed would be bad design. Users can always pad if they have nothing useful to put in the rest of the cache line.
You probably want it in the same cache line as the data it's protecting if it's usually lightly contended; only one cache line to bounce around, instead of a 2nd cache miss ... |
64,170,742 | 64,171,294 | How static library in c++ work with name mangle? | I ask this for understanding, In c there is no name mangling but c++ has. How this works for example say I have following files
exlib.hpp header file
exlib.cpp function implemented file
exapp.cpp main function using exlib
File exlib.hpp
#ifndef EXLIB
#define EXLIB
#include <iostream>
int sum(int, int);
int sum(int,... | While C++ offers Polymorphism (i.e. different things can be named equal in the same scope by using other features for distinguishing them), this is not supported by linkers (neither in statical nor dynamical linking). So, C++ compilers uses name mangling. (The other features are used to decorate the original identifier... |
64,170,897 | 64,171,086 | How to keep the end 0 when multiply it by a number in c++ | I have a program like this
cin >> input;
input *= x (a random number just dont care)
cout << input;
So everyting works fine until the input number is 00 then it prints 0
How can you keep the other number 0 ? Thanks in advance.
| I did not understand your question... 0, 00, 000, are the same number but in C++ a number starting with 0 means that the base is octal and not decimal... indeed int a = 08 won't compile. Also note the a number starting with 0x means hexadecimal and since C++20 a number starting with 0b is in binary.
If you want to prin... |
64,171,431 | 64,171,473 | Error: one or more multiply defined symbols found | I am setting up my first proper SDL project and c++ project, but I am getting errors. The last error says one or more multiply defined symbols found. Along with that error, I am getting a bunch of errors, one of them is:
Severity Code Description Project File Line Suppression State
Error LNK2005 "public:... |
I am not sure is main is related to the problem
Oh, yes, it is! :-)
By including game.cpp into main.cpp, you define all the things in game.cpp twice, once in the main object file and once in the game object file. Object files aren't necessary for an implementation but they're common enough to use as an explanation. I... |
64,171,536 | 64,208,330 | Using #include <vector> fails checking R package | I am building a package for R in c++. How can I include libraries in the code?. For example, if I use #include <vector> vector, R check fails with error
> fatal error: vector: No such file or directory
> E> #include <vector>
> E> ^~~~~~~~
> E> compilation terminated.
I have tried using LinkingTo: vector in ... | The most recently added vignette entitled Thirteen Simple Steps for Creating an R Package with an External Library covers the topic you are asking for.
Very broadly, there can be three types of packages with an external library:
header-only, which is easy as you only need to take care of the -I... flag
embedded, which... |
64,171,729 | 64,171,937 | c++ how to pass min() and max() as as constructor argument? | I have a class MyClass, which will use either min() or max() based on what argument is taken during construction,
class MyClass {
private:
myfunc;
public:
MyClass(args);
}
Later myfunc will be used in another method in MyClass, and I would like args can be used to initialize myfunc to be either max or min, won... | I would do it like this:
class MyClass
{
const bool isMax;
public:
MyClass( bool ax ) : isMax( ax ) { }
template<class E>
E apply( E a, E b ) const
{
if( isMax )
return std::max( a, b );
else
return std::min( a, b );
}
};
Technically doable with a funct... |
64,171,816 | 64,172,005 | How can I retrieve the type a templated object was instantiated with? | Problem:
I would like to get the type a templated type was instantiated with. E. g. for std::shared_ptr<int> I want to get int. The approach below works for this simple case. I need to instantiate an object of that type, though. This does not work in some cases, e.g. std::shared_ptr<some_abstract_class> or if the defau... | Yes it is possible. Just use a template class (struct here) instead of the template function. And retrieve the type of the object with decltype and pass it to the template class.
The following is one way to do it:
#include <memory>
#include <type_traits>
template<typename>
struct inner;
template<template<typename>cla... |
64,172,025 | 64,172,545 | Setting-up a 2D array using std::Vector | I have already improved my array from this question in order to be created within a class, I also kind of optimized it using std::vector so it is not allocated on a heap but on a stack and thus it is faster and also I do not have to manage the memory manually.
But I was not able to create a function which would set a v... | As far as I understood your problem, you need an array of arrays (a number of slots), which size is known at compile time. And you prefer it to be on the stack.
I encourage you to use std::array and forget about C-style arrays ([] - these guys). Or better learn the difference between them and make your own mind.
There ... |
64,172,250 | 64,172,515 | create two pointers for template class and work with current selected possible? | I'll try showing what I want with an example code:
template <typename T>
class myclass
{
public:
myclass(int x, int y);
// code
};
main()
{
myclass<cat>* ptr1 = NULL;
myclass<dog>* ptr2 = NULL;
if (/*condition*/)
{
ptr1 = new myclass<cat>(1,1);
delete ptr2... | Templates are a compile time construct. When the template is instantiated, it creates unrelated classes.
As such, myclass<cat> and myclass<dog> are totally different, unrelated classes with you cannot exchange pointers between them.
To mix them up at runtime, you need some form of runtime polymorphism. The simplest is ... |
64,172,500 | 64,187,943 | Internal compiler error (CL version: 14.27.29110) | There is code
#include <array>
struct Foo {
int bar;
};
int main() {
constexpr auto v = std::array{Foo{}};
return 0;
}
While compile whith C++17:
fatal error C1001: Internal compiler error. ... (compiler file 'msc1.cpp', line 1591)
INTERNAL COMPILER ERROR in 'C:\Program Files (x86)\Microsoft Visual Studio\2019... | This looks like the same bug reported on developercommunity.visualstudio.com under Regression: c++ internal compiler error in 16.7.0 with /std:c++17 (compiler file 'msc1.cpp', line 1591). I suggest you upvote that bug report, and keep an eye on it for possible resolutions.
The issue was introduced in the 16.7.0 update,... |
64,172,718 | 64,172,758 | what is the correct and easy way for initialization of class containing array of tuples? | I have a class which contains array of tuples like the following:
template<size_t __v, typename ... __tz>
class turray{
public:
std::tuple<__tz ...> array[__v];
};
It does not have any user defined constructor and I was wondering how can I initialize it.
Please consider the following methods:
int main(){
turra... | You just need to add another pair of braces:
turray<2, int, float> mturray1 { { {1, 1.1}, {2, 2.2} } };
// ^ ^ tuple
// ^ ^ array
// ^ ^ turray
Here's a demo.
|
64,172,875 | 64,173,319 | C++ visual studio C2027 and C2011 errors | I am working on a game engine and got those errors building:
Severity Code Description Project File Line Deletion status
Error C2027 using undefined type 'AssetManager' SharkEngine F: \ Projects \ C ++ \ SharkEngine \ Text.h 10
and
Severity Code Description Project File Line Deletion status
Error C2011 'AssetManager... | Finished to understand the problem, I found out that somewhere else in my code I did a wrong include (#include "SharkEngine/AssetManager.h" instead of "AssetManager.h").
|
64,172,910 | 64,176,584 | Configure Qt project (.pro file) to use PcapPlusPlus | I want to use Pcap++ inside my Qt project.
I've followed steps in the installation & introduction guide of PcapPlusPlus, but there are still unknowns:
How do I implement that in my .pro file : include ../../../Dist/mk/PcapPlusPlus.mk
And that:
all:
g++.exe $(PCAPPP_INCLUDES) -c -o main.o main.cpp
g++.exe $(P... | The idea is to convert the .mk to an appropriate code that qmake understands, for example in my case the .mk is:
PCAPPLUSPLUS_HOME := /home/developer/PcapPlusPlus-20.08
### COMMON ###
# includes
PCAPPP_INCLUDES := -I$(PCAPPLUSPLUS_HOME)/Dist/header
# libs dir
PCAPPP_LIBS_DIR := -L$(PCAPPLUSPLUS_HOME)/Dist
# libs
PC... |
64,173,224 | 64,205,483 | C++ OpenCV VideoWriter frame rate synchronization | I am about to capture frames from a video grabber card. Those frames are processed and written to the HDD.
The whole setting is in a multithreading environment, so the grabber writes the images to a queue, and in another thread, the images is processed and another one writes to hdd. If the image is good by the definiti... | I figured out my problem and it was me, not OpenCV.
Because of the multithreading environment, I was writing the images (cv::Mat) to a queue. Since there are a lot of transformations YUV -> RGB -> BGR -> Crop etc. I was expecting the cv::Mat object I put in the queue was a deep copy. Instead of this, the cv::Mat was al... |
64,173,586 | 64,221,368 | Cross compiler link in Docker container | I have some troubles using a docker container in order to cross compile a program with visual studio 2019.
Here is my docker file
FROM ubuntu:16.04
RUN dpkg-divert --local --rename --add /sbin/initctl
RUN ln -sf /bin/true /sbin/initctl
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update
RUN apt-get -y upgrade
# in... | Finally, I've changed my project in Visual Studio 2019 to a CMake project.
I've created a CMake file in the shared volume of my container.
SET(CMAKE_C_COMPILER /opt/gcc-linaro-5.3-2016.02-x86_64_arm-linux-gnueabihf/bin/arm-linux-gnueabihf-gcc)
SET(CMAKE_CXX_COMPILER /opt/gcc-linaro-5.3-2016.02-x86_64_arm-linux-gnue... |
64,173,595 | 64,173,801 | Difference between delete() function and delete operator in c++? | I know delete operator used to deallocate the memory allocated by new keyword. delete() function also do the same job in below code .what is difference between delete() function and delete operator in below code?
int* ptr = new int(5);
int* ptr1 = new int(5);
delete ptr;
delete (ptr1);
|
delete() function also do the same job in below code
delete (ptr1);
That is not a "delete function". That is a delete expression where the "operand" is a parenthesised expression.
what is difference [between delete ptr; and delete (ptr1);]
The difference is the same as in the following expressions:
1 + 2
1 + (2)... |
64,173,915 | 64,174,470 | Structured binding reference with tuple of reference | The Structured binding Case2 in cppreference is a bit hard to understand. Basically, I want a clarification of these situations
int x = 1;
double y = 2.0;
auto [a, b] = std::forward_as_tuple(x, y); //a, b are both reference, why?
auto&& [c, d] = std::forward_as_tuple(x, y); //What's the difference of this and above?
... | std::forward_as_tuple(x, y) gives you a tuple<int&, double&>. The types of the bindings into that are int& and double& (in the same way that the types of the bindings into tuple<int, double> are int and double). Basically:
auto [a, b] = std::forward_as_tuple(x, y);
auto&& [c, d] = std::forward_as_tuple(x, y);
behaves ... |
64,173,989 | 64,174,619 | clang error "explicit instantiation does not refer to a function template" across multiple namespaces | I'm trying to reuse existing templated functions from a namespace in my own namespace and explicitly instantiate them for code coverage reasons.
The following code compiles with gcc 9.3 but does not compile with clang 10.0.0
namespace bar {
template<typename T>
T func(T arg){ return arg;};
}
namespace foo {
... | You can't do that, I'm afraid. Clang is correct.
[temp.explicit]
2 The syntax for explicit instantiation is:
explicit-instantiation:
externopt template declaration
4 If the explicit instantiation is for a class or member class,
the elaborated-type-specifier in the declaration shall include a
simple-template-id; ... |
64,174,082 | 64,174,585 | What's the behaviour of "" + number and why it compile? | The code successfully compiles it but I can't understand why, for certain values of number, the program crashes and for other values it doesn't. Could someone explain the behavior of adding a long int with a char* that the compiler uses?
#include <iostream>
int main()
{
long int number=255;
std::cout<< "Value ... | In C++, "" is a const char[1] array, which decays into a const char* pointer to the first element of the array (in this case, the string literal's '\0' nul terminator).
Adding an integer to a pointer performs pointer arithmetic, which will advance the memory address in the pointer by the specified number of elements of... |
64,174,143 | 64,186,358 | Locking mouse cursor in X11 | I'm trying to move and lock a mouse cursor in place, to calculate it's delta position after it was moved by the user. I'm using X11 and the XWarpPointer() function. I found a similar problem in another thread and I followed it, but it didn't work. I even looked into SDL source code but still nothing. The main problem i... | I tried to compile the code on a pc with a Linux system, and it worked. Before I
was compiling it in a virtual machine, so I'm guessing that the base system has priority when it comes to the mouse.
|
64,174,238 | 64,174,274 | How can I capture a function result in a lambda? | I was wondering if I can capture a function result:
int main()
{
struct A { int a; int func() { return a; } };
A a;
auto lambda = []() {};
// I WANT THE LAMBDA TO HAVE A COPY OF a.func();
// In other words I want capture the return value of a.func()
}
Is there a way to do this? I know ... | The syntax is slightly different. The type of the entity in the capture group is deduced from the initializer, and you can't explicitly specify the type:
auto lambda = [copy = a.func()] () { std::cout << copy; };
// ^ no int
You can create multiple entities of different types in the capture group as well, i... |
64,174,298 | 64,174,540 | How to change the working directory in visual studio for c++ | Usually, I place all the assets I need in the project folder, and whenever I run it using the Visual Studio debugger, it runs fine. But when I run the .exe file using the command line, or by just clicking on it, it has problems loading the files. The only way it can load the files is if copy all the resource files in t... | If I understand correctly you would like to move application dependencies into the Debug or Release folder.
You can do it using project property page (right click on the project and select properties). From list on the left side, select build events. There are three options, you can use Post-Build.
Have a look here : V... |
64,174,792 | 64,175,202 | error C2338: YOU_MIXED_DIFFERENT_NUMERIC_TYPES | I'm receiving this error at line eigen/src/Core/AssignEvaluator.h(834) of Eigen library:
error C2338: YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY
Based on the compiler logs I think the errors is triggered by this line in the code:
class IndexedMesh... | Type mismatch between Vec3d and Vec3f was the error cause.
// Caller of the method:
Vec3d IndexedMesh::normal_by_face_id(int face_id) const {
return m_tm->normal_by_face_id(face_id);
}
// Bad method:
Vec3f TriangleMesh::normal_by_face_id(int face_id) const
{
return Vec3f();
}
// Fine method:
Vec3d TriangleMes... |
64,174,859 | 64,174,951 | How does the pointer containing an address returned by address of operator assigned to a pointer variable? | I understand the fact that we can't assign the address literal to a pointer variable directly, thus the address of operator(&) doesn't return an address of variable/operand as literal.
int* ptr{ 0x7ffd78ad698c }; // Compiler error
Instead, it returns a pointer containing the address of the variable/operand, and then... | You seem to be confused about pointers.
First, the only reason you can't do
int* ptr{ 0x7ffd78ad698c }; // Compiler error
is because the compiler thinks it's silly and a mistake. If you add a cast, the compiler will absolutely let you do this.
int* ptr{ (int*)0x7ffd78ad698c }; // Compiles
(I'll also point out that mo... |
64,175,121 | 64,187,676 | Can I initialize static const class member? | I want to run this code:
struct A {
static const string d[] = {"1", "2"};
};
And get an error:
error: in-class initialization of static data member ‘const string A::d []’ of incomplete type
static const string d[] = {"1", "2"};
^
error: non-constant in-class initialization invalid... | The standard explicitly states that non-inline static data members of a class are declaration only, and must be followed up by definition at namespace scope: class.static.data#3
3:
The declaration of a non-inline static data member in its class definition is not a definition and may be of an incomplete type other than... |
64,175,475 | 64,246,640 | How to tell that class/struct is copyable using python bindings for clang tooling | Our project is using clang python api to generate python bindings for C++ classes.
Right now we have a limitation that the copy will only be exposed if a type has an explicitly defined copy constructor.
I would like to change it to also declare a copy for a generated copy constructor - so I need to detect that somehow.... | This is what we ended up with.
a) Seems like from clang ast directly you can only ask if 'is_pod'
cindex.py
Not quite what I need since pod also implies no default constructor accroding to this std::is_pod std::is_trivial.
b) What we did is:
include the original file in a different tmp file that we generate and
parse ... |
64,176,399 | 64,176,618 | How to return base64 decoded image bytes through a methods formal parameter of type char** | Being new to C++, I am still struggling with pointers-to-pointers and I am not sure if my method below is returning decoded image bytes properly.
This method gets a base64 encoded image string from API. The method has to follow this signature as it is part of legacy code that is not allowed to abbreviate from the way ... | Give the requirements there isn't any way to avoid allocating more memory and copying the bytes. You cannot use the vector directly because that is local to the GetInfoAndPicture function and will be destroyed when that function exits.
If I understand the API correctly then this is what you need to do
//*image = new ch... |
64,176,545 | 64,177,353 | Is there a standard memory_resource allocator adapter/wrapper? | I'm surprised not to see the standard or anyone else(?) providing an adapter/wrapper to make standard allocators look like a std::memory_resource. Am I missing something? Is it just something along the lines of
template <typename ByteAllocator>
class AllocatorMemoryResource : public std::memory_resource {
ByteAlloc... | For now, I believe it is still experimental: https://en.cppreference.com/w/cpp/experimental/resource_adaptor.
Your implementation seems to be correct, in the simplest sense. You could make it more advanced by doing a dynamic cast, and returning the result of
this->m_allocator == cast_other->m_allocator
|
64,176,768 | 64,176,835 | Incorrect value of enum variable | I just began a little fun project which is good ol' snake in CLI. What I'm currently figuring out is changing directions of a single dot inside a box (no snake yet!). I created an enum type with values up, down etc. and created a simple loop to update the position. What's curious is that no matter what value I assign t... | Change:
if (dir = STOP)
to:
if (dir == STOP)
since you want to compare those two, not assign UP to dir. Same change is required for your other conditions in the else-if statements.
Tip: Enable compiler warnings in order to get informed about those pesky logical errors. For example in GCC, you could use the useful all... |
64,177,223 | 64,177,271 | A C++ abstraction for sorted containers that differ only in sort function? | In C++, I have a class that contains two members which are sorted containers. The containers store the same object type, but one is sorted in ascending order and the other in descending order. Note: the object type in each container is the same, but the actual object instances stored in the two containers are differe... | You can write a couple private helper functions and tags like
struct fwd_tag_t{};
struct rev_tag_t{};
auto& getSet(fwd_tag_t) const { return fwd_set_; }
auto& getSet(rev_tag_t) const { return rev_set_; }
and then use tag dispatch to call the one to get the correct set like
template <bool IS_FWD> inline void printSet()... |
64,177,492 | 64,177,855 | Getch() behavior when terminal is resized? (ncurses) | getch returns 410 when I resize terminal. Why does the getch interpret the resize as input? What's the 410? Is it a special symbol?
Code:
#include <curses.h>
int main() {
initscr(); cbreak(); noecho();
int x = getch();
printw("%d", x);
getch();
endwin();
return 0;
}
But when I use timeout I g... | /* curses.h */
#define KEY_RESIZE 0632 /* Terminal resize event */
410 = 0632 (octal).
As for your second question, that doesn't happen when I test on my machine. Are you perhaps running an old version of ncurses? There have been bugs around this. https://lists.gnu.org/archive/html/bug-ncurses/2002-01/msg00003... |
64,177,660 | 64,178,147 | glEnableVertexArrayAttrib throw invalide size | Got 2 computers with both having modern graphic card. Both handle OpenGL 4.6. I got this code :
GLuint VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
//Setting up the VAO Attribute format
glVertexArrayAttribFormat(VAO, 0, 3 * sizeof(float), GL_FLOAT, GL_FALSE, 0);
glEnableVertexArrayAttrib(VAO, 0);
For some... | Your size is indeed incorrect, it is not in bytes. The size denotes number of elements per vertex, e.g. vec3 corresponds to 3:
glVertexArrayAttribFormat(VAO, 0, 3 , GL_FLOAT, GL_FALSE, 0);
As why it works on one PC, well, get used to it. OpenGL implementations in GPU drivers are usually quite magical and forgiving unti... |
64,177,972 | 64,178,182 | Can I tell my compiler to ignore the side effects of a statement or a function? | Suppose my code has the following function:
inline int foo() {
bar();
int y = baz();
return y;
}
and suppose that bar() and baz() have side-effects.
If I write:
int z = foo();
printf("z is %d\n", z);
then obviously both bar() and baz() have to be executed. But if I write:
foo();
and not use the return va... | As an extension to standard C and C++, gcc and clang support the pure function attribute which informs the compiler that the function has no side effects and unneeded calls can be deleted. If you declare a function with this attribute, the compiler will believe you, even if you are lying.
#include <iostream>
static i... |
64,178,143 | 64,178,264 | Regular loop to Pointer loop conversion, how? | SomeClass* stuff;
int N = 10;
stuff = new SomeClass[N];
Someclass* objectPtrDelete = null;
int i = 0;
for(Someclass* pointer = begin(); pointer != end(); pointer++)
{
if(pointer->getSomeAttr() == randomPointer.getSomeAttr()){
objectPtrDelete = pointer;
break;
}
i++;
}
// Shrinking the... | (edited to take into account your changes)
if I well understand what you want, having
SomeClass* stuff;
you can replace
for (int j = i; j < N-1; j++)
stuff[j] = stuff[j + 1];
by
for (SomeClass * p = stuff + i; p < stuff + N-1; p++)
*p = *(p + 1);
or to easily manages changes concerning the type :
for (aut... |
64,178,395 | 64,178,573 | Cannot access a std::vector* in an async lambda | I need to generate a bunch of random numbers and use(just read) them from different threads. Here's how I generate the numbers:
const std::vector<double>* Test::getRandomDoubles(int count)
{
std::vector<double>* numbers = new std::vector<double>();
numbers->reserve(count);
for (int i = 0; i < itemsCount; i... | It is your responsibility to make sure that the lambda doesn't outlive variables it captures by reference.
If you return a lambda from a function, then by the time you call it, local variables it has captured are long dead. The same thing occurs if you run it asynchronously and return a future.
One way to overcome thi... |
64,178,554 | 64,178,590 | So...is there a way to stop files from clearing automatically? (c++) | So i'm making an extremely simple guessing console game and i want to store data permanently in a file (highscore). However everytime i compile the file i'm using empties itself. Is there anyway to stop that?
I've tried a lot of thing which didn't work and i honestly don't know where the problem is. I'm guessing it has... | Don't open your file twice in parallel with two streams. Also, a simple open-for-writing will not truncate your file, but will place you at the start of the file, so you'll be overwriting existing data; see this question. You have to open files with the write mode.
You need to either:
Open your file for both input and... |
64,178,729 | 64,178,815 | Friend function with default argument inside struct in C++ | I have a struct that looks like this:
struct Lip {
int x;
friend Lip mkLip(Tester t, bool full = false);
bool operator == (Lip p) const { return x == p.x; }
bool operator != (Lip p) const { return x != p.x; }
bool operator < (Lip p) const { return x < p.x; }
};
The problem with this is that... | All your members are public, so you don't need a friend at all.
Just have a nice, normal function declaration:
struct Lip
{
int x;
bool operator==(Lip p) const { return x == p.x; }
bool operator!=(Lip p) const { return x != p.x; }
bool operator<(Lip p) const { return x < p.x; }
};
Lip mkLip(Tester t, ... |
64,178,918 | 64,179,110 | Print a string from a pointer to its member class | So I'm trying to print a string, but I get no output. However the other values in the class prints just fine.
In main I have a for loop that prints the the values for the Skill class. In Skill I have a pointer to the Ability class.
class Skill {
private:
Ability* ability;
public:
Ability* GetAbility() {
... | Your AbilityScores::GetAbility() method is returning an Ability object by value, which means it returns a copy of the source Ability, and so your Skill objects will end up holding dangling pointers to temporary Ability objects that have been destroyed immediately after the Skill constructor exits. So your code has und... |
64,178,997 | 64,179,101 | Stateless lambdas as static local variable | I am trying to write a templated wrapper class around a stateless lambda. Something like this:
template <class TFuncOp>
class Adapter
{
public:
void Op()
{
TFuncOp func; // not possible before C++20
func();
}
};
Since this isn't possible before default constructible lambdas arrive with C++2... | In any case, accessing a nullptr is never a good idea as it is UB.
But we can see that typical implementations generate code which simply works. I try to explain why:
First, it has nothing to do with lambdas. It is simply the not needed using of a copy constructor on a class which has no data. As you have no data, the ... |
64,179,008 | 64,181,551 | Moving triangles to a new column with triangle strip | I'm having problems moving triangles to another column. I'm able to successfully add them to right direction (in the picture), but when I want to move them into a new column it takes points from old points (furthest on the right) and I would like to have them connected to the upper triangles as I elevate the mesh, the ... | On possibility is to use Primitive Restart inidces.
Another simple trick is to add the last vertex and the first vertex of a strip twice:
A C E G
+---- +-----+-----+
| / | / | / |
| / | / | / |
B +-----+-----+-----+
| / | D F H
| / |
+-----+
I J
Triangle strip:
... |
64,179,087 | 64,179,128 | How do you pass in structs in multiple threads using C++? | Recently, I have been creating a program that creates multiple threads using structs. In my subroutine, I've noticed that my values in my struct are never passed (they're random things). I've been told to instantiate a new struct with every thread created, but this doesn't work for me (probably because of syntax).
I'm ... | You will have to create instances of Node for each threads.
It can be done like this:
node = new Node; // create an instance of Node
node -> upper_bound = interval;
node -> lower_bound = min;
for( int i = 0; i < num_threads; i++ ) {
ids[i] = i;
cout << "Making a thread with these boundaries: " ... |
64,179,119 | 64,181,948 | How can I get smoother rotation when space is pressed | I am making a game where a nozzle of a tank rotates around when space is pressed to shoot enemies. However, right in the beginning when the space is pressed, it seems to stop for a few milliseconds and then continues without any problems. How can I make it so that the rotations is smooth and consistent as soon as the s... |
if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym == SDLK_SPACE)
nozzle.plusAngle(0.1f);
}
This is not how you do controls in a game.
If you open a text editor and hold a key, you'll see one letter being typed, then, after a delay, a steady stream of the same repeated letter. And SDL does the sa... |
64,179,145 | 64,179,681 | Static library (/MT) linking conflicts with project /MTd option | My project links a lot of static libraries. All of them previously links well, but now I added mysql c api library and now I gets errors like that:
mysqlclient.lib(client_authentication.obj) : error LNK2038: mismatch detected for "_ITERATOR_DEBUG_LEVEL": value "0" doesn't match value "2" in mysql_database_connection.o... | The error indicates a conflict between the CRT libraries used in your project (/MTd multithread static debug) and the ones used by the statically linked library (/MT multithread static release). This is an error condition because one module (EXE or DLL) can only have/use one copy of the CRT.
From the /MD, /MT, /LD (Use... |
64,179,379 | 64,179,440 | How to output the lowest and highest values from a data file using dynamic arrays? | I'm having trouble outputting the lowest and highest values of the integers contained in a txt file.
My directions are to set up a dynamic array to hold the exact number of values in the array and read the values from the file into the array.
After the values are in the array, sort them using a bubble sort. And then to... | Few issues with the code.
Not going to beginning of the file stream, passing values to array with nElements instead of i, accessing arr[n] instead of n-1.
#include <iostream>
#include <fstream>
using namespace std;
void bubbleSort(int[], int);
void printArray(int[], int);
int main()
{
// open the file
ifstrea... |
64,179,651 | 64,179,690 | How do I create a destroyable threadsafe singleton C++? | class Singleton
{
static std::shared_ptr<Singleton> GetInstance()
{
static std::shared_ptr<Singleton> instance = make_shared<Singleton>();
retrun instance;
}
static void DestroyInstance()
{
// What goes in here?
}
}
The reason I pass around a sharedPtr is because I don't want other... | Your other function would have to get access to a reference to the static object somehow.
What I would do is to hide the instance function privately and return a reference. The public function would return the copy of the shared pointer as usual.
struct Singleton {
static auto GetInstance() -> std::shared_ptr<Singl... |
64,179,718 | 64,185,969 | Storing or accessing objects in boost r-tree | I am using Boost's r-tree implementation in my code. I have a list of objects with coordinates (say cities on a map, if it matters), which I wish to index in the r-tree, to perform fast NN search, etc. I have followed their iterative query example, in which trees are storing boost::geometry::model::point objects.
My qu... | You can store any type in a rtree, you just have to tell Boost how to get the coordinates out.
So the first step is to make a type with both a index and point:
struct CityRef {
size_t index;
point location;
};
You can specialize boost::geometry::index::indexable to give Boost a way to find the point you've put... |
64,179,954 | 64,181,465 | template friend bool overload clash in namespace | I have 2 different class templates in the same namespace, xy and rgba. Both of them overload operators == and !=. When I compile, I get the error that the overload has already been defined. Is it because both those classes are in the same namespace? If so, is there a trick to avoid the clash? I tried different labels f... | There are many good points in the comment, so I will only provide a solution to your compilation problem.
You need some type_traits and if constexpr. If you don't have c++17 you can do it with SFINAE.
#include <iostream>
#include <type_traits>
template <class T, class U = void>
struct has_xy : std::false_type{};
templ... |
64,180,170 | 64,180,217 | Assigning rvalue to rvalue | Can I ask why the code below can be compiled without any error?
struct Test {
int num;
};
int main() {
(Test){.num = 10} = (Test){.num = 20};
return 0;
}
(Test){.num = 10} and (Test){.num = 20} are rvalue, this is impossible that a rvalue can be assigned to another rvalue. How cpp considers the statement ... | This is just how the the special member functions are specified in c++ by default. e.g. Test has a synthesized special member function:
Test& operator=(Test const &) = default; // if you write it out
which can be called on both lvalues and rvalues.
If you want to disallow assignments to rvalues, you have to customize ... |
64,181,338 | 64,193,127 | Switching a bulb ON and OFF using toggle switch in Arduino | Kindly help me in the Arduino code as I am new in this field. I have Arduino code that turns the light in bulb ON and OFF using toggle switch. It is successfully running and giving output.
The following is the code:
int buttonPinBulb = 11;
int relay1 = 10;
void setup() {
pinMode(buttonPinBulb, INPUT_PULLUP);
pinMo... | You can use a global variable to store the current status of the button.
You may also want to debounce your button (using millis() in the below example, unless the debouncing is already done in hardware) - especially when you want to update a database each time the status changes.
int buttonPinBulb = 11;
int relay1 = 1... |
64,181,457 | 64,181,487 | Use std::bind and store into a std:: function | I am trying to use std::bind to bind to a function and store it into my std::function callback object. The code I wrote is the simplified version of my actual code. The below code does not compile, says
_1 was not declared in the scope
Note: I know the same can be done using a lambda. However the function handler is ... | The placeholders _1, _2, _3... are placed in namespace std::placeholders, you should qualify it like
Callback c = std::bind(handler, std::placeholders::_1);
Or
using namespace std::placeholders;
Callback c = std::bind(handler, _1);
|
64,181,694 | 64,183,349 | Dereference Pointer to Struct Variable | I try to understand what value we get when dereference the pointer to struct.
My struct is.
struct car
{
int a = 5;
int b = 10;
int c = 2;
int d = 14;
int e = 20;
};
My code in main function is
int main()
{
car k1,k2,k3,k4,k5; // declare struct variable
car* ptr1,*ptr2,*ptr3,*ptr4,*ptr... | Variadic functions do not have type checking and practically may pun types. Essentially you passed content of structure as raw values and format string described how to treat them. Luckily, in this case struct has no padding, so first five integers were read accordingly.
The behaviour in this case is unspecified and d... |
64,181,934 | 64,184,931 | C++ Errors involving outputting chrono duration | Here's the class I'm working with (Some parts cut out)
const int records = 7;
class Timed {
public:
friend std::ostream& operator<<(std::ostream& os, Timed right) {
for (int i = 0; i < records; i++) {
os << right.eR[i].vName << " " << right.eR[i].duration << " " << right.eR... | In C++11/14/17, there is no streaming operator for chrono::duration types. You have two choices:
Extract the .count():
|
os << right.eR[i].duration.count() << "s ";
Use this open-source, header-only date/time library:
|
#include "date/date.h"
// ...
using date::operator<<;
os << right.eR[i].duration << " ";
The... |
64,182,382 | 64,182,650 | Why is NOT std::string defined in program equal to std::string loaded from file when printing out using prinft() and string::c_str()? | When i create std::string and define it in program like this and print it to console it looks like this:
std::string shader = "#version 330\nlayout(location = 0) in vec3 vp;void main(){gl_Position = vec4(vp, 1.0);}";
printf("Original: %s\n", shader.c_str());
Output:
But when i load std::string from file the way below... | Solution was to read text file by each character and then printing the string is correct.
std::string shader;
std::ifstream inputStream(path, std::ifstream::in);
char character;
if (inputStream.is_open())
{
while (inputStream.get(character))
{
shader += character;
}
}
Output when printing shader:
... |
64,182,421 | 64,184,183 | Linking C++ object files embedded with Python | I have a C++ constructor file (formatting_SQ.cpp) of a header file formatting_SQ.h which I want to link to other constructor files of header files (neat.cpp nnode.cpp link.cpp etc...-> neat.h nnode.h link.h) in order to have formatting_SQ.o.
Then, I want to link my main.cpp file with this formatting_SQ.o file. The prob... | So after some long hours of research I can conclude that the compilation method is correct but BE EXTREMELY CAREFULL with where you declare your import modules from python, because this was the problem for me
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <Python.h>
#inclu... |
64,182,639 | 64,182,960 | Memory Leak issue with my code, I am newbie | I keep getting a Memory Leak which seems to occur because the new initialized objects passed as pointers to add(…) are not actually delete. But somehow, I cannot make this work properly. I tried adding a for-loop to loop every object in array within class Monsters to delete each object when the call of the destructor i... | Well here's my old school effort. See comments at various points in the code for the things you were missing.
References
What is The Rule of Three?
What is the copy-and-swap idiom?
It is good to know this stuff, although that doesn't mean you should be old school. Modern C++ is better.
#include <iostream>
#include <alg... |
64,182,961 | 64,188,967 | c++ : can process automatically reclaim excess allocated memory on stl objects? | context: (from this question reduce the capacity of an stl vector)
Is there a way to reduce the capacity of a vector ?
My code inserts values into a vector (not knowing their number
beforehand), and when this finishes, the vectors are used only for
read operations. ...
this answer: https://stackoverflow.com/a/1111311... | Lets consider what would be needed to implement something like that.
Some way to tell the process to release memory (rule them all)
Some signal and handler or event.
Some way to know which objects are to release memory (find them all, bring them all)
each register somewhere so they can be called by the signal or e... |
64,183,746 | 64,187,020 | array problem of finding number of edits needed | Given an array arr containing positive elements and an integer K. In one operation you can pick an element of the array (suppose arr[i]) & break to p1,p2 insert p1 & p2. You need to find the minimum possible value.
This is my approach:
#include <bits/stdc++.h>
using namespace std;
int main(){
int n,k; cin >> n >> k;
v... | As already stated in a comment, your algorithm cannot always provide the correct answer. This is a proposal of another algorithm.
Checking that a given max (= target) can be obtained in K operations is rather easy: for each element x=A[i], calculate the number of operations C(x) which are necessary for this particular ... |
64,184,400 | 64,192,629 | Including a specific function in the header file causes and error when trying to include that header file | This is my threeD.h:
#pragma once
#include "SDL.h"
#include <vector>
struct vec3
{
float x, y, z;
};
struct vec2
{
float x, y;
};
struct triangle3D
{
vec3 v[3];
};
class Triangle2D
{
Triangle2D(vec2 v1, vec2 v2, vec2 v3)
{
this->v[0] = v1;
this->v[1] = v2;
this->v[2] = v... | https://en.cppreference.com/w/cpp/language/inline
// function included in multiple source files must be inline
inline int sum(int a, int b)
{
return a + b;
}
There may be more than one definition of an inline function or variable (since C++17) in the program as long as each definition appears in a different trans... |
64,184,499 | 64,184,500 | Message "error: use of undeclared identifier 'assert'" | I had a piece of code that was including some Boost headers. Upon compilation I received errors like
/usr/local/include/boost/smart_ptr/shared_ptr.hpp:1041:9: error: use of undeclared identifier 'assert'
BOOST_ASSERT( deleter_.use_count() <= 1 );
^
/usr/local/include/boost/assert.hpp:60:29: note: exp... | As it turned out I had a file called Assert.h in my include-path (a custom file of mine). On case-insensitive file systems as used by Windows and macOS, this would shadow the original assert.h header that actually defines the assert macro.
The solution therefore was simply to rename my assert-header file.
(I found the ... |
64,184,732 | 64,184,806 | CTAD fail to deduce template argument with SFINAE in partial specialization | I tried using CTAD with SFINAE in partial specializations, but it doesn't compile unless I add a seemingly useless deduction guide. What's the reason/limitation behind?
template<typename T, typename Enable = void>
struct A;
template<typename T>
struct A< T, std::enable_if_t<std::is_arithmetic_v<T>>>
{
A(T) { std::... | Implicitly generated deduction guides mirror the constructors of the primary template only, not of the specializations.
It will work if you get rid of one of the specializations, and move code from it into the primary template:
template<typename T, typename Enable = void>
struct A
{
A(T) { std::cout << "Other\n"; }... |
64,185,446 | 64,194,345 | How to get the value passed from an unrelated signal to a slot? | I have a signal/slot arrangement for an asynchronous call to request data. Normally that's fine as received data just updates controls. But in a couple instances I have to wait for the reply to the request to be sure an action is complete before moving to the next step. There is a signal that is fired every time val... | Final solution without re-writing the entire thing.
Subclass QEventLoop, passing the expected address, then add a check on the received queue item address.
If the expected address turns up in the queue then the loop can quit the event loop and return expected value.
If the timer expires then we've waited too long so ra... |
64,185,958 | 64,186,121 | If using QString after being `std::move`d defined? | Consider following pattern, stripped of details for simplicity:
QString str = /* expression */
/* some actions with str */
foo(std::move(str));
str = /* expression */
/* some actions with str */
foo(std::move(str));
Does reuse of str yield defined behaviour in Qt 4.8.6? Qt 5.x?
| A move operation leaves the moved-from object in a "valid but unspecified state":
16.5.5.16 Moved-from state of library types [lib.types.movedfrom]
Objects of types defined in the C ++ standard library may be moved
from. Move operations may be explicitly specified or implicitly
generated. Unless otherwise specified, s... |
64,185,992 | 64,262,561 | The break point in c++/WinRT Component code is not triggered | I am trying to migrate a macOS app to UWP
there are some c++ code need to be reused, I put them in a WinRT/c++ component.
then I add it to the assembly reference of the UWP app and set it to mixed debug type.
I set the breakpoint in the c++/WinRT component code and rebuild the project.
Lately, I open the UWP app and b... | this is the answer from @YanGu - MSFT
If you want to trigger a break point in your C++/WinRT Component, the
component project should be in the same solution as the UWP app. Then
set the debugger type as Mixed(Managed and Native)
|
64,186,005 | 64,188,764 | Why "int const B::bsm1a;" not considered a redefinition? | #include <iostream>
struct B {
public:
static int const bsm1a{ 0xf };
};
int const B::bsm1a; // 1) Why is this NOT considered a redefinition?
// 2) What does this line actually do here?
int main()
{
std::cout << "Hello World!\n";
}
#include <iostream>
struct B {
public:
static int cons... | This is what I gathered reading the C++ standard. If my interpretation is wrong, please correct me.
In the first case the situation is rather interesting. This comes down to the meaning of of declaration and definition in C++. If you dig into the C++ Standard, you'll find a section of this topic:
(§6.2) Each entity de... |
64,186,077 | 64,186,260 | Using function decimal to return only decimal of input as double C++ | I am on week 3 of C++ & I am so lost. I need to write a program with function decimal - that will return the decimal part of any non negative decimal number sent to it as input. Needs to be clear that it needs to return a double - parameters set at double.
we haven't learned about function decimal yet nor type coercion... | You can use string conversions:
#include <algorithm>
#include <iostream>
#include <string>
int main() {
float input = 12.123456;
std::string ip = std::to_string(input);
ip.erase(ip.begin(), --std::find(ip.begin(), ip.end(), '.'));
ip.front() = '0';
std::cout << ip;
return 0;
}
Another way wou... |
64,186,201 | 64,186,257 | Getting address of first passed variadic argument | #include <stdarg.h>
template<typename... Args>
void Func(Args... args)
{
// WANT: Get the address of the first argument
// TRIED:
// va_list vargs = (char*)&(args);
// va_list vargs = (char*)&(args)...;
// va_list vargs = (char*)&(args...);
// GOT:
// 'args': parameter pack must be expanded in this context
}
I'm w... | Simpler would be to split argument in signature:
template <typename T, typename... Ts>
void Func(T arg, Ts... args)
{
// WANT: Get the address of the first argument
T* p = &arg;
}
else
template <typename... Ts>
void Func(Ts... args)
{
// WANT: Get the address of the first argument
auto* p = std::get<0>(std::... |
64,186,308 | 64,223,191 | Best way to broadcast Armadillo matrix operations similar to Numpy | Consider the matrices A and B where A is a 5x5 matrix and B is a 1x5 matrix (or a row vector). If I try to do A + B in Numpy, its broadcasting capabilities will implicitly create a 5x5 matrix where each row has the values of B and then do normal matrix addition between those two matrices. This can be written in Armadil... | Expanding on the note from Claes Rolen. Broadcasting for matrices in Armadillo is done using .each_col() and .each_row(). Broadcasting for cubes is done with .each_slice().
mat A(4, 5, fill::randu);
colvec V(4, fill::randu);
rowvec R(5, fill::randu);
mat X = A.each_col() + V; // or A.each_col() += V for in-place op... |
64,186,621 | 64,187,214 | Why doesn't std::is_invocable work with templated operator() which return type is auto-deduced (eg. generic lambdas) | c++17 introduces template <class Fn, class...ArgTypes> struct is_invocable:
Determines whether Fn can be invoked with the arguments ArgTypes.... Formally, determines whether INVOKE(declval<Fn>(), declval<ArgTypes>()...) is well formed when treated as an unevaluated operand, where INVOKE is the operation defined in Cal... |
I guess the reason may be related to SFINAE.
Indeed. We call things like f1 "SFINAE-unfriendly":
struct {
template<typename T>
auto operator()(T t) { return t.a(); }
} f1;
That's because f1 advertises itself as being invocable with anything (there are no constraints at all) but to find out what the call operator... |
64,186,685 | 64,195,521 | Arduino MKR Wifi 1010 Serial Communication with Arduino Mega | I am writing a serial communication program between a mkr wifi 1010 and a mega in which the mkr sends either a H or L char to the mega, and the mega responds by reading the char and setting it's onboard LED to either high or low depending on the char. When I use delay(#) on the mkr the code works just fine and the meg... | In the delay-less sender code:
int byteToSend
should be
char byteToSend
and in the receiver code:
int incomingByte
should be
char incomingByte
This fixes the issue.
|
64,186,815 | 64,192,979 | Random exit code on giving larger array sizes in DPC++ Vector Addition | I am trying to run a hello-world DPC++ sample of oneAPI which adds two 1-D Arrays on both CPU and GPU, and verifies the results. Code is shown below:
/*
DataParallel Addition of two Vectors
*/
#include <CL/sycl.hpp>
#include <array>
#include <iostream>
using namespace sycl;
constexpr size_t array_size = 100000;
typed... | Turns out, this is due to Stack size reinforcement by VS. Contiguous array with too many elements resulted in a stack overflow.
As mentioned by @user4581301, the error code -107374171 in hex, gives C00000FD, which is a signed representation of 'stack exhaustion/overflow' in Visual Studio.
Ways to fix this:
Increase th... |
64,186,848 | 64,189,789 | is it possible to encourage threads to line up without forcing it? | I have a single atomic variable that multiple threads are loading, they perform some local calculations on it, then call an atomically fetch_and on it. They check that they were able to make there change before another thread did, if not, repeat using the updated value returned from fetch_and
Works a lot faster than a ... | There's no point. If two threads don't try to do this at the same time, they'll make perfect progress. If two threads do try to do this at the same time, one of them will have to wait in some way. What way that other thread waits has no effect on performance.
If each thread needs about the same amount of time between a... |
64,186,919 | 64,187,250 | why can't I construct an std::span from iterators? | Consider a large memory container. In this simple example an std::vector<int>:
std::vector v = { 0, 1, 2, 3, 4, 5 };
std::span allows me create a lightweight view over the memory. Now I want to simply print the span:
template<typename T>
void print(std::span<T> span) {
std::cout << '[';
if (span.size())
... | You can construct a span using iterators, it has such a constructor (as added by P1394, which you can see in [views.span]):
template< class It, class End >
explicit(extent != std::dynamic_extent)
constexpr span( It first, End last );
It's just that MSVC's standard library doesn't implement it. The program compiles fin... |
64,187,584 | 64,188,535 | Connecting each column with each other with GL_TRIANGLE_STRIP | I've created these triangles using triangle strip. I was wondering if there's a better way to connect the triangles to each other (first picture). For now I just created the triangles based on the previous columns verticies (second picture). So is there a better way so I dont have to calculate all the previous vertices... | AFAIK the only way to avoid recalculating/storing some previous vertices is to use an index buffer
https://www.learnopengles.com/tag/triangle-strips/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.