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,387,242 | 64,387,444 | how to get list of all files in a directory and sub directories(full file path) | how to get list of all files in a directory and sub directories(full file path), And also show it if the file name is in Russian and Arabic
I did a lot of searching on Google but did not find anything that would solve my problem, any help is appreciated
| It is better to include what you have tried so far to solve your problem. That way we can help you debug your own code which can be very good for you.
However, C++17 made iterating over directories very easy through the directory iterator. Read more about the directory iterator here and see the code below:
#include <st... |
64,387,248 | 64,402,640 | [Boost::ext].SML: Is there a way to store a callback to later process an event? | I came from Boost MSM and I'm now trying to implement the same state machines with SML 1.1.3.
With SML I don't have access to the state machine itself and I'm forced to work with injected dependencies. I'm also heavily using D-Bus and now I have problems making asynchronous D-Bus calls. The async D-Bus call is made in ... | In order to get access to state machine itself, you need to separate your application class to base class and sub class.
The base class has pure virtual member function declaration.
You can call the member functions from sml transition table action.
You need define the sub class after transition table definition.
Now, ... |
64,387,304 | 64,388,532 | ReadProcessMemory always reads 0 | I'm creating a cheat for educational purpose (on windows for now) on a small game. My error is so far is that ReadProcessMemory always reads 0.
LPCVOID addr = (LPCVOID *) 0x1228A93C; // TO-DO: c++ casts
int dest = 0;
SIZE_T read = 0;
bool error = ReadProcessMemory(process, addr, &dest, sizeof(int), &read);
if (!error)... | This is probably what you want:
LPCVOID addr = (LPCVOID *) 0x1228A93C; // TO-DO: c++ casts
int dest = 0;
SIZE_T read = 0;
if (ReadProcessMemory(process, addr, &dest, sizeof(int), &read))
{
printf("I read %llu w/ %u at %p\r\n", read, dest, addr);
} else {
auto lasterror = ::GetLastError(); // firs... |
64,387,448 | 64,388,132 | Some functions/methods not exported into static library - Visual Studio 2019 C++ | Apologies if this is an ill formed question. But it is something I don't even know where to start debugging.
I have a library, in which I keep general purpose code. i build this as a static library to include in my projects. The library and the projects are written in C++ and built in Visual Studio 2019.
I have just ma... | As mentioned in my comment, constexpr is implying inline which causes compiler to not emit the symbol at all.
A constexpr specifier used in a function or static member variable (since C++17) declaration implies inline.
Your edit is also empirical proof that that's the case. I would say it is working as expected. The ... |
64,388,243 | 64,388,383 | Save value of object in vector and pointer in map. Is this correct? | I have a question of the validity of pointers of objects in std::vectors. I am not sure if the memory in the following example is saved correctly and if I am accessing the pointers in the way I intend to do:
// class which should hold the 4 Indices
struct Face
{
Face(){};
Face(std::array<int, 4> indices) : Indi... | That depends on how do you use your CreateAndStoreFace function. If the lifetime of faces is longer than indexToFaces, and the faces vector does not invalidate its references (e.g. after another push_back), then the pointer in your map always points to the correct block of memory.
std::vector<Face> faces;
std::map<int,... |
64,388,270 | 64,388,994 | Why ifndef is not allowed inside a macro? | I am trying to write something like this:
#define set(x){cout<< x}
int main() {
set(#ifdef A 1 #else 3 #endif );
return 0;
}
But it does not work, my question is why?
Why doesn't C allow the code to work? what the problem with ifndef inside a macro?
| Who said no?
set(
#ifdef A
1
#else
3
#endif
);
The above snippet works as expected. Demo on Godbolt
# is a special character that starts a preprocessor directive and must be at the start of the line (after optional whitespaces) so you must separate into new lines. Anyway that's not what pe... |
64,388,440 | 64,388,560 | When function templates are instantiated in a class template? | At which moment the function templates within the following class template are instantiated?
// a.h
#pragma once
template <typename T>
class A {
public:
template <typename T2> void func1(T2 t);
void func2(T t);
T func3();
void func4();
// SECONDARY ISSUE
// Is there any difference in writi... | Methods of class templates are only instantiated when called. For illustration consider:
#include <type_traits>
template <typename T>
struct foo {
void only_for_int() {
static_assert(std::is_same<T,int>::value);
}
};
int main(){
foo<int> f;
f.only_for_int(); // OK (T == int)
foo<double>... |
64,388,682 | 64,388,819 | Inline functions across multiple C++ translation units | I recently learnt about inline functions in C++. I understand how they work (in terms of expanding the code instead of making jumps etc), however I'm a little confused regarding how I should use them when it comes to multiple translation units / *.cpp files.
I've read that, as a rule of thumb, I should contain the defi... | The inline keyword in front of a function was only an optional indicator for the compiler that inline is preferred. Modern compilers don't care about the inline keyword when it comes to code inlining.
The important meaning about inline is "multiple definitions are permitted", member functions definitions implicitly inl... |
64,388,802 | 64,389,219 | Problems returning a const reference (no a reference to a const) | I want to return a const reference so I cannot change the object itself but I can call their non-const methods. But I don't know how to do it.
With pointers is easy, I can choose between a const pointer (const myclass*) or a pointer to const values (myclass const*). But with references it seems not working the same way... | You can't have "partial mutability" in that way, not without removing assignment completely from A.
(Despite your claim that this is easy with pointers, that situation is exactly the same - you need to either disallow b.get()->set(100) or allow *b.get() = a.)
One thing you can do is add a level of indirection by way of... |
64,389,877 | 64,390,531 | Why std::unique_ptr isn't optimized while std::variant can? | I tried to compare the overhead of std::visit(std::variant polymorphism) and virtual function(std::unique_ptr polymorphism).(please note my question is not about overhead or performance, but optimization.)
Here is my code.
https://quick-bench.com/q/pJWzmPlLdpjS5BvrtMb5hUWaPf0
#include <memory>
#include <variant>
struc... | I've compiled your code with Clang++ to LLVM (without your benchmarking) with -Ofast. Here's what you get for VariantPolyMorphism, unsurprisingly:
define void @_Z19VariantPolyMorphismv() local_unnamed_addr #2 {
ret void
}
On the other hand, PointerPolyMorphism does really execute the loop and all calls:
define void ... |
64,390,135 | 64,390,209 | Why isn't my class method's if statements not modifying the private variables time variables | this is basically a time program that supposed to output well... the time (from an input). It supposed to have overflow checkers that basically check whether or not minutes/seconds are above 60 and then add 1 to either int minutes or int hours. Currently, it's not wanting to do that and outputs 'Time : 1:3:13' which is... |
Division between integers are truncated, so you don't need floor.
=+ is combination of = and +. To assign result of addition, += should be used.
Assignment will eliminate what is previously assigned, so addition should be done after assignments.
Try this:
void add(int hours, int minutes, int seconds) {
... |
64,390,263 | 64,390,331 | Why does code work in codeblocks 16.01 but doesn't i the newest version of Clion | #include<iostream>
#include<iomanip>
using namespace std;
int main(){
int r,k;
cout << "Unesite broj redova:";
cin >> r;
cout << endl << "Unesite broj kolona:";
cin >> k;
int A[r][k];
for(int i = 0; i < r; i++){
for (int j = 0; j < k; j++){
cout << "A[" << i << "][" << j <<"] = ";
... | This construct
int A[r][k];
is called variable length array (VLA) and is not part of C++. Some compilers provides it as an extension, others don't.
You should use either new or std::vector or any other constructs, instead of VLAs.
For example, with vectors, A becomes:
std::vector<std::vector<int>> A(r, vector<int>(k, ... |
64,390,537 | 64,391,213 | How to redefine an existing Q_PROPERTY as REQUIRED? | Goal
I have a QQuickItem derived C++ class, Foo, and I would like to ensure, that whoever uses it in QML, gives a value to the objectName property. In Foo I am redefining the property like this:
Q_PROPERTY(QString objectName READ objectName WRITE setObjectName NOTIFY objectNameChanged REQUIRED)
Since objectNameChanged... | What you could do is to expose a qml file Foo.qml which contains
CppFoo {
required objectName
}
instead of exposing the C++ class directly to your users. Doing that for instance with a simple Item, and using it in another file would then lead to an error like
file:///tmp/tmp.aOQi2yetXl/Foo.qml:3 Required property ... |
64,391,285 | 64,391,725 | How to solve the problem with "impossible constraint in asm" while building libmfx for ARM? | I have a problem. I'm trying to compile libmfx for ARM v7-a processor from source code. But when I launch "make" I have an error:
The source code in src/mfx_critical_section_linux.cpp:
mfxU32 mfxInterlockedCas32(mfxCriticalSection *pCSection, mfxU32 value_to_exchange, mfxU32 value_to_compare)
{
mfxU32 previous_val... | lock; cmpxchgl is x86 assembly code. No surprise really, as libmfx is an Intel library (as in, libmfx was written by the company that makes x86 chips). It really isn't designed to compile on ARM.
|
64,391,313 | 64,391,678 | How can I bind a member function of an instance whose address may change? | #include <iostream>
#include <string>
#include <functional>
#include <vector>
class B;
class A {
public:
std::function<void(B*, const std::string&)> m_callback;
void* m_dest = nullptr; // Will be used in later versions of this code.
void trigger(const std::string& message) {
m_callback(m_dest, mes... |
How can I bind a member function of an instance whose address may change?
Strictly speaking, address of an instance doesn't change. But, I suppose that you mean that you might want the bound instance to replaced by another without modifying the functor.
if it's stored in a vector or some other data structure which m... |
64,391,961 | 64,392,898 | largest number with each digit only swap at-most K times and only adjacent swap | I had a test, and there was a problem I still can't solve.
Given an array of numbers, with EACH ELEMENT have at-most K swap allowed, and only adjacent swap, find the largest lexicographical order.
Ex:
Input
[7, 1, 2, 3, 4, 5, 6]
swapTime = 2
Output
[7, 3, 4, 1, 2, 6, 5]
At first I thought it was a modified BubbleSort... | For lexicographical order you have to maximize the first letter, then the 2nd and so on. So you don't need to worry about using swaps on a digit as long as it helps improving the current position (going left to right) and doesn't exceed k. Here is a solution (also modyfing the input like your method):
public static voi... |
64,392,066 | 64,394,303 | How do I keep passing the output of a Halide pipeline back into the pipeline until some condition is met? | I have a Halide pipeline which takes in an image, and applies some filters to it. It works fine for a single pass. I pass in an image, and I get the processed image as the output. What I would like to do is implement multiple passes i.e., I want to keep passing the output image back into the pipeline for a number of st... | You can run the pipeline a static number of times, by unrolling it into a larger pipeline. If what you are computing is expressible as a single stage, you can run it a dynamic but unconditional number of times by using an RDom to iterate over successive applications. However, you can not express any loops with a dynami... |
64,392,338 | 64,392,468 | Some differences between xvalue and prvalue | I've been carefully studying C++ catogories recently. The difference between lvalue and rvalue seems to be clear, but I got confused when it comes to prvalue and xvalue.
Given the example below:
#include <iostream>
using std::cout;
using std::endl;
using std::move;
class Type {
public:
int value;
Type(const int... | foo2 is returning reference bound to temporary which is destroyed immediately; it always returns a dangled reference.
a temporary bound to a return value of a function in a return statement is not extended: it is destroyed immediately at the end of the return expression. Such function always returns a dangling referen... |
64,392,509 | 64,392,779 | Read symbols in WinDBG without exe | I've been using WinDBG to view some structures for an attached C++ exe, e.g
dt blah::class::thingy
+0x000 Flags: Uint4B
+0x004 Whatever : Ptr64 something
But I've been given some older PDB files for an earlier version, and I'd like to view the same structures to compare changes, but I can't load the older PDBs... | use .symopt+ SYMOPT_LOAD_ANYTHING
to load an unmatched pdb to a current exe
but be aware and use it with caution
Type information needed for structure recognition wont have much effect .
but source line numbers or Disassembly Address For a Function may not match
and provide bogus information
you can check a module with... |
64,393,031 | 64,393,558 | Why the Calculation needs to be done on Complex way? | I am expecting the fully calculated output clearly by
just doing: But the problem is the program giving the output of 6% Tax which is opposite of my expectations.
lrooms = 1 and srooms = 3, the result should 116.6 but it's not.
cout << "The total cost is: "<<(((lrooms*35)+(srooms*25))*0.06)<<'\n';
and by doing this t... | lrooms = 1 and srooms = 3, the result should 116.6 but it was not but 6.6 when doing with 0.06 and when changed to 1.06 really solved the problem.
The solution Provided by: @MikeCAT
cout << "The total cost is: "<<(((lrooms*35)+(srooms*25))*1.06)<<'\n';
But Still I don't know why it solved the problem just changing 0.0... |
64,393,225 | 64,393,646 | Why can't a std::atomic of a std::chrono time_point member variable be default constructed? | I have an atomic wrapping a chrono time_point value. The default construction of time_point is fine for me, so I expect to not need to explicitly set it. However in gcc I get a compiler error without explicitly setting the default. Here's a minimal example:
#include <atomic>
#include <chrono>
struct A
{
using Time... | Nice answer @Nicol - but I'm going to go with a libstdc++ bug.
The following code:
#include <atomic>
struct A {
A() {}
};
int main () {
std::atomic<A> a;
}
gives a similar error on gcc 8.3/9.x, but compiles w/o error on gcc 10.x (all with -std=c++17)
clang8 + libstdc++ 8.3 fails as well.
clang + libc++ compi... |
64,393,853 | 64,393,894 | class variable getting altered by code that were seemingly not executed | So I'm doing this singly linked list implementation for an school assignment. A struct of "evaluation" was defined in the header file and a object of "mylinkedlist" would hold the pointer to the head of the linked list. This should be an easy project but for some reason, whenever I try to call the add function, the hea... | The same node assigned to tempt is repeatedly added, so modifying the node will affect other references of the node.
It seems you want to allocate new nodes for each input. To do that, allocate new elements inside the loop.
// remove this
//Evaluation *tempt = new Evaluation();
do
{
// and move ... |
64,393,854 | 64,393,981 | What is the idiom here when static_cast is used on null pointer? | Static analysis flagged this code as nullPointerArithmetic:
static_cast<BYTE*>(NULL) + p_row_fields->offsets.back(), // field offset
where NULL is defined as #define NULL 0
and offsets resolves through typedef to std::vector<int>
The line in question is passed as a BYTE* argument to a method call.
My question is - Wha... | Null pointer constant converts to any pointer type, resulting in null pointer value of that pointer type. Thus, static_cast<BYTE*>(NULL) yields a null pointer of type BYTE*. This conversion works implicitly as well.
Strictly speaking, the behaviour of the pointer arithmetic on null is undefined by the standard because ... |
64,394,371 | 64,398,568 | Can you not call a preprocessor macro from a specific namespace the same way you call a function from a specific namespace? | Ok so I am working on some embedded code to go on a msp430 launch pad, I was trying to toggle a pin high and I ran into an issue when I began trying to use one of the macros in the header file which was also in a specific namespace in the main.cpp file. I assumed I could use the same convention as say to call a functio... | No, macros don’t know about namespaces. Try to avoid macros whenever possible. Here you can probably do something like
namespace msp430 {
// inline requires C++17, allowing you to put this as is in the header:
inline auto& LEDOUT_m = *reinterpret_cast<unsigned int volatile*>(0x0202u);
}
// A trick I saw in a talk by H... |
64,394,449 | 64,394,631 | Adding a new enum without breaking existing code | I have an enum with one undefined and two user values:
class enum E
{
UNDEFINED,
VALUE1,
VALUE2
};
I want to add VALUE3 but I'm worried there's a lot of code like:
assert(val != E::UNDEFINED);
if(val == E::VALUE1)
{
}
else
{
// Without an assert this wrongly assumes E::VALUE2
}
and:
something = (val =... | Enums are not restricted to the values you give names to. From cppreference (formatting is mine):
An enumeration is a distinct type whose value is restricted to a range of values (see below for details),
which may include several explicitly named constants ("enumerators"). The values of the constants are values of an ... |
64,394,514 | 64,395,233 | C++ Nlohman::json third-party support not compiling | I'm using nlohmann::json to (de)serialize some C++ objects in JSON. I haven't yet understood how to set up the code to work with a third-party library (SoapySDR). My code is in the global namespace in this example, while the SoapySDR code is in its own namespace. I'm getting a ton of compile errors with this simplif... | The to_json and from_json overloads for your data types need to be in the type's namespace for the library to find them:
namespace SoapySDR {
void to_json(json &j, const SoapySDR::Range &r)
{
j += {"min",r.minimum()};
j += {"max",r.maximum()};
j += {"step",r.step()};
}
/* ... */
}
After that, your code compil... |
64,394,551 | 64,394,694 | Undefined Reference to `SDL2_Init` with LD when G++ is not giving an error | (FYI Yes I do know that a similar question exists, But I have already tried all the answers.)
I'm trying to setup SDL2 with MinGW and I have everything set up beside one thing. Whenever I try to compile G++ gives no errors but then LD gives me a: undefined reference to SDL_Init Error.
c:/mingw/bin/../lib/gcc/mingw32/9.... | The common cause of mysterious undefined reference errors on MinGW is using libraries compiled for x64 with an x32 compiler, or vice versa. SDL ships both x32 and x64 ones, try the other ones.
I was able to fix the WinMain Error
Be aware that the intended way of fixing undefined reference to WinMain@16 is not adding ... |
64,394,587 | 64,400,073 | Visual Studio 2019 not building all cpp files when a header file changes | I have been trying to figure out why visual studio has not been recompiling all the compilation units affected by a header file change in my Library project.
Lets say I have the following header file TestA.h:
class TestA
{
public:
int GetNumber() { return 0 };
std::string GetString(); // implemented in Tes... | So after exhausting all my ideas I decided to try and just recreate the project. And that fixed it! Not sure what exactly happened but deleting all the vcxproj files and recreating the vcxproj from scratch fixed my issue. Not sure what exactly changed but that seemed to solve it
|
64,394,895 | 64,395,348 | Write Bin File Using Python C-module And Read The File In C | I'm using ctypes to convert some info in a binary file that needs to be read by a C++ program. This file will contain lines with strings and others with double/vectors of double.
The problems occur when I try to read a vector of double in C++: the address of the vector goes in the end of the line and the address has 11... | You have one deep misunderstanding here.
The pair of fields
unsigned int n_measures;
double* value;
is an array (deducing from their names), so in a writer you have to save n_measures double value, not one single pointer. Consequently, in the reader you should read n_measures values, not just a pointer. A pointer is j... |
64,395,163 | 64,395,297 | C++: Move constructor not called, unless explicit casting is called | I created a class, "ListElement", that contains as a single data variable an instance of the class "MyClass" which contains a dynamically allocated array.
For ListElement I created a default constructor which delegates to a right-value constructor that initializes an instance of MyClass.
For MyClass I created a const... |
Question 1
Because data is not an rvalue. Rvalues are nameless. data is a name ⇒ not an rvalue. Named rvalue references are references that bind to rvalues but they are not rvalues themselves.
Your cast is correct but not generic and not idiomatic. The standard library offers std::move precisely for this purpose, use... |
64,395,214 | 64,396,529 | c++, member thread object causes crash on structure deletion when it's running | I've got a player class that has a kick function where I need to wait for a bit and kick the player afterwards for reasons out of my control and I also need to not hold the function while I wait, so my problem is;
When the thread is done waiting and kicks the player, the disconnect event is risen and the memory for the... |
trying to join the thread on the destructor just causes the thing to spit a resource deadlock exception which I don't understand since it's not trying to join itself it's trying to join a member object
delaydKick_ = std::thread([p = this](){
std::this_thread::sleep_for(std::chrono::seconds(3));
p->kick(); //c... |
64,395,489 | 64,396,411 | Unable to display PNG image from file in Gtk::Window | I am having some trouble displaying a PNG file in a Gtk::Window. I tried creating a Gtk::Pixbuf from the file and then create a Gtk::Image using that. Then I tried adding the Gtk::Image to the Gtk::Window but all I'm getting a blank screen. What am I doing wrong?
class CMainWindow : public Gtk::ApplicationWindow
{
publ... | While Gtk::Application::run() will ensure that the CMainWindow is shown, it does not try to show all of its children. In your constructor, add a call to img->show();.
I recall seeing a blog post reporting that the next version of GTK+ (hence also the next version of gtkmm, presumably) will change the default behavior ... |
64,395,524 | 64,398,081 | C++ Concurrent Queue memory leak | Consider the following program, which implements a SINGLE consumer, MULTIPLE producer concurrent queue.
Runs fine in the context of 1 consumer, 1 producer.
However, putting up a second consumer (un-commenting the lines below) results in memory leaks and I can't understand why...
Using Queue's T=std::shared_ptr, and mod... | There are a number of issues with your example.
The main thing is that it's not thread-safe: Both push() and pop() modify non-atomic member variables mReadP and mWriteP while not protected by a mutex.
A second, less important issue is that waiting on the arrival of items to pop or free space to push is typically done b... |
64,395,798 | 64,416,414 | PlaySound in C++ using CLion | I am trying to make a simple C++ program that plays music, but I'm getting this error.
undefined reference to __imp_PlaySoundA'
From what I read I found out that I don't have any source code that implements PlaySound. I know I should add a reference to winmm.lib to my linker, but I only found how to do this in VisualSt... | I have already solved it, you need to add winMM.Lib to the CMake file. Plus the file can't be .mp3 but .wav (maybe some others, I did't try).
# Link to GLFW, GLEW and OpenGL
target_link_libraries(template PUBLIC
${GLFW_LIBRARIES}
${GLEW_LIBRARIES}
${OPENGL_LIBRARIES}
winMM.Lib)
|
64,396,609 | 64,396,974 | Convert 2D vector to 2d array | I have some C++ code that uses a 2D vector and needs to call an external library that uses a pointer the array with rows and col as parameters. So what I need to do is convert my 2d vector into a format that I can shove into foo((float *)data, int rows, int cols).
So 2D Vector data ---code---> foo((float *), int row, i... | You can flatten the vector
vector<float> flat_vect =
accumulate(test_vect.begin(), test_vect.end(),
vector<float>(),
[](vector<float>& a, vector<float>& b) {
a.insert(a.end(), b.begin(), b.end());
return a;
})... |
64,397,408 | 64,397,590 | How to show time from a time stamp and show current time when I have no argument? | I need to make a function which takes a timestamp (the time in milliseconds, type long) and transforms it into readable time (Y-M-D H:M:S); however, after that, I have to overload the function such that if the function doesn't get a parameter it will return the current date.
I know how to make the function to transform... | First of all (as mentioned in the comments) you should really be using the Modern C++ library's std::chrono functions for your time operations. However, sticking with the basic code that you have, you can just provide a default value for the parameter of your timeToString function; this should be a value that is meanin... |
64,397,480 | 64,397,761 | Delete shared pointer by memory address from vector | I have a vector containing shared pointers. I want to remove a pointer from the list by using its memory address, is this possible? Or is there a better way to store a collection of shared pointers?
std::vector<std::shared_ptr<Person>> list;
void removePerson(const std::shared_ptr<Person>& person) {
a... | Yes it's possible to remove a pointer from a container of pointers by address.
While std::vector<std::shared_ptr<T>> is a normal way of storing shared pointers, the question of which way is better can not be answered without knowing more about your requirements.
Here is an expansion of your template to demonstrate poin... |
64,397,550 | 64,555,335 | Matrix transposition before passing to the vertex shader | I'm very confused about passing matrices to a vertex shader, as far as i know you have to transpose matrices before passing them to a vertex shader.
But my world matrix when i pass it to a vertex shader did not work correctly, it worked fine with scaling and rotation but translation caused weird visual glitches. So thr... | It depends on the code of your shaders.
Without any of the /Zpr or /Zpc HLSL compiler options, when your HLSL code says pos = mul( matrix, vector ) the matrix is expected to be column major. When HLSL code says pos = mul( vector, matrix ), the matrix is expected to be row major.
Column major matrices are slightly faste... |
64,397,616 | 64,397,671 | C++ string does not concatenate in a class | i try to write a small program to control a pump and a valve connected with two ds18b20 temperature sensors on a raspberry pi 3B+. I defined a class for the pump and one for the valve, in the future more pumps and valves will be added, i also created a class for the ds18b20 sensor that is connected over 1 wire. The sen... | In your class declaration:
string device;
This class member is default-initialized to an empty string.
string baseDir = "/sys/bus/w1/devices/";
This class member gets default-initialized to the given string.
string tempFile = "/w1_slave";
This class member gets default-initialized to the given string.
string path = ... |
64,398,212 | 64,398,246 | Incrementing every value in a parameter pack | I am currently attempting to increment every value in a parameter pack full of std::vector::iterators of some unknown type. I am currently struggling to get my head around how the ... syntax works. I would have thought to increment every value it would be ++input_starts ... but that just gives me a compiler error. Here... | Replace this:
++input_starts ...
With this:
(++input_starts, ...)
That is a C++17 fold expression (your use case is analogous to the push_back_vec() example on that page).
Simple demo: https://godbolt.org/z/YoY4b1
|
64,398,341 | 64,398,364 | "std::transform" compiles without qualified name lookup on multiple compilers? | I was writing a library in C++ when I discovered that calls to std::transform were unexpectedly compiling fine without fully qualifying the calls with the std:: namespace prefix. According to the C++ documentation std::transform is defined in the std:: namespace so it should not compile without fully qualifying the nam... | No, it is not a bug1. This is argument dependent lookup (aka Koenig lookup).
When an argument to a function is in a particular namespace, the compiler will look in that namespace for the function itself.
In this case, the relationship may not be obvious, but the argument to the function is what v.begin() returns, which... |
64,398,353 | 64,398,367 | [C++]The value has changed even though a variable has never been assigned since the first declaration | Envs
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Background
I practice implementing DFS.
I tried to solve this problem.
Code
sorry for dirty code
#include<iostream>
using namespace std;
int dfs(int params[4], int i, int arr[3], int sum) {
cout << "i: " << i << endl;
cout << "params[0]: " << params[0] << endl << en... | The array arr has only 3 elements, so arr[3] is out-of-range and no read and write to there are allowed. It seems params is happened to be placed just after arr and writing to arr[3] is breaking data in params.
To easily fix this, allocate one more element for arr.
Better fix is to fix range of i not to cause this out-... |
64,398,420 | 64,399,306 | How to end libsoundio stream after starting? | I've built and ran the example at libsound.io.
The life cycle of SoundIoOutStream* outstream is not clear for me.
According to the example soundio_outstream_create(device) returns that pointer. Then soundio_outstream_open(outstream) and soundio_outstream_start(outstream) gets called. At this point the callback starts g... | The important thing is that: we don't create a stream for each sound clip in the resources, we create a stream each time we want to play a sound clip.
After playing the sound clip, soundio_outstream_destroy(outstream); stops the callback from getting called. The trick is that we can't call this function within write_ca... |
64,398,553 | 64,401,267 | C++: Printing dynamically allocated array to console behaving weirdly | I am having weird behavior with my print function but I am wondering if it is an IDE issue or an issue with the fact that my code and target/executable is stored on an external hard drive. OR if it is my code. it will randomly print things like '/323' '2u3m' that kind of stuff. Then I run it again and it prints totally... | This line, and lines that are similar to this:
m_list[m_count] = new char (strlen(word));
are wrong for two reasons.
First, that line does not allocate strlen(word) chars dynamically. What it does is it creates a single character dynamically, with the value of that character equal to strlen(word).
Second, even if you ... |
64,398,862 | 64,400,356 | How to print a level of a binary search tree? | If we have say, a tree with a depth of 2:
6 <- depth = 0
/ \
/ \
4 9 <- depth = 1
/ \ \
3 5 10 <- depth = 2
And I only want to print the second level, so 3, 5, and 10 (in that order), how would I go about doing this? I'm using the code I wrote fo... | Some issues:
As your initial call to printLevelNodesHelper gets the desired level as argument, it makes no sense to make recursive calls with level+1. Think about it: when you recur, you actually descend in the tree, coming closer to the desired level, so you should not increase the distance to that level, but decreas... |
64,399,234 | 64,399,319 | Local variables definition in relation to scope, C++ | When considering a local variable inside of main, e.g.
#include <iostream>
void doNothing(int x)
{
}
int main()
{
int x{0}, y{0};
doNothing(x);
return 0;
}
Would both variables (x,y) still be considered in scope when the function doNothing() is entered? I understand that a variables scope extends to where th... | The scope refers to the 'visibility' of a variable, so the scope of variables x and y is limited to main().
y would be inaccessible inside of the function doNothing()
Exactly!
If it is to be understood that a local variables lifetimes starts when it enter scope and ends when it goes out of scope, would its lifetime ... |
64,399,483 | 64,399,514 | c++ reassign after moved | From other posts that I understand after moved from, the object is in a valid, but unspecified state. Can I reassign things to the vector, illustrated by the example below:
std::vector a = {1,2,3};
std::vector b = std::move(a);
a = {1,3,4}
Does it guarantee that a will contain 1,3,4 after all.
| This is guaranteed. After the move, the vector is guaranteed to be empty, i.e. has no elements. It's fine to be assigned by other contents.
After the move, other is guaranteed to be empty().
|
64,400,050 | 64,400,167 | Link winmm.lib to CLion using CMake | I am trying to play music in my C++ project, but I'm getting undefined reference error. I know it was already answered here, but that doesn't help me at all:
What is an undefined reference/unresolved external symbol error and how do I fix it?
I know how to fix it in VisualStudio, by adding a reference to winmm.lib to m... | As @arrowd said, winMM isn't a variable,so CMake file should look like this.
# Link to GLFW, GLEW and OpenGL
target_link_libraries(template PUBLIC
${GLFW_LIBRARIES}
${GLEW_LIBRARIES}
${OPENGL_LIBRARIES}
winMM.Lib)
|
64,400,186 | 64,400,220 | Why is the output of the maximum of two string literals wrong? | Can someone explain, why the output is "C" in this code?
#include <iostream>
using namespace std;
template<class X>
X maximum(X a,X b)
{
if(a > b)
return a;
else
return b;
}
int main() {
cout << maximum("C","D") << endl;
}
| Note that in your case the type X will be inferred as const char*, hence you are comparing two const char *s i.e. the addresses of the two string literals.
If you want to get the expected result, use something like the following
cout << maximum("C"s, "D"s) << endl;
To pass std::strings instead of passing the addresses... |
64,400,531 | 64,401,980 | Scale integral types to a different bits size | How to scale up/down integral types to other sizes, example from 8 bits to 16 bits should be:
0x00 -> 0x0000
0xFF -> 0xFFFF
This is what I came up with so far as a generic solution. Scale down works fine, but scale up only works if the size of the return type is two times larger than input type, 8 to 16, or 16 to 32,... | One possible application of what OP tries to perform is the scaling of colors from a lower pixel depth (say 8 bits per pixel) to a higher pixel depth (say 16 bits per pixel).
At the first glance, you may think the factor has to be 216 / 28 = 28 = 256 but that's wrong.
It would not map 0xff (white with 8 bit) to 0xff00 ... |
64,400,847 | 64,400,889 | Call captureless with its type instead of its instance | I have a code where I can have the type of the lambda, but not its instance, and I want to call it
I tried the following, and obviously, it does not work because operator() is not a static member function...
#include <utility>
template<typename F, typename ...Args>
void call(F, Args&&... args) {
&F::operator()(std... | In your example you do have an instance. You pass it to your function, it's just that the parameter is not named. The fix is simple: name the parameter and use that:
template<typename F, typename ...Args>
void call(F f, Args&&... args) {
f(std::forward<Args>(args)...);
}
int main() {
auto is_odd = [](auto ... |
64,401,085 | 64,403,425 | boost::asio building a buffer with a boost::array containing strings | I am learning how to use boost::asio by following the examples in the documentation and expanding on them.
The examples Daytime.4 and Daytime.5 show how to implement a synchronous udp server-client communication. The example sends data by constructing a boost array of type char and then constructing a boost buffer out ... | You call the following overload of buffer function:
template<
typename PodType,
std::size_t N>
mutable_buffer buffer(
boost::array< PodType, N > & data);
which works only with POD. string is not POD type.
Buffer in boost asio can be treated as pair: pointer to data and length of data. In your case you crea... |
64,401,269 | 64,401,278 | Why am i Getting this error? error: invalid operands of types 'int' and 'int(int, int)' to binary 'operator/' | int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
int n1, n2;
cin >> n1 >> n2;
int lcm = n1 * n2; //Line 2
int rem = lcm / gcd;
cout << gcd(n1, n2) << endl;
cout << rem << endl;
I am getting an Error at line 2 saying " error: invalid operands of types 'int' and 'int(int, int)' to ... | You are getting the error because you cannot divide integers by functions.
Instead of
int rem = lcm / gcd;
it seems you wanted to call the function gcd.
int rem = lcm / gcd(n1, n2);
|
64,401,532 | 64,401,562 | error: expected a ';', bug in Intellisense when building? | I got an error in Visual Studio 2019, when building and using IntelliSense at the same time, which said that it expected a ';' (CODE: E0065 and the error is supposed to be on line 9), I am extremely confused because this is my first time getting an error like this when defining functions because it is also my first tim... | Nesting of function definition (defining functions inside another functions) is not allowed in C++ unless you use lambda functions.
Put the function definitions outside the function
#include <iostream>
using namespace std;
const double pi{3.14159};
double calc_area_circle(double radius) {
return pi * (radius * r... |
64,402,831 | 64,403,146 | Is this item from Effective Modern C++ still up to date? | p.146 of effective modern C++ :
void processWidget(std::shared_ptr<Widget> spw, int priority);
void cusDel(Widget *ptr);//a custom deleter
This was an unsafe call prior to C++17 :
processWidget(std::shared_ptr<Wdiget>(new Widget, cusDel), computePriority());
It used to be unsafe because computePriority could be calle... | C++17 did change the sequencing with regard to the evaluation of the expressions used to call a function. While it doesn't impose any particular order, it does say:
The initialization of a parameter, including every associated value computation and side effect, is indeterminately sequenced with respect to that of any ... |
64,403,127 | 64,403,754 | How to reduce the time in this program? | I have a program like this: given a sequence of integers, find the biggest prime and its positon.
Example:
input:
9 // how many numbers
19 7 81 33 17 4 19 21 13
output:
19 // the biggest prime
1 7 // and its positon
So first I get the input, store it in an array, make a copy of that array and sort it (because I use ... | Start with a basic "for each number entered" loop:
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int main() {
int n;
int newNumber;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> newNumber;
}
}
If the new number is smaller than the current largest prime, ... |
64,403,974 | 64,404,075 | How to take delimiter as -0 between array size and array value of integer in c++ | How to take delimiter as -0 between array size and array value of integer in c++.
for example: 2 -0 1,2 -0
array-size '-0' 1st array values separated by "," '-0'
If I take input in a string using get line then how to separate size from the string and take input of array.
int main(){
string s,t;
getline(cin,s);
stri... | Given the input, the easiest way is to check the string token as being the -0 delimiter.
#include <iostream>
#include <sstream>
#include <string>
using std::cin;
using std::cout;
using std::getline;
using std::string;
using std::stringstream;
int main(){
string s,t;
getline(cin, s);
stringstream x(s);
... |
64,404,171 | 64,404,366 | openMP initialization of the iterator in the for loop with curly braces | I have this main :
int main() {
std::size_t n{10000};
std::vector<int> A(n);
for (size_t k{0}; k < 10000; ++k) { // repeating the same task over and over again.
#pragma omp parallel default(shared)
{
#pragma omp for
for (size_t i = 0; i < n; ++i) {
A[i] = i;
... | The OpenMP 5.0 API doesn't allow the following construct:
#pragma omp for
for (size_t i{0}; i < n; ++i) {
A[i] = i;
}
Section 2.9.2 says:
The for directive places restrictions on the structure of all associated for-loops. Specifically, all associated for-loops must have canonical loop form(see Sec... |
64,404,409 | 64,404,513 | Is reference to this safe to use in a class? | class Obj
{
private:
Obj& self{*this};
// now use self for . notation and this for -> notation
public:
}
Are there any disadvantages to this kind of usage, or is it simply a bad idea to have 'self' as an option to use within your class?
| Nice try to use other languages syntax. But no, it's not safe:
class Obj
{
private:
Obj& self{*this};
// now use self for . notation and this for -> notation
public:
void test() { cout<< (this==&self?"ok":"nok")<<endl; }
}; // semicolon, please
int main() {
Obj o;
o.test();
Obj o2{o};
o2... |
64,405,008 | 64,408,133 | The most efficient nested array container in C++ for reading and writing? | I am a mathematician by training and need to simulate a continuous time Markov chain. I need to use a variant of Gillespie algorithm which relies on fast reading and writing to a 13-dimensional array. At the same time, I need to set the size of each dimension based on users input (they will be each roughly of order 10)... | I would start by using a std::unordered_map to hold key-value pairs, with each key being a 13-dimensional std::array, and each value being an int (or whatever datatype is appropriate), like this:
#include <iostream>
#include <unordered_map>
#include <array>
typedef std::array<int, 13> MarkovAddress;
// Define a hashe... |
64,405,126 | 65,775,152 | C blocks extension (libBlocksRuntime) - use custom memory allocator (Boehm GC) for Block_copy() | I am writing a C program that uses Apple's Blocks extension to provide lexical closures. I am also using the Boehm garbage collector. What I would like is for Block_copy() to use GC_MALLOC when allocating blocks on the heap, so that they are garbage collected.
#include <stdio.h>
#include <Block.h>
#include <GC.h>
int m... | Ok, I've finally worked it out. There's probably a better way of doing this, but the only documentation for this I could find was the source code. Firstly, you need to #include the Block_private.h header as well as Block.h. This allows access to the _Block_use_GC() function. The version of libBlocksRuntime in the Debia... |
64,405,152 | 64,405,256 | Is it faster to use iterator-based search-and-use in STL associative containers? | Let's say I'm trying to check if an item exists in an associative container, and do something to it if it does. The simple way to do this is as follows:
std::unordered_map<std::string, Whatever> thisIsAMap;
// C++17
if (thisIsAMap.count("key") > 0u) { doThing(thisIsAMap["key"]); }
// C++20
if (thisIsAMap.contains("key... |
Is the latter approach actually any better?
Yes. For several reasons.
First, doing one map lookup is definitely at least as fast as doing two map lookups. Best case, the compiler optimizes out the second lookup, but I've never actually seen that happen in practice and that seems like a lot to rely on.
Second, using f... |
64,405,162 | 64,405,206 | Draw GL_LINE in QOpenGLWidget using array of coordinates | I have working application done using QtCreator. My render class is
GLRendWindow::GLRendWindow(QWidget *parent): QOpenGLWidget(parent)
Now I would like to draw objects using arrays with coordinates of vertices.
I found some tutorial that draws triangle on this page:
OpenGL Window Example
I tried to reused it to draw s... | You missed to set specify the array of generic vertex attribute data for the color attribute (attribute lowp vec4 colAttr;). This is similar to specifying the vertex attributes.
For example, add the following code to GLRendWindow::drawLine:
GLfloat line_colors[] =
{
1.0f, 0.0f, 0.0f, // red
0.0f, 0.0f, 1.0f //... |
64,405,340 | 64,405,416 | Why the white spaces are ignored when converting to encrypted message? | The Program should print the expected messages as expected but its not printing.
Plain Text message: Hello! how are you?
Expected encrypted message: Glqqv! bvc Rfl avm?
The program is printing: Glqqv!bvcRflavm
White spaces are totally ignored. How to fix it?
The Code:
#include <iostream>
#include <string>
using namespa... | ' ' is not part key.
To handle c not found in key and remain unchanged, add an else statement.
float position = alphabet.find(c);
if(position != string::npos) {
char new_char {key.at(position)};
encrypted_message += new_char;
} else // add
encrypted_message += c;
}
Recommen... |
64,405,396 | 64,407,086 | Segmentation Fault when trying to access pointer to Node | I'm trying to initiate an element inside a Node struct but whenever I try to access it I get a Segmentation Fault. I have initialized the Node inside my Stack class but cannot insert an element on it.
Stack.h
#ifndef QUEUE_H
#define QUEUE_H
struct Node;
// Pilha de números inteiros.
class Stack {
public:
// Repre... | In your Stack class' constructor, you are using (de-referencing) the top_ member pointer before having initialized to anything meaningful. Since its value is likely some kind of junk, you're trying to access an address in a virtual memory segment not set up for your process; thus you get a "Segmentation Fault".
What to... |
64,405,533 | 64,405,699 | Polymorphism in c++ - Access functions over pointers | Got the following simple structure:
class Base {
public:
virtual void foo() { std::cout << "Base" << std::endl; }
};
class Derived1 : public Base {
public:
void foo() override { std::cout << "Derived1" << std::endl; }
void boo() {}
};
class Derived2 : public... | If you can be sure the pointer points to a Derived1 object, then static_cast it:
static_cast<Derived1*>(p1)->boo();
If you don't know if it points to a Derived1 object, then you need to test for that first with a dynamic_cast:
if (auto* as_derived1 = dynamic_cast<Derived1*>(p1)) {
as_derived1->boo();
}
dynamic_ca... |
64,405,625 | 64,405,747 | Doing cartesian product the functional way in C++17 | I'm trying to implement cartesian product using a closure / custom function, the closure is function(x,y) = pow(x,2) + pow(y,2) and implement it the functional way i.e. without using the C-style loops.
Here is my take.
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
void... | Your compilation issues are because you are not capturing the needed variables in your lambdas, and you're missing some ;.
However, a simpler way to do a cartesian product is with 2 nested loops, like this:
for (int i : a)
for (int j : b)
cartesian.push_back(i * i + j * j);
If you want to use algorithms, then y... |
64,405,790 | 64,405,868 | Use parameters with user defined type parameters without declaring a default parameter for that type | This is what happened (I simplified the problem to be easier to see):
#include<iostream>
class number_holder{
public:
int value;
number_holder(int value_to_set){
this->value=value_to_set;
}
};
class number_holder_pair{
public:
number_holder first;
number_hol... | In this constructor:
number_holder_pair(number_holder first, number_holder second)
{ // <--
this->first=first;
this->second=second;
}
before reaching the marked line, all the members must be initialized. However, there is no default constructor for number_holder, and so the first and second members can't be d... |
64,405,800 | 64,412,261 | Matrix Multiplication on SYCL using 2D std::vector | I'm new to SYCL and C++. This is my kernel for simple matrix multiplication using 2D std::vector.
void MatrixMulParallel(queue& q,
const std::vector<std::vector<double>>& a_host,
const std::vector<std::vector<double>>& b_host,
std::vector<std::vector<double>>& c_gpu) {
/*
To Multiply: C[M][P] ... | A 2D std::vector<std::vector<T>> does not have elements stored contiguously in the memory.
A better way around would be to declare std::vector<T> with sizes M*N, i.e. linear arrays, and operate on them as contiguous blocks.
Since the destination vector C, is supposed to be 2D, create a kernel that indexes in both rows ... |
64,405,915 | 64,406,241 | c++ Hold instructions for a later time | I am trying to design a UIDraw method. I want to declare what UI elements to draw in the main Draw method But then Have a separate UIDraw Method later in the code. So I need a way to store instructions to execute in this new function. I hope it makes sense.
Something like this:
Draw();
DrawUI();
But sa... | There are many ways to tackle this problem depending on what exactly you need. One approach popular in the OO world is the so called Command Pattern (similar approaches exist in other programming paradigms, they just have either different names or are considered so obvious they don't even get a specific name at all).
T... |
64,406,467 | 64,407,549 | How to fix "error C1083: Cannot open include file :'simpleclass.h' :no such file or directory" when using a library? | I have a very very simple C++ class and tool is QT Creator.
I created a Non-QT project.
Have the SimpleClass class as given below
simpleclass.h
#ifndef SIMPLECLASS_H
#define SIMPLECLASS_H
class SimpleClass
{
public:
SimpleClass();
void printLine();
};
#endif // SIMPLECLASS_H
simpleclass.cpp
#include "simplec... | Cause
Your include path is set to $$PWD/libs:
INCLUDEPATH += $$PWD/libs
but the screenshot does not show simpleclass.h in that location.
Solution
Delete from UseLibrary.pro:
win32: LIBS += -L$$PWD/libs/ -lTestLibrary
INCLUDEPATH += $$PWD/libs
DEPENDPATH += $$PWD/libs
Right click the UseLibrary project in the pr... |
64,406,603 | 64,408,565 | Double checked locking implementation - using atomic vs not using | I saw this cpp core guideline and I'm trying to understand something:
http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#cp111-use-a-conventional-pattern-if-you-really-need-double-checked-locking
Why is the first example marked as bad? Is it only because the variable is volatile? What harm can happen if the fi... | Making the function thread-safe bears a cost. Yes, example 1 is faster, that is because it is not doing the required job.
There is a fundamental error in your thinking, that you can reason about concurrent accesses without atomics or syncing. The assumption is wrong. Any concurrent read and write from a non-atomic vari... |
64,406,726 | 66,520,900 | Is it possible to use C++20 modules in bazel with custom rules? | Bazel does not have direct support for modules (See Issue #4005).
However, it is possible to provide bazel with a custom CROSSTOOL.
From https://docs.bazel.build/versions/0.22.0/crosstool-reference.html:
By default, Bazel automatically configures CROSSTOOL for your build, but you have the option to configure it manual... | Yes, it is. Here's an outline of how to do it.
Add a custom provider for tracking module information:
ModuleCompileInfo = provider(doc = "", fields = [
"module_name",
"module_file",
"module_dependencies",
])
Add a custom rule cc_module for producing C++20 modules. Then you can write something like
cc_modu... |
64,406,744 | 64,406,816 | Returning the remaining mean in an array | Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.
I've already attempted this problem and I believe that I am right however it isn't outputting the results i was hoping for.
Example:
Input: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6... | On this line:
double average = sum / (largest - smallest);
the right hand side consists of only ints and so you are doing integer division, and then assigning it to a double.
You can fix this by making sum a double:
double sum = 0;
Also, sorting the entire range is needlessly inefficient for this problem. You only c... |
64,406,949 | 64,596,747 | Linking an external library bundle file on macos with cmake | I have a library compiled as a single file that I'm trying to link with cmake but haven't been able to cobble together something that works using existing examples that should be related, eg.
CMake link an external library
Cmake linking external libraries
What I have so far:
cmake_minimum_required(VERSION 3.17)
project... | This may not be helpful to anyone else because it was so specific to the one library I was using, but here it is anyway.
cmake_minimum_required(VERSION 3.17)
project(atem)
set(CMAKE_CXX_STANDARD 14)
find_library(CoreFoundation_Library CoreFoundation)
mark_as_advanced(CoreFoundation_Library)
set(
SWITCHERS_SDK_INCLU... |
64,407,005 | 64,408,239 | How to remove dependencies in this OpenMP summation exemple | I'm starting with OpenMP now, and need to achieve parallelism in this task with OpenMP:
for (i = 0; i < N; i++){
index += i*alpha + 4;
sum += array[index];
}
I intend to use reduction operator to get the correct value of sum variable , but in order to do that I need to solve the dependency of the index variable firs... | The loop cannot be straightforwardly parallelized because of the sequential dependency. However, it can be first split in two parts:
for (i = 0; i < N; i++) {
index += i*alpha + 4;
tmp[i] = index;
}
for (i = 0; i < N; i++) {
sum += array[tmp[i]];
}
Once split, the first loop exhibits a scan pattern and can be paral... |
64,407,268 | 64,437,064 | Vulkan instance creation fails | I have a vulkan program that is running on my laptop but fails on my desktop. The error is:
HeatMethod: ../libraries/vulkansdk-linux/1.2.154.0/source/Vulkan-Headers/include/vulkan/vulkan.hpp:13143: typename vk::ResultValueType<vk::UniqueHandle<Type, Dispatch> >::type vk::createResultValue(vk::Result, T&, const char*, c... | The problem was trying to set the validation layers on a build script:
os.environ['VK_INSTANCE_LAYERS'] = 'VK_LAYER_LUNARG_standard_validation'
Deleting that line solved the issue.
|
64,407,527 | 64,407,550 | How to restrict the instantiation of a class based on the ancestry of the templated type | I have a templated class XX and would like to restrict the instantiation of it to only types T that are descendants of another class ZZ:
class ZZ {
public:
int transmorgificationFactor;
};
template <typename T>
class XX {
public:
static_assert(std::is_base_of<ZZ, T>, "T must be a ZZ");
T foo;
// ...
};... | std::is_base_of is a type, which can't be used as a condition in static_assert. You're looking for std::is_base_of_v instead:
static_assert(std::is_base_of_v<ZZ, T>, "T must be a ZZ");
// ^^
or pre-C++17, you can do:
static_assert(std::is_base_of<ZZ, T>::value, "T must be a ZZ");
... |
64,407,675 | 64,407,836 | Pointer arithmetic within the while loop exit condition with C++? | EDIT POST ANSWER: This is NOT a pointer arithmetic issue, see answer #1
I am trying to figure out why the two programs below are NOT equivalent. I am learning pointers for the first time and I think there is something I am not understanding correctly about pointer arithmetic. I am using C++
int main()
{
int array[]... | It may just be a typo but, in your second code snippet, the while loop comparison will never be false because your are testing if a value is less than "itself + 10".
What you probably wanted is to compare the pArray pointer, after each increment, to its original value, which was a copy of the array address; so we can u... |
64,407,908 | 64,407,998 | Static inheritance with variadic templates | I am trying to use std::conditional to implement static inheritance.
I have two possible parents of my child class, parent_one, which should hold multiple variables based on passed types, and parent_two, which takes two types. I am using tag dispatching to differ between the classes I want to inherit from.
Now to the p... | std::conditional_t<
std::is_same_v<T, one_t>,
parent_one<ARGS...>,
parent_two<ARGS...>
>
Here both alternatives are validated before the condition is checked. std::conditional_t is not magical, being just a regular template it requires all template arguments to be valid before it can do anything.
You need ... |
64,407,963 | 64,417,354 | How to convert binary into a wav file in c++ | I am working on a project where I need to take input from a microphone in c++, and create a wav file that stores the recorded microphone. Right now, I made a simple function that just reads from the microphone, and dumps it into a bin file. I can open it in audacity and hear what I said, but I wish to convert it to sou... | Okay so I managed to find an article that walks you through how to do it. You need to have a bin value in order to do this, so you could use my code to get the bin from your microphone if you wish. Here is the article, and good luck! -- http://blog.acipo.com/generating-wave-files-in-c/. Also here is another site that d... |
64,408,503 | 64,416,910 | Why isn't the derived-class version of the function being called? | I'm trying to store multiple different derived classes from the same base class in a vector of pointers. Trying to call a function of one of those objects results in a segmentation fault. I haven't used inheritance very much, but I've tried every version I've been able to find and they either result in a segmentation ... | vector<Player*> players(2); declares a vector with two elements that will both be default initialized to nullptr.
Later, you add two more elements, so that players has 4 elements.
When state has a value of 1 or 2, the call to players[state-1]->getMove(game); will dereference a null pointer, resulting in your segmentati... |
64,408,769 | 64,408,872 | How to do a print version of 3D objects with templates? (c++) | I guess you have seen this particular function:
template<typename T> void print(const T& cont){
for (auto &i: cont)
std::cout << i << " ";
std::cout << std::endl;
}
It print's almost all type of containers like std::list. Now i wanna create one that prints (as example) 3D std::vector, look at this fant... | You can write the following template overloads, one that prints a 1-D range, and one that prints an N-D range by printing each nested (N-1)D range in a loop:
template<template<typename...> class Range,
// ^ ^
// Note the template template parameter
typename T>
void print... |
64,408,866 | 64,410,632 | SFML - Sprite is blank after loading from texture | I am using SFML to display a sprite on the screen. I first use a texture and call loadFromFile() to load the image. This works well with no errors occurring. It seems that the image path is correct and it loads the image, but it doesn't seem to store the data in the sprite. The sprite is displayed without error, but it... | An sf::Sprite object doesn't internally copy the passed sf::Texture object when you call the setTexture() member function. An sf::Sprite just refers to an sf::Texture; the former doesn't own the latter. The associated sf::Texture must exist when you render the sf::Sprite.
It is stated in the documentation for sf::Sprit... |
64,409,332 | 64,412,524 | Best way to draw gps point with qt | I dont really know how to ask this question but I will do my best to explain. I have a project on arduino with a gps, I transfere the geo point via serialdata on my pc. I can read it without probleme, but where I need help is how I can draw a path of that point. for the moment I use this:
void MainWindow::paintEven... | You can use QTransform to scale and move the polygon. QPainter scaling will increase the width of the drawing line.
Use QPolygonF::boundingRect() to get the original points' size and scale from there.
#include "mainwindow.h"
#include <QPainter>
#include <QPolygonF>
#include <QDebug>
MainWindow::MainWindow(QWidget *pa... |
64,409,364 | 64,409,471 | Passing Dynamic Two Dimensional Array as argument to a functoin in c++ | Hy guys, I actually Trying to create a 2D Array in c++ but not able to create that, When I execute the following statement
int arr=new int[10][10]
It gives me error and when I search on google it shows me 2D array in c++ is array of pointers which is declare like the below statements
int** a = new int*[rowCount];
for(... | you need to get the parameter in your function as pointer
void displayArray(int **a)
{
for (int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
cout<< a[i][j] <<"\t";
}
cout<<endl;
}
}
int main()
{
int** a = new int*[10];
for(int i = 0; i < 10; ++i)
... |
64,409,499 | 64,409,545 | Multiplication of value of each postition of String? | I have this string str . I want to Multiply value of each position of string with 7 or any value. First I used string Function str.at() and stored in a new char type variable, but when i multiplied the index 0 value: 9 with 7 it's giving me 399 instead of 63. I have also tried this without a string function, like this:... | That's because '9' ASCII code is 57. See
To get the expected result use something like the following
string str = "9958721";
char s = str[0];
cout << 7 * (static_cast<int>(s) - static_cast<int>('0'));
to subtract the equivalent ASCII value of zero. Note that they are ordered.
And see Why is "using namespace std;" cons... |
64,409,928 | 64,411,328 | Run-Time Check Failure #2 - Stack around the variable 'sortObject' was corrupted. how to fix? | I was trying to store numbers in an array. The first half of the array are numbers that are ascending 1,2,3,4,5 etc and the second half of the array are random numbers. When i run the program it produces the output I wanted but gives me the error please help
#include <iostream>
#include <cstdlib>
using namespace std... | As i could see you want the array size to change during run time depending on the input, we need to dynamically allocate a array.so take a integer pointer as a field instead of static array.
then inside the sort function after reading the input, dynamically allocate the memory to pointer.(actually its better if we do i... |
64,409,962 | 64,410,027 | why do i have to add a new variable in this code | I was trying to write a code that takes two numbers as a input and change the numbers into words in certain rules.
Below is the code I wrote at first, but whatever input I put in, the loop starts from x=0.
#include <iostream>
int main() {
string nums[10] = {"zero","one","two","three","four","five","six","seven","... | In first sample that you provided you defined a local variable(x) as same name in outer block:
for (int x = x; x <= y; x++)
In fact shadowing of variable take place here and c++ hide the declaration of variable of outer block with same name in nested block.
|
64,410,011 | 64,410,085 | Creating buffer in SYCL for 2D std::vector | What is the correct way to create a 2D std::vector buffer in SYCL?
I have a template function which receives arguments as shown below:
template <typename T>
void MatrixMulParallelNaive(queue& q,
std::vector<std::vector<T>>& a,
std::vector<std::vector<T>>& b,
std::vector<std::vector<T>>& c){
// Is... | No. vector<vector<T>> doesn't create a contiguous block of memory. You need to use vector<T> and interpret it as a two dimensional block of data.
|
64,410,059 | 64,410,066 | C++ How do I get a reference to a nested map, to remove an element? | How do I get a reference to the second map here? I want to be able to delete elements by using items.erase(). In the example below, the number of elements in the main map doesn't change, it only changes the copy. C++ 98 only please.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
... | The copy happens here
map<int, string> items = it->second;
so just change that to a reference
map<int, string>& items = it->second;
I think you will also need to change
map<int, map<int, string> >::const_iterator it = acks.find(10);
to
map<int, map<int, string> >::iterator it = acks.find(10);
|
64,410,245 | 64,410,332 | separate the size of array and array value by delimiter -1 in c++ |
Separate the size of array and array value by delimiter -1
Input is of the form:
Array-size -1 array-values(separated by ,) -1 number -1
3 -1 3,5,7 -1 6 -1
Don't use vector, take the values into array of size given by user otherwise print "-1".
I have tried this code but I am not able to complete it:
#include <iostr... | Your code doesn't seem a million miles away, but you haven't decalred values, and you have initalised ss in the wrong place, and used delimiter2 where you meant delimiter3, and you tried to use push_back on an array.
Other errors are reading integers values as strings, which seems to be making more work for yourself.
F... |
64,410,496 | 64,410,549 | why doesnt the bool function return false? | I'm soo sorry I searched for and read similar questions but couldn't understand/use them to solve my own.
Im writing a bool function within an if statement but the function doesn't seem to return false, what am I doing wrong.
My bool function just checks if there are more than one of the given number in an array:
bool ... | I think you got confused why "false" is not getting printed on console with the function returning the false value.
You need to add to an extra else statement to print false on the console:
if(findsame(a,b)){
std::cout<<"true";
}else{
std::cout<<"false";
}
Also, there are two 4 values in the array, therefore ... |
64,410,564 | 64,410,606 | how to send an email using libcurl | I'm able to send an email to my gmail successfully, but it's sending an empty message and not able to send contain message , anyway the code I'm using is as follows:
#include <stdio.h>
#include <string.h>
#include <curl/curl.h>
#define FROM "<xxxxxx@gmail.com>"
#define TO "<xxxxx@gmail.com>"
static const char*... | static const char* payload_text[] =
{
"To: " TO "\r\n",
"From: " FROM "\r\n",
"Subject: SMTP TLS example message\r\n",
"Contain: Helllo\r\n",
NULL
};
should be something like
static const char* payload_text[] =
{
"To: " TO "\r\n",
"From: " FROM "\r\n",
"Subject: SMTP TLS example message\r\n",
"\r\n... |
64,410,970 | 64,411,134 | Using a value in a class to set equal to a new value without changing previous value c++ | I am using a class structure for rational numbers. I'm trying to essentially use the r2 values for the num and den (numerator and denominator) and have them be negative and equal to r3. While r3.output(cout, "r3") should output
r3: 4/1.
Current output of code (when I remove the r3):
r1: 10/3
r2 = -4/1
I cannot grasp ho... | You never initialize r3. It probably should be throwing a warning (maybe with the -Wextra g++ flag or something of that ilk). As Botje mentioned, one option would be to code neg() as a constructor for a Rational object that takes a reference to a Rational object being negated.
Another option is to code neg() as a void ... |
64,411,130 | 64,411,287 | Is this BOM in UTF-8 incorrect? | I want to verify BOM in UTF-8, and wrote the c++ codes below.
However, the result was 0XFFFFFFEF, 0XFFFFFFBB, 0XFFFFFFBF.
This is different from what I expected 0XEF, 0XBB, 0XBF.
Why did the result became above?
By the way, the UTF-8 file used was made by Notepad++.
#include <iostream>
#include <fstream>
using namespa... | The BOM itself is fine. You are simply printing out the bytes incorrectly.
The result you are seeing is due to sign extending signed 8bit char values to signed 32bit integers. Whether char is signed or unsigned is compiler-defined, unless you state it explicitly in code. In your case, you are using (implicitly) signed ... |
64,411,398 | 69,230,726 | Parse the .dbc file and generate C++ code to represent classes/struct for each message( for target ECU ) | I am trying to generate C++ code from a .dbc file.
e.g. A message is defined like following in .dbc file
BO_ 500 IO_DEBUG: 5 IO
SG_ IO_DEBUG_test_unsigned : 0|8@1+ (1,0) [0|0] "" DBG
SG_ IO_DEBUG_test_signed : 8|8@1- (1,-128) [0|0] "" DBG
SG_ IO_DEBUG_test_float1 : 16|8@1+ (0.1,0) [0|0] "" DBG
SG_ IO_DEBUG_test_flo... | Here is a python script which generates C++ code. You need to install cantools packages to run following script.
import cantools
import math
def build_name(name):
nodes = name.split("_")
nodes[0] = nodes[0].title()
return "".join(nodes)
def signal_variable_name(signal_name):
return "m_" + build_name(s... |
64,411,685 | 64,411,712 | Does stripping all symbols from a static library prevent linking? | As far as I know, the linker's job is to match undefined symbols in an object file with symbols defined in a static library. If found, the proper symbol definition is included into the final executable. This is the so-called symbol resolution.
So what happens if all symbols get stripped away from the static library? Do... | Stripping symbols is an operation that's normally meant to remove debug information on symbols, not symbols needed for the actual linking process (though it can be used to remove symbols for things that you don't want used in the linking process if, for example, you didn't generate the object file).
It would be a rath... |
64,411,846 | 64,425,679 | nghttp2-asio : Proper way to set content-type in header | I came up with this code, but not sure if it is right usage:
boost::system::error_code ec;
nghttp2::asio_http2::header_map headers;
headers.insert(std::pair<std::string, nghttp2::asio_http2::header_value>("content-type", {"application/json; charset=utf-8", false}));
headers.insert(std::pair<std::string... | Yes, what you have done is correct way of setting a header in nghttp2 asio. Please read the documentation to know the usage of the sensitive field here.
For brevity, you can use std::make_pair. For example:
headers.insert(std::make_pair("content-type", {"application/json; charset=utf-8", false}));
|
64,412,356 | 64,412,490 | Merge Sort Base Case | I'm practicing sorting algorithms and I'm stuck on this silly issue.
I specifically don't understand how the array is partitioned to arrays that only contain single (sorted) element. I drew out a call stack example to illustrate my confusion.
void merge_sort(int A[], int start, int end) {
if (start < end) {
... | When start == end it means there's only a single element to "sort".
And since start == end also means that start < end will be false, then from that follows that the function skips everything inside the if body.
So merge_sort(A,0,0) doesn't do anything, but return back up the call-stack to merge_sort(A,0,1) .
Looking ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.