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 |
|---|---|---|---|---|
73,977,805 | 73,978,141 | IXAudio2Engine::CreateSourceVoice fails | I receive the Error XAUDIO2_E_INVALID_CALL when I try to call IXAudio2Engine::CreateSourceVoice. My code for creating a source voice is as follows:
auto sample_rate = quality_to_sample_rate(settings.quality, sound_category::effect);
WAVEFORMATEX wave_format{ // 8000Hz 16 bit mono WAV
.wFormatTag = WAVE_FORMAT_PCM,
... | Reading the docs helps:
nBlockAlign and nAvgBytesPerSecond need to be set correctly.
nBlockAlign needs to be (nChannels * (nBitsPerSample/8)) / 8 and
nAvgBytesPerSecond is nBlockAlign * nSamplesPerSecond
|
73,979,485 | 73,980,936 | Get number of active threads spawned by current process on MacOS | I've been searching for the last 3 hours online and through system headers, but can not find a mechanism available to me in C/C++ for what I'm trying to do on MacOS.
I'm looking to find a way to retrieve for the currently running process the total number of active/alive threads. I acknowledge that this would be trivial... | From a bit of googling around, it seems to me like you should be able to obtain this information using task_threads(), after getting the right mach port from task_for_pid():
int pid = 123; // PID you want to inspect
mach_port_t me = mach_task_self();
mach_port_t task;
kern_return_t res;
thread_array_t threads;
mach_msg... |
73,979,818 | 73,979,930 | Copying non-sequential columns from an array into another array C++ and removing duplicates based on 1 column | I want to copy columns from a std::vector<std::vector<double> > into another std::vector<std::vector<double> > in C++. This question answers that but only deals with the case where all the columns are in a sequence. In my case, the inner std::vector has 8 elements {C1, C2, C3, C4, C5, C6, C7, C8}. The new object needs ... | I would use std::transform.
It could look like this:
#include <algorithm> // transform
#include <vector>
#include <iostream>
#include <iterator> // back_inserter
int main() {
std::vector<std::vector<double>> orig{
{1,2,3,4,5,6,7,8},
{11,12,13,14,15,16,17,18},
};
std::vector<std::vector<do... |
73,979,843 | 73,993,243 | Using a swig wrapped c++ library with go | I have managed to successfully wrap a large C++ library with SWIG. I published the module and can install it okay, but when I go to build it I get a ton of undefined reference errors to the functions contained within the generated c file.
I placed the generated so lib file in my system lib directory, and placed the hea... | The reason is that Go compiler has no idea about the library librawgo.so.
Put the following line to the top of the C comment in librawgo.go:
#cgo LDFLAGS: -L<path/to/dir/with/librawgo.so> -lrawgo -lraw
This instruction tells the compiler to add this line to the linker flags.
Sorry, I don't know how to modify your CMak... |
73,979,892 | 73,979,999 | std::unique_lock::_Owns data member is not atomic? | Looking through the std::unique_lock implementation in MSVC14, I noticed it has a data member
bool _Owns;
Since _Owns is used by operator=, operator() and owns_lock() amongst other, I was expecting _Owns to be atomic. Anyone can comment as to why it is not?
Thanks.
| A std::unique_lock object cannot be accessed by multiple threads (that would be completely counter to its purpose), so it doesn't need to consider atomicity of the data stored in itself.
The lock object has a reference to a mutex object (e.g. std::mutex) on which it calls member functions to lock or unlock the mutex fo... |
73,980,275 | 73,980,507 | Dynanically choose derived class to instantiate – how to take care of memory? | Consider the following setup:
struct Base {
virtual void f() = 0;
virtual ~Base() {};
};
struct Helper: Base {
virtual void f() {}
};
struct Derived: public Base {
Derived(Helper& helper): m_helper(helper) {}
void f() {}
Helper& m_helper;
};
that I, at the moment, use conditionally using prepro... | You can use std::shared_ptr instead of std:unique_ptr:
auto h = std::make_shared<Helper>();
std::shared_ptr<Base> p;
if (condition) {
p = std::make_shared<Derived>(*h);
} else {
p = h;
}
Alternatively:
auto h = std::make_shared<Helper>();
auto p = condition ? std::shared_ptr<Base>(new Derived(*h)) : h;
Though... |
73,980,365 | 73,980,978 | Can gcc emit code as efficient as clang for the binary tree "LowerBound" algorithm? | I have been implementing various node based binary search trees using C-ish C++ code. When benchmarking these I have noticed surprisingly large performance variations both across compilers and in response to small code changes.
When I focused on insertion and removal in a tree that allowed duplicates (as a C++ std::mu... | Using llvm-mca, which is a tool from the LLVM suite to analyze the machine code for a given architecture, we can see that indeed there is a difference.
For the Intel Skylake architecture the code generated by GCC versus LLVM:
Instructions: 1200 vs 1200
Total Cycles: 1305 vs 1205
Total uOps: 1700 vs 14... |
73,981,222 | 73,982,351 | Attaching .pdb to a compiled .exe in Visual Studio 2022 | I am trying to debug a .exe file with a .pdb. The project is using SCons, and here is the part where it compiles in sconstruct:
env.Append( CCFLAGS=["/EHsc"])
env.Append( CCFLAGS=["/DEBUG", "/Zi", "/Fdgame.pdb"])
env.Program('game', ['game.cpp', Glob('feather/*.cpp')], LIBS=['SDL2', 'SDL2_image', 'SDL2_ttf', 'SDL2_mix... | Try changing to
env.Append( CCFLAGS=["/EHsc"])
env.Append( CCFLAGS=["/DEBUG", "/Zi"])
env.Program('game',
['game.cpp', Glob('feather/*.cpp')],
LIBS=['SDL2', 'SDL2_image', 'SDL2_ttf', 'SDL2_mixer', 'SDL2main'],
LIBPATH='lib/Windows/lib', PDB="game.pdb")
If that's still not in the... |
73,981,381 | 73,981,864 | why is GNU make not filling out the $^ variable here? | I can compile the project just fine if I run the project by hand with g++ source/* -lSDL2 -o bin/fly_fishing. When I do run make, I get
mkdir -p bin
g++ -lSDL2 -o bin/fly_fishing
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/12/../../../x86_64-linux-gnu/Scrt1.o: in function `_start':
(.text+0x17): undefined reference to... |
Which tells me that it's not populating from $^ for linking.
That seems unlikely. Much more likely would be that $^ expands to nothing. Which would be the case if $(OBJ) expands to nothing. Which seems plausible because I don't see any corresponding objects being built (though perhaps you've omitted that, or they ... |
73,981,511 | 73,981,751 | How to Access a Struct in a Class through a Function in Main? | I'm using a function void displayStudent(Student stu), which displays the student's info. In my main(), I did this (all the parameters have been created in main() respectively already, and Student is my class):
Student student1(name1, id1, dept1, year1);
displayStudent(student1);
Now, in my display function, here is ... | On this line:
cout << "Name: " << stu.getName() << endl;
stu.getName() returns a Name struct, but by default the compiler doesn't know how to print a Name struct to an std::ostream, like std::cout, when using operator<<. So you need to implement your own operator<< overload for printing a Name, eg:
struct Name {
... |
73,981,813 | 73,981,901 | What is a bfloat16_t in the C++23 standard? | Cppreference documents that stdfloat includes 5 new types: float16_t, float32_t, float64_t, float128_t and bfloat16_t. While the first 4 types are self-explanatory (a float with 16, 32, 64, and 128 bits respectively), the last type bfloat16_t is not at all clear to me. What does this type represent? What does the b in ... | "bfloat16" refers to a fairly recent 16-bit floating-point format that is not a valid IEEE-754/IEC 60559 defined format. But it is related to them.
BINARY16 is just BINARY32 with smaller numbers for its components. But the size changes are evenly distributed; it has both a smaller mantissa and a smaller exponent.
Bfloa... |
73,982,002 | 73,982,470 | C++20 concepts: accumulate values of all good types passed to function variadic template | I write a function variadic template that can be used like this:
auto result{ Accum<int>(10, 20, 1.1, "string") }; // result is 31.1;
Using binary operator+ Accum accumulates values of types from parameter pack for which init_type{} + value; arithmetical operation makes sense. If used with empty parameters pack, Accum... | A string literal is of type const char[/*...*/] which can be added to an integral type. The array decays to a const char* pointer and int + const char* is then pointer arithmetic advancing the pointer by the given integer value. So the string literal will never be replaced in your scheme.
You are only checking that eac... |
73,982,242 | 73,982,753 | leetcode question 81 c++ returns wrong answer | question:
There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).
Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]... | To figure out why it's not working, you can walk through one of the failing test cases. You'd want to pick the easiest one to manage in your head, so in this case I recommend one of those with an array length of 1.
So let's walk through
input [1] target 1 returned false expected true
Your function first creates two l... |
73,982,638 | 73,982,974 | custom std::set.find() for a set of pointers | class Node{
public:
Node* back1 = nullptr;
Node* back2 = nullptr;
int value;
Node(int value) {
this->value = value;
}
//bool operator< (const Node& rhs) const {return this->value < rhs.value;}
bool operator< (const Node* rhs) const {return this->value < rhs->value;}
};
std::unorder... | find takes as input the key type. In your std::unordered_map, that key type is int, and in your std::set that key type is Node*.
If you want to use your elements' sorting, then you can change your std::set's key to be Node instead of Node*. std::set's comparison uses operator < (via std::less) by default, so you can ... |
73,982,834 | 73,982,879 | C++ function type and callable object | I'm trying to assign callable object to function object with conforming call signature. This is my code:
#include <functional>
int add(int i, int j) { return i + j; }
struct div {
int operator()(int denominator, int divisor) {
return denominator / divisor;
}
};
int main() {
auto mod = [](int i, i... | Including <functional> includes <cstdlib> which brings a function div into your current namespace.
Change your struct div to struct Div and the error goes away.
|
73,983,024 | 73,983,543 | Minimum number of jumps | Given an array of N integers arr[] where each element represents the max length of the jump that can be made forward from that element. Find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then you cannot move through that element.
Note: Return -1 if you ... | There are multiple ways through the array.
The one you described is:
2 1 1 2 2 1 6 jumps
┌───┬─┬─┬───┬───┬─┐
2 3 1 1 2 4 2 0 1 1
But you can also do:
1 3 2 2 1 5 jumps
┌─┬─────┬───┬───┬─┐
2 3 1 1 2 4 2 0 1 1
↑
jump 1 forward, not 2
You can find an optimal solution as:
1 3 1 4 4 jumps... |
73,984,557 | 74,078,792 | Why do some assignment operators for the helper classes of std::valarray return void? | For example, the assignment operators for std::slice_array:
void operator=(const valarray<T>&) const; //#1
void operator=(const T&) const; //#2
const slice_array& operator=(const slice_array&) const; //#3
#1 and #2 return void, but #3 returns const slice_array&.
It prohibits some code, such as:
std::valarray<int> va{1... | While returning a reference from operator= is the common and reasonable way for implementations, keep in mind that valarray is a rarely used and an unsupported library. See C++ valarray vs. vector for more detailed answers on this topic.
From one of the answers:
ISTR that the main reason it wasn't removed from the sta... |
73,985,013 | 73,985,433 | Beaglebone black gpio pin out not as expected, LED blink program | Im follwoing this guide: https://www.teachmemicro.com/beaglebone-black-blink-led-using-c/
And when connecting at P9_13 i do not get any LED Blinking. ( I also tried to set it manually, and can check that gpio is high, but LED is still dark).
I move the right-hand side wire (green) from the breadboard to P9_2 and P9_4 a... | The guide actually is referencing P9, while shematic is according to P8.
And in addition, the program should use gpio26 (not gpio23) if using P8 Header (Atleast for my board).
UART is used for serial commnunication, so i guess that is not a general purpose io....
Anyway, question solved after realizing this :)
|
73,985,352 | 73,987,241 | concept for check and out-of-bounds | I am trying to define a C++20 concept that enforces the implementors to check for an out of bounds.
template <size_t Num>
concept IsInBounds = requires (const size_t idx) {
requires idx >= Num;
};
So, for a method that I have in a custom container that returns a non-const reference to an element inside it, I want ... | If you want to provide the out-of-bounds checking at compile time, you must provide the index via template parameter. You should rely on a std::size_t value to provide the index that the client code wants to retrieve, and, with the concept, index will be determined when the template is instanciated. This will lead the ... |
73,985,869 | 73,989,665 | Passing variables to an embedded Python script from C++ | I need to run a Python script from c++, but I need also to pass it some variables. It can't be a function with parameters, because there are hundreds of variables, so the syntax would become too messy.
I will post a simple example, analogue to my case.
This is the Python script:
script.py
c = 10 * 5 + a
print(c)
And t... | The following will do the trick:
Py_Initialize();
PyObject *locals = PyDict_New();
PyObject *globals = PyDict_New();
PyDict_SetItemString(locals, "a", PyLong_FromLong(123));
PyDict_SetItemString(locals, "b", PyLong_FromLong(9));
PyRun_FileExFlags(fopen("script.py", "r"), "script.py", Py_file_input, globals, loca... |
73,986,076 | 73,986,399 | What is the difference between x+=x and x = x +y in C++ | I don't understand why my two expressions produce the same result even though the second expression calls f() twice.
I am using gcc with C++20 enabled.
#include <iostream>
using namespace std;
int& f(int& i, string name);
int main() {
puts("\n-------------------------------------\n");
int x = 5;
/* expr... | Note that this is undefined behaviour before (and correct after) C++17 which explicitly sequences evaluation of left, right sides including their side-effects.
f(x, "one") += 1
is evaluated as:
Evaluate right side to 1.
Evaluate left side:
Set i: 5->6
Return ref to i which holds 6.
Evaluate += by adding one to th... |
73,986,528 | 73,986,699 | subtraction of iterators that give integer number | can someone tell me what happens under in this subtraction?
why did I get a number in the end? its build operator '-' or something else?
int main(){
vector<int> v{5,3,8,3,9};
auto p=remove(begin(v),end(v),3);
cout<<p-begin(v);
return 0;
}
output: 3
| Iterators for std::vector are LegacyRandomAccessIterators, and you can see in that link that subtracting one such iterator from another yields a difference_type. For std::vector, this is defined as "a signed integer type (usually std::ptrdiff_t)", which sounds like what you wanted.
And yes, the magic occurs inside ope... |
73,986,853 | 74,018,009 | How can I create a cmake configuration for tensorflow lite? | I want to create a cmake configuration for my tensorflow lite project. The problem is that I do not know how to link my project with tensorflow. Here is my project tree:
.
├── app
│ ├── include
│ └── src
│ └── main.cpp
├── build
├── CMakeLists.txt
├── README.md
└── tensorflow # <-- submodule of the tensorflow... | This website answers the question:
https://www.tensorflow.org/lite/guide/build_cmake#create_a_cmake_project_which_uses_tensorflow_lite
For anyone in the future, here is my cmakelists.txt:
cmake_minimum_required(VERSION 3.2.2)
project(app LANGUAGES CXX)
option (FORCE_COLORED_OUTPUT "Always produce ANSI-colored output (... |
73,987,256 | 73,987,312 | Why base class copy and move constructors should not be inherited? | CWG2356:
Base class copy and move constructors brought into a derived class via a using-declaration should not be considered by overload resolution when constructing a derived class object.
But other constructors that are inherited from the base class only initializes the base class subobject, too.
So, why base class... | Keep in mind, the default implementations of the copy/move constructors of the derived class already call the base class copy/move constructors. If the base class copy and move constructors were eligible for overload resolution, you would make the following legal, which in general is not desirable:
Base b;
Derived d =... |
73,988,300 | 74,009,824 | Using a package from packages.config in C++ visual studio 2017 | I am developing a code in C++ using as IDEE Visual Studio 2017 on my Windows 10 workstation. I need the onnxruntime library, so I have installed it by the NuGet package menager. The installation went ok and in my solution I have a folder Resource files and within it I have the file packages.config. Its content is:
<... | OnnxRuntime lib and dll can be found in folder Yourproject\packages\Microsoft.ML.OnnxRuntime.XXX\runtimes\win-x64\native.Header file folder XXX\packages\Microsoft.ML.OnnxRuntime.XXX\build\native\include
Try adding them as dependencies.
|
73,988,574 | 73,990,872 | Given x>0, is it possible for sqrt(x) = 0 to give a floating point error? | Question in title.
I have a section of code:
double ccss = c * c + s * s;
double sqrtCCSS = sqrt(ccss);
if (sqrtCCSS != 0)
{
n = n1 / sqrtCCSS;
}
and am just wondering if this is safe:
double ccss = c * c + s * s;
if (ccss != 0)
{
n = n1 / sqrt(ccss);
}
My gut tells me yes, but floating point error is still s... |
and am just wondering if this is safe:
double xxyy = x * x + y * y;
if (xxyy != 0)
{
n = n1 / sqrt(xxyy);
}
It's always safe because floating-point math doesn't trap and you can freely divide by zero or even Inf/NaN, unless you tell the compiler to trap on those cases
Anyway if you just want to check whether the... |
73,988,769 | 73,993,565 | Returning range of different containers | I have multiple containers with the same element type T. I would like to select one of the containers depending on a enum.
I tried something like this:
auto range = [category,system]() -> auto {
switch(category) {
case sound_category::voice:
return std::ranges::views::all (system->dialogue_voice... | ranges-v3 has any_view for type erasure view.
So it would be something like:
auto range = [category,system]() -> ranges::v3::any_view<Voice>
{
switch(category) {
case sound_category::voice:
return std::ranges::views::all (system->dialogue_voices); // could be std::array
case sound_catego... |
73,989,392 | 73,997,506 | GDK: Expression must be a modifiable value | I have a function which works with GdkPixbufs (simplified):
void test_function(std::vector<GdkPixbuf> &images)
{
std::vector<std::filesystem::path> filenames = {"path/a", "path/b"};
for(int i = 0; i < 2; i++)
{
images[i] = *gdk_pixbuf_new_from_file(filenames[i].string().c_str(), NULL);
}
ret... | Compiling on Gtk4, I got this error,
usr/include/c++/12/bits/stl_vector.h:1124:41: error: invalid use of incomplete type ‘struct _GdkPixbuf’
1124 | return *(this->_M_impl._M_start + __n);
| ~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~
/usr/include/gdk-pixbuf-2.0/gdk-pixbuf/gdk-pixbuf-core.h:89:16: note... |
73,989,424 | 74,053,302 | Custom values in Qt Creator (CMake) build settings | I want to achieve the equivalent of C++ #define foo "bar" but I don't want the value "bar" to be part of my code repository, and the value will depend on whether the build is Debug or Release.
How can I do this?
NB: I like the idea of using the following in CMakeLists.txt add_compile_definitions(foo="bar") but I don't ... | You need a 2 step process:
Add a Qt Creator build setting to create a CMake cache variable.
In CMakeLists.txt use the cache variable within a command.
For your example:
In Qt Creator build settings,
either click Add > String setting Key to MYPROJECT_FOO and Value to bar
or click Batch Edit... and add -DMYPROJECT_F... |
73,990,029 | 74,508,778 | Difference between a vector and a dynamically allocated array | What are the internal differences of choosing to use an std::vector vs a dynamically allocated array? I mean, not only performance differences like in this matching title question.
I mean, I try to design a library. So I want to offer a wrapper over an StackArray, that is just a C-Style array with some member methods t... | First there is a mindset (usually controversial) between the usage of the modern tools that the standard provides and the legacy ones.
You usually must be studing and asking things about C++ modern features, not comparing them with the old ones. But, for learning purposes, I have to admit that it's quite interesting di... |
73,990,342 | 73,992,226 | Showing the unlock from std::condition_variable::wait | I've read from https://en.cppreference.com/w/cpp/thread/condition_variable/wait that wait() "Atomically unlocks lock". How do I see this via std::cout? I am trying to understand conditional variables better on what they're actually doing. I've wrote an attempt below.
#include <chrono>
#include <condition_variable>
#inc... | std::unique_lock and std::lock_guard work with any class type that satisfies the requirements of BasicLockable. So, just write your own class that wraps a std::mutex, then you can add whatever logging you want.
UPDATE: However, std:condition_variable only works with std::mutex specifically, so if you write your own mu... |
73,990,548 | 73,990,575 | How to provide C++ version when extending python | I want to make c++ code callable from python.
https://docs.python.org/3/extending/ explains how to do this, but does not mention how to specify c++ version.
By default distutils calls g++ with a bunch of arguments, however does not provide the version argument.
Example of setup.py:
from distutils.core import setup, Ext... | You can pass compiler arguments as extra_compile_args so for example
module = Extension(
"Hello",
sources = ["hello.cpp"],
extra_compile_args = ["-std=c++20"]
)
|
73,990,941 | 74,014,524 | How to find out the coordinates of the two vertices of a TopoDS_Edge (Openscascade)? | I want to find out the coordinates of the two vertices of a TopoDS_Edge.
I couldn't find any solution on the Public Member Functions list on https://dev.opencascade.org/doc/refman/html/class_topo_d_s___edge.html
| With this you can get the vertices of any topological object in OpenCascade:
TopoDS_Edge edge;
for (TopExp_Explorer ex(edge, TopAbs_VERTEX); ex.More(); ex.Next())
{
gp_Pnt point = BRep_Tool::Pnt(TopoDS::Vertex(ex.Current()));
double xCoord = point.X();
}
This is also capable of iterating over other types of t... |
73,991,485 | 73,992,662 | What parameters should I put in functions | How do I know which variables to declare as parameters and which ones I should just declare inside the function?
| Let's say I want to write a function that prints a name. So you can say that the function needs information that is not in the function.
One method is to ask the User:
void print_name()
{
std::string name;
std::cout << "Enter name: ";
std::cin >> name;
std::cout << "\nname is: " << name << "\n";
}
The above f... |
73,991,545 | 73,991,845 | Can I avoid a second object when using a unary operator on a temporary? | The usual meaning of unary operators such as bitwise inversion, postfix increment, and unary minus is to return a modified copy of their argument. When their argument is a temporary, is there a way to modify that original object, thus avoiding the creation and destruction of a second object?
The examples below both in... |
Is there a way to rewrite the struct so that example 2 only creates and destroys a single object?
But your code says to create two objects. You create a prvalue and then perform an operation on it which is not initializing some other object. That operation requires manifesting a temporary from that prvalue. That's ob... |
73,991,660 | 73,991,924 | Vulkan RAII. Got VK_ERROR_NATIVE_WINDOW_IN_USE_KHR when trying to create VkSurfaceKHR | I'm learning Vulkan_raii API and ran into this problem:
I have the source file:
#include <vulkan/vulkan_raii.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
int main() {
glfwInit();
GLFWwindow *window =
glfwCreateWindow(800, 600, "First window", nullptr, nullptr);
if (!window) {
std::cerr << "Failed ... |
But I can't even imagine how my window can be already connected to the surface.
Because that's what glfwCreateWindow does. The library is called "GLFW" because, by default, it creates OpenGL windows. Which counts as "some other non-Vulkan API".
If you want to use it with Vulkan, you have to follow special rules for t... |
73,992,048 | 73,995,287 | Detect if there is an error when importing a point cloud and display alert message without closing application PCL and C++ | I am trying to import a point cloud into a program I have made with the PCL and C++ library. This program must be able to load different files and that, in case of encountering one that has some error at the time of having made its coding, it indicates that there has been an error but in no case makes the application b... | Try pcl::io::loadPLYFile() (https://pointclouds.org/documentation/group__io.html#ga0cfc645cc531647728e16088b6342204) instead of pcl::io::loadPolygonFilePLY()
|
73,992,176 | 73,992,395 | Segfault when deleting from a set C++ | Segfaulting code
Hey all, was just wondering how to delete elements from a set if its detected in another set.
The current code iterates through both sets using a for loop, then if the value the iterators hold is the same, it attempts to erase from the first set.
It would look something like this:
#include <iostream>
u... | The simple solution is to use one for loop.
for (auto val : myset2)
myset.erase(val);
and not the doubly-nested for loop you're using now.
The std::set::erase can erase by key or iterator. All you need to do is provide the key element in this case.
Full example.
|
73,992,532 | 73,999,129 | Segfault when reading ELF Shdr of own executable | I'm trying to read the symbol table of the program's own ELF binary as part of a symbolizer. Part of this involves finding the ELF start, then ELF shdr, etc. I must be doing something wrong, though, because despite e_shoff matching what I see by readelfing the binary manually and the start address looking reasonable, I... |
maybe the sections just aren't loaded into memory...
That's exactly right. Here is readelf -WS /bin/date on my system:
Section Headers:
[Nr] Name Type Address Off Size ES Flg Lk Inf Al
[ 0] NULL 0000000000000000 000000 000000 00 0 0 0
[ ... |
73,992,908 | 73,992,993 | Manipulation with an array using iterators | I want to reverse an array of chars using 2 iterators, but i figured out that i entry the loop once and swap() never worked.
`
std::vector<char> s = {'a','b','c','d'};
std::vector<char>::iterator it1{s.begin()}, it2{s.end() - 1};
while(it1 < it2){
swap(it1,it2);
++it1;
--it2;
}
`
If i write while(it1 != it2),I w... | The problem is that the std::swap function requires two references. The iterators need to be dereferenced for the swap, as you are swapping the values that the iterators point to, not the iterators themselves.
swap(it1, it2);
needs to be replaced with
swap(*it1, *it2);
The rest of your code seems to be fine and with... |
73,993,084 | 73,993,278 | Why does Gio::Settings require a delay? | I'm writing an application in C++ that uses both Qt and GIO. It happens to be an embedded Linux platform, but I don't know if that matters much. I have a function that sets a setting that another program uses:
void setCityName(const QString &cityName)
{
const Glib::RefPtr<Gio::Settings> settings = Gio::Settings:... | As the documentation says:
Writes made to a GSettings are handled asynchronously.
Call Gio::Settings.sync: https://docs.gtk.org/gio/type_func.Settings.sync.html
|
73,993,434 | 73,993,683 | Method pointer and constness | Consider the following hypothetical example:
template<typename T, typename R, typename... Ps>
R call(T& t, R (T::*method)(Ps...), Ps... ps){
return (t.*method)(ps...);
}
struct A{
int f(int i) const {return i;}
};
A a;
Then call(a, &A::f, 3) wont compile, because f is const. Can I make call work without provi... | There is already a standard library function that allows calling any callable, including member function pointers. You can simply use that for your wrapper function and it will automatically allow using any kind of callable as well:
With C++20:
decltype(auto) call(auto&& f, auto&&... args) {
/* do whatever you want... |
73,993,667 | 73,993,697 | Why does Microsoft use types like __int32 etc instead of int32_t? | While browsing the implementation of standard library headers in Visual Studio with C++ 20, I came across the type __int64, it looked like a built-in type and I couldn't go to its definition. I googled it and found this article by Microsoft. Apparently the types __int32, __int64 etc are Microsoft-specific built-in type... | Because MSVC existed long before C++11 was introduced. For things that need a fixed size obviously they have to user their own internal type. That's why those have the __ prefix because the standard says that names beginning with double underscores are reserved in the global namespace
That's also the reason why lots of... |
73,993,910 | 73,994,076 | Fastest way to read / write text file, excluding specific string | I am writing a program which reads large (10Gb+) text files, structured in chunks, like this:
@Some_header
ATCCTTTATTCGGTATCGGATATATTACGCGCGGGGGATATCGGGG
+
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:::::::::
@Some_header unfixable_error
ATTTATTTAGAGGAGACTTTTATTTACCCCCCCCGGGGGGATTTTA
+
FFFFFFF:::::::::::::::FFFFFFFFFFUUUUUUU... | Here is few points:
substr creates a new string which is quite expensive for a simple comparison. You can use string views since C++17 to avoid new strings to be created. An alternative solution is to use compare with a position and size. Since C++20, there is also ends_with which is simpler here.
std::endl flushes th... |
73,993,950 | 73,994,559 | Create *.o files in a separate folder | I'm trying to make so that the *.o files are kept in /bin however after running it, the *.o files are not kept.
my file systems is as follows:
> bin
> src
*.cpp
> headers
*.h
makefile
.
CC := g++
CFLAGS := -Isrc/headers
NAME := run
SRC := src/
HSRC := $(SRC)/headers/
OBJ := bin/
SOURCES := $(wildcard... | Your main, high-level problem is that you are not testing the makefile as you develop it, so the bugs pile up before you know they're there.
The first concrete problem is that your assignment to OBJECTS is incorrect, and doesn't work the way you think it does. The patsubst function uses %, not *, so it ought to be:
OBJ... |
73,993,979 | 74,128,070 | C++ function somehow prevents main from being invoked | I encountered a strange issue in C++ and OpenCV2. The following code does not print "I ran!":
#include <iostream>
#include <opencv2/opencv.hpp>
// Opens image as grayscale and saves it to save_dir
int grayscale_file(const cv::String &file_dir, const std::string &save_dir){
cv::Mat fi = cv::imread(file_dir, cv::Im... | After weeks of head-scratching and research, I eventually figured out that my debugger was throwing an error at me (as pointed out in the comments). I was able to find info on fixing it from this question, which lead me to believe that my libraries were still not properly linked.
I am not 100% sure on why or how the er... |
73,994,094 | 73,994,126 | I am trying to loop inserting elements into a set if they intersect, but it isn't giving me what im looking for | all and all2 are both string sets. all is filled with actors in movie1, and all2 is empty. my loop is supposed to check if an actor in movie2 is also in movie1, and if they are then to insert that actor in all2. However my code is just outputting all the actors in movie2.
all = imdb.find_actors_in_a_movie(matchedMovie1... | Instead of writing a loop, use std::set_intersection.
#include <string>
#include <set>
#include <algorithm>
#include <iterator>
#include <iostream>
int main()
{
std::set<std::string> all = {"Joe", "Jack", "Mary", "Frank"};
std::set<std::string> actors_in_movie2 = {"James", "Jack", "Philip", "Frank"};
std::... |
73,994,270 | 73,994,302 | Are temporaries created as arguments in a call guaranteed to hold their lifetimes until the function call returns? | I need to return char arrays from a method what() to be used in printf() and variants.
The obvious solution of printing to a (thread local) static internal buffer obviously does not work because of the multiple calls problem.
#include <cstdio>
unsigned int counter = 1;
const char* what() {
static char buf[8];
b... | Yes it's well-formed.
[class.temporary]/4
Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created.
That means the two temporaries will be destroyed after the invocation of printf (immediately).
|
73,994,546 | 74,154,670 | Node-addon-api - construct ObjectWrap from C++ | I'm new to NAPI, and I'm trying to convert and old Nan code to NAPI.
What happens is that I have a structure like this:
class PointWrapper : public Napi::ObjectWrap<PointWrapper> {
public:
static void init(Napi::Env env, Napi::Object exports);
PointWrapper(const Napi::CallbackInfo& info);
private:
Point point;
}
... | Ok, so I found a solution - it's clumsy, but at least it works. The first thing I had to do was to make the "constructor" a variable that other places could use. So I changed my class to have a *constructor pointer:
class PointWrapper : public Napi::ObjectWrap<PointWrapper> {
public:
static void init(Napi::Env env, N... |
73,995,409 | 73,995,457 | C++ How can i remove the last comma? | #include <iostream>
using namespace std;
int main() {
string x;
cin >> x;
char ch;
/* how can i remove the last comma? */
int l = x.length();
for (int i = 0; i < l; i++) {
ch = x.at(i);
cout << ch << ",";}
return 0;
}
I expect:
in... | Do this(Basically you print the comma separately between that you check if it is the last iteration and works for any numbers):
#include <iostream>
using namespace std;
int main() {
string x;
cin >> x;
char ch;
/* how can i remove the last comma? */
int l = x.length();
for (int i = 0; i < l; i++) {
ch ... |
73,996,053 | 73,996,070 | C++ linking error: duplicate symbol for different source file | If two variables as same type and name in different source files, the linker command failed with duplicate symbol error, although two source files are not related.
This is my project structure.
CMakeLists.txt
cmake_minimum_required(VERSION 3.0.0)
project(duplicate-symbol-test VERSION 0.1.0)
add_executable(duplicate-sy... |
How should I solve it?
By making all symbols local to their translation unit. Global non-const variables have by default external linkage, thus two variables with the same qualified name clash during linking.
This can be fixed by either:
declaring them static - forcing internal linkage.
putting them into an anonymou... |
73,996,114 | 73,996,275 | Get all input of int from cin separated with space in c++ | N = Input How much attempt (First Line).
s = Input How much value can be added (Second, fourth and sixth lines).
P = Input of numbers separated with space.
Example :
3 ( Input N )
2 ( s 1 )
2 3
3 ( s 2 )
1 2 3
1 ( s 3 )
12
Example :
Read #1: 5 (Output s1 = 2 + 3)
Read #2: 6 (Output s2 = 1+2+3)
Read #3: 12 (Output ... | #include <iostream>
using namespace std;
int main() {
int t; //number of attempts
cin >> t;
while(t--) { // for t attempts
int n, s = 0; //number of values and initial sum
cin >> n;
while (n--) { //for n values
int k; //value to be added
cin >> k;
... |
73,996,577 | 73,996,740 | How can I get the object of specific type from vector that contains multiple type of objects | I've got a question, if we have a class A and other classes from class B : class A to class Z : class A are inherited from class A, and we have a vectorstd::vector<A> that contains objects of all types from class A to class Z, how can we get an object of specific type from that vector, for example we want to get object... | You cannot store subtypes of A in a std::vector<A>. Any objects of a subtype you put in there are sliced and every element in the vector is simply an object of type A.
You could use a std::vector<std::variant<A, ..., Z>> instead. You should probably think about a different design though:
#define TYPES(x) \
x(B) ... |
73,997,093 | 74,067,666 | What is the correct exception to throw when a method is called at an inappropriate time? | I have a class which exposes a method which should be called a certain number of times by the user of the class. The amount of times the method is to be called is agreed upon via an int parameter during object construction. Thus, while calling it too few times could be due to the caller deciding to cancel the operation... |
What is the correct exception to throw when a method is called at an inappropriate time?
std::logic_error, preferably a struct/class deriving therefrom.
struct PixelOverflowException : public std::logic_error {
PixelOverflowException() : std::logic_error("Cannot accept further pixels: resampled image is already c... |
73,997,779 | 73,998,138 | Generate a sequence of null values follwed by one at compiletime | I have a problem similar to
Generating a sequence of zeros at compile time
However, in my case I have no pack to expand. The situation is like this:
template<size_t N>
void foo()
{ bar(T{}, ..., static_cast<T>(1)); }
There are N - 1 T{}:s followed by a one.
It may happen that T is not usable as a non-type template par... | you generate the sequence yourself
#include <utility>
template<std::size_t N>
void foo(){
[&]<std::size_t...I>(std::index_sequence<I...>){
bar((I,T{}) ... , static_cast<T>(1));
}(std::make_index_sequence<N-1>());
}
|
73,997,839 | 73,998,111 | Why can't C++20 compliant compilers detect memory leaks? | In C++20 we can allocate memory in constexpr contexts as long as the memory is freed within the context — i.e this is valid:
constexpr int* g(){
int* p = new int(100);
return p;
}
constexpr int f(){
int* ret = g();
int i = *ret;
delete ret;
return i;
}
static_assert(f() == 100);
Whereas this w... |
surely the functionality that allows compile-time constexpr leak detection could be extended to some degree of general compile-time leak detection too?
No, it can't.
Compile-time code execution means that the compiler is executing the code. That is the "functionality that allows compile-time constexpr leak detection"... |
73,998,574 | 73,999,058 | Call boosts dijkstra shortest paths algorithm using a external weight map | I want to create a graph and call Dijkstra multiple times using different weight maps. I read that I can use an associative_property_map to map edges to weights but I don't know how to call Dijkstra using this custom map as a weight map.
#include <iostream>
#include <vector>
#include <map>
#include <boost/graph/adjacen... | You are mixing positional parameters with named parameters. The overload with named parameters doesn't take a weightmap positional: https://www.boost.org/doc/libs/1_80_0/libs/graph/doc/dijkstra_shortest_paths.html
So, add the weight map to the name parameters:
using graph = boost::adjacency_list<boost::vecS, boost::vec... |
73,999,066 | 73,999,503 | Converting lambda (cpp) to function pointer (for c) | I am trying to implement a parallel runtime using argobots api.
In the main.cpp I am using a lambda function which is argument to the "kernel" function in lib.cpp. I need to convert the lambda received in lib.hpp to a function pointer and call "lib_kernel" in lib.c. I have read many answers and came to know that conver... | You can convert a lambda to a function pointer with +, i.e.:
typedef void (*func)(void* args);
void kernel(func fn, void* args){
fn(args);
}
void CallKernelWithLambda() {
func f = +[](void*) { };
kernel(f, nullptr);
}
However, lambdas that capture cannot be converted to a function pointer -- the followi... |
73,999,161 | 73,999,605 | Score average (Cambodian Idol Practice) | I'm having a bit of trouble with a coding project the question is as follows.
A particular talent competition has five judges, each of whom awards a score between 0 and 10 to each performer. Fractional scores, such as 8.3, are allowed. A performer’s final score is determined by dropping the highest and lowest score rec... | For solving this problem, you don't need to define isLowest() and isHighest() function. You can directly find the highest and lowest number by just comparing all numbers and also in your calcScore() function, you have not covered all cases. For example if num1 is lowest and num2 is highest.
Here is the correct code -
#... |
73,999,191 | 73,999,201 | Variadic arguments template method specialization | I'm in a process of implementing loadAsset method in my asset manager implementation. I've tried using variadic arguments template method with following signature:
class AssetManager {
public:
template <typename AssetType, typename... Args>
void loadAsset(std::string_view name, const Args &...args);
...
};
And f... | If you specialize a template in a cpp file, that'll be available in the given file, but not externally (unless, of course, if you instantiate it manually). Best way to do it is to move all template definitions to header.
|
73,999,513 | 73,999,568 | How to overload variadic template function based on size of parameter pack in C++ | I'm sorry if this question is basic. Let's say I have a function template that took in a parameter pack of arguments. How would I overload it so that there might be a specialization for 2 arguments getting passed in, 3 arguments passed in, etc.
| For small parameter packs, I'd use non-variadic overloads:
template <typename A, typename B> void foo(A a, B b);
template <typename A, typename B, typename C> void foo(A a, B b, C c);
If you prefer to have a pack, you can constrain the size with requires or std::enable_if_t:
template <typename ...P> requires(sizeof...... |
74,000,137 | 74,000,510 | Practical difference between implicit and defaulted constructor in C++ | As far as I know, in C++ default constructors are declared (and defined if needed) implicitly if there is no user-defined default constructors. However, a user can declare a default constructor explicitly with the default keyword. In this post the answers are mainly about the difference between the implicit and default... | To the best of my knowledge, there is no functional or theoretical difference, both are still "trivial."
Uses of an explicit default constructors:
To ensure it exists when it would not otherwise be created, i.e. if a different constructor exists
You can default it in a different compilation unit:
Header file:
struct ... |
74,000,262 | 74,000,462 | Move semantics and overload | I think my understanding of rvalue references and move semantics has some holes in it.
As far as I've rvalue references understood now, I could implement a function f in two ways such that it profits from move semantics.
The first version: implement both
void f(const T& t);
void f(T&& t);
This would result in quite so... | If you need to take a T&& parameter, it usually means you want to move the object somewhere and keep it. This kind of function is typically paired up with a const T& overload so it can accept both rvalues and lvalues.
In this situation, the second version (only one overload with T as a parameter) is always less efficie... |
74,000,296 | 74,000,321 | Cannot add constant to vector | I tried to add path to my vector but it's defined by constant. What do I need to do to fit the data from entry.path() to my vector.
#include <iostream>
#include <string>
#include <vector>
#include <filesystem>
namespace fs = std::filesystem;
int main () {
std::vector<std::string> sourceContent;
std::string re... | Yout need you to use the string() member function:
sourceContent.push_back(entry.path().string());
Another option would be to store actual paths in the vector instead:
std::vector<std::filesystem::path> sourceContent;
|
74,000,607 | 74,000,709 | Can I compile and dlopen a dynamic library in Compiler Explorer? | Just for the purpose of learning, I've made a small example of a main program tentatively loeading a shared library via dlopen (and then a symbol from it via dlsym) and using a default one if the former is not avalable.
On my machine, to make the non-default library available to the main program, I need to compile the ... |
Can I compile and dlopen a dynamic library in Compiler Explorer?
Yes, it's certainly possible.
In CMakeLists.txt:
add_library(MyLib SHARED MyLib.cpp)
...and remove MyLib.cpp from add_executable.
Then in main.cpp:
void * lib = dlopen("build/libMyLib.so", RTLD_LAZY);
Because the library is placed in the build subdire... |
74,000,681 | 74,008,810 | Deserialize Json object from mqtt payload using ArduinoJson library | I'm trying to deserialize a Json object using the ArduinoJson 6 library. The object is passing through a mqtt callback using the PubSubClient library. The payload contains the following example: "{\"action\":\"message\",\"amount\":503}" but I am unable to retrieve the amount value. Only zeros are returned when using th... | Update & resolution:
The first method in my original post worked fine once I fixed the data that was being sent from the Lambda function to the IOT side. (Something I didn't include in my original question and didn't think it was relevant. Turns out it was.) Here is a snippet from the Lambda function that is receiving ... |
74,000,804 | 74,000,824 | STL function to get all dimensions of a vector in c++ | I wish to know if there is any STL function in c++, to get the dimensions of a vector.
For example,
vec = [[1, 2, 3],
[4, 5, 6]]
The dimensions are (2, 3)
I am aware of size() function. But the function does not return dimensions.
In the above example, vec.size() would have returned 2.
To get second dimension, I would ... | In C++, a(n std::)vector is, by definition, 1D-vector of size() elements, which can be changed in runtime.
You can define a vector of vectors (e.g., std::vector<std::vector<int>>), but that doesn't have a constraint that the 'inner' dimensions are the same. E.g., {{1, 2, 3}, {1, 2}} is valid.
Therefore, inner dimension... |
74,000,936 | 74,000,987 | C++ std::string bug when adding size as string in map | I found Some thing on
visual studio v143 tools std:c++ lastest
is it bug or something
std::unordered_map<std::string, std::string> map;
std::string test_str = "1234567890123456789012345678901234567890123456789012345";//55 LEN String
map["test_len"] = test_str.length();
std::cout << map["test_len"]; // 7 on 55 len strin... | In statement
map["test_len"] = test_str.length();
std::unordered_map::operator[] default-constructs a new std::string and returns a reference to it which is then assigned to a value of type size_type. This assignment invokes std::string::operator=(char) which interprets integer value 55 as ascii character 7.
This is a... |
74,001,426 | 74,002,222 | Cannot have separate declaration and implementation of class with custom variadic non-template parameters | Is this a bug in Clang (the default version used by Xcode 14)? The following code does not compile:
struct TestValue
{
};
template<TestValue... Values>
struct TestCompiler
{
TestCompiler();
};
template<TestValue... Values>
T... | This is a clang bug since the program is well-formed as this is the correct way of providing an out of class definition for a nontemplate ctor of a class template.
Here is the clang bug report:
Clang rejects valid out of class definition of a nontemplate constructor of a class template
|
74,001,933 | 74,002,020 | G++ responds differently to const int** and const int* as function parameters | I was writing a C++ function that takes int** as input and the function itself does not modify the data (i.e. matrix elements). So I decided to make the argument a const int** type (Is that an acceptable practice?). A sample code is like this:
void func1(const int* k) {
std::cout << *k << '\n';
}
void func2(const i... | With multiple levels of pointers, a type is only more const-qualified if every level of pointer from the right has const added. This is for const-correctness reasons so that when you assign to the pointer, you can't accidentally assign a more const-qualified pointer at the "lower" levels of pointers when you have multi... |
74,002,217 | 74,002,470 | Is there a way to access variable declared in for loop outside of for loop? | For example, there is a char named 'character' defined in a for loop. Can I possibly use the char outside of the for loop?
Code:
#include <iostream>
int main()
{
for(int i = 0; i < 5; i++)
{
char character = 'a'; // Char defined in for loop
}
std::cout<<character; // Can this be made valid?
... | Yes, you can do this indirectly in C++11 and later, with a lambda:
#include <iostream>
#include <functional>
int main()
{
std::function<char()> fun;
for(int i = 0; i < 5; i++)
{
char character = 'a'; // Char defined in for loop
fun = [=](){ return character; };
}
std::cout << fun() << std::endl;
... |
74,002,327 | 74,047,435 | Cannot compile with buildroot 2022.08.1 | I'm having issues compiling with buildroot 2022.08.1. There seems to be nothing on the internet (that I can find anyway) that can help me so I'm turning to the legends of the internet.
Currently on linux mint 20.3, Kernel 5.19-surface
Normally I wouldn't ask but I can't really find much of a specific error message here... | aarch64-buildroot-linux-gnu-g++.br_real: fatal error: Killed signal terminated program cc1plus
This is a typical symptom of an OOM (Out-Of-Memory) - the v8 javascript engine takes a lot of memory. Check the kernel logs on your build machine (journalctl -ke or dmesg | less) just after this error happens.
If it is indee... |
74,002,699 | 74,002,766 | On Linux, what's the use of installing clang++ if it uses g++ libs only? | For C++ development on Linux, if I install clang and use it; it actually uses libstdc++(the g++ lib). What's the use of installing the frontend compiler clang on linux then?
I should be good with gcc/g++ only on a linux machine as that's a complete toolchain!
Note: I'm not an expert in C++.
| libstdc++ is a default runtime on your Linux. libc++ is not installed by default. If you link your app to libc++, you have to add it as a runtime dependency.
You are right, gcc/g++ is good for Linux, moreover its diagnostic messages are more clear, thus the compiler is better for beginners. By using clang++, you need t... |
74,002,759 | 74,002,932 | C++ Constexpr Template Structs with String Literals | Currently using C++20, GCC 11.1.0.
I'm trying to create types in a namespace with a unique value and name. I came up with this structure specifically to be able to access the variables with the scope resolution operator like so: foo::bar::name. However, I have no idea how to initialize the name variable. I tried adding... | Since we can't pass string literals as template arguments, we have to use some other way. In particular, we can have a static const char array variable as shown below:
static constexpr char ch1[] = "somestrnig";
static constexpr char ch2[] = "anotherstring";
namespace foo
{ //--------------------vvvvvvvvvvvvvvvv--->a... |
74,003,709 | 74,003,751 | how to get a class to take in another classes parameters? |
I want to have my grid class constructor to take in drivers_location parameters , but it keeps giving me these errors.
https://imgur.com/a/y4MZqso
#include <iostream>
#include <string>
using namespace std;
class drivers_location {
public:
drivers_location() = default;
drivers_location(string name, float ... | The correct syntax for declaring a constructor takes argument of type driver_location is as shown below. Note that you don't have to specify the 2 parameters of driver_location when defining the constructor for grid that has a parameter of type driver_location.
class grid {
public:
grid() = default;
//---vvvvv... |
74,003,817 | 74,004,091 | C++ Reference being duplicated when generated in loop at runtime | I have recently switched from C# to C++ trying to learn SFML for graphical animation.
I am trying to generate multiple CircleShape with random radius at runtime whose reference is saved as an object class, whose reference is then saved in a vector array.
However, after generating the shapes and iterating through the ar... | I think @AlanBirtles is right. On each iteration new sf::CircleShape(circleRadius); allocates new memory, so the pointer someValue will point to the different memory addresses each time. You can't say the same about the memory address of the someValue itself, in your case it seems that the pointer someValue is created ... |
74,003,911 | 74,012,702 | c++ JSON serialize using reflection | Can someone modify given code so my commented code works. Actully I don't understand how reflect macro is working at first place.
#include <vector>
#include <string>
#include <iostream>
using namespace std;
#define REFLECT(x) template<class R> void reflect(R& r) { r x; }
typedef struct _Employee {
string emp_id;... | @TRT thanks for your explanation. I got following solution.
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
#define REFLECT(x) template<class R> void reflect(R& r) { r x; }
typedef struct _Employee {
string emp_id;
int salary;
REFLECT(
("Emp_id", em... |
74,004,012 | 74,004,719 | Inlined function to return nested array value not performing as expected | I want to inline the function MyClass:at(), but performance isn't as I expect.
MyClass.cpp
#include <algorithm>
#include <chrono>
#include <iostream>
#include <vector>
#include <string>
// Making this a lot shorter than in my actual program
std::vector<std::vector<int>> arrarr =
{
{ 1, 70, 54, 71, 83, 51, 54, 69,... | Member function directly defined in the class definition (typically in header files) are implicitly inlined so using inline is useless in this case. inline do not guarantee the function is inlined. It is just an hint for the compiler. The keyword is also an important during the link to avoid the multiple-definition iss... |
74,004,197 | 74,004,381 | Fedora: 'GLFW/glfw3.h: No such file or directory' | I am very new to C when trying to make some example code I get the error
basic.cc:18:10: fatal error: GLFW/glfw3.h: No such file or directory
On further inspection the contents of the Makefile are
# This Makefile assumes that you have GLFW libraries and headers installed on,
# which is commonly available through your ... | The linked glfw package contains the compiled shared library only, but for development you also need glfw-devel package which contains the headers.
but the its files are now in /usr/lib64/ where gcc does not see them
It should see them, but that comes at play later during linking, the Makefile correctly adds -lglfw s... |
74,004,359 | 74,004,563 | Pointers in C++ - value pointed by two pointers | I'm trying to understand an example provided in this tutorial.
// more pointers
#include <iostream>
using namespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue; // p1 = address of firstvalue
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; /... | *p2 = *p1; sets the value pointed to by p2 to the value pointed to by p1.
So in effect sets secondvalue to 10.
It doesn't appear to have any effect because the next two lines make p1 point to the same thing as p2 (secondvalue) and set the value there to 20.
The effect of the line in the question is overwritten.
Try thi... |
74,004,519 | 74,006,304 | Creating two outputs for two, two dimentional arrays, using two nested for loops? | Completely new to programming, i come from only excel experience so any help appreciated. The expressions calculate the altitude and bearing of the sun given your latitude, the hour of the day t and day of the year day.
The altitude calculation works fine, however the bearing calculation has sporadic nonsence negative ... | When I run your program with UndefinedBehaviorSanitizer active, I get a run-time error message in line 48 and 51 that you are converting a NaN to an integer, which invokes undefined behavior. This means that your calculatings are producing a NaN.
When I run your program line by line in a debugger, I notice that when li... |
74,004,622 | 74,005,456 | How to populate every row of two dimensional array C++ | I'm starting to learn C++ and C in context of embedded devices, and recently I started to make my own libraries, to clean up my code a little bit. I have a problem with passing two dimensional array to my function. The problem is as follows:
uint8_t cardSectors[8][16];
cardsClient.readDataBlocks(uid, uidLength, *cardSe... | In C++, it is probably easiest to
#include <vector>
template <class T>
using Arr2D = std::vector<std::vector<T>>;
and to pass this type around.
Since C is just barely above the level of an assembly language, lacking templates and other convenient concepts, one way to approach 2D arrays is to have a linear chunk of mem... |
74,005,197 | 74,005,253 | How to get a compiler error for assignments in an if statement? | Is it possible in Visual Studio to get a compiler error for an assignment in an if statement? How?
#include <iostream>
int main()
{
int a = 2;
if (a = 3) // Want a warning here
std::cout << "Avoid this!\n";
}
I know I can switch to Yoda conditions (if (3=a)), but I really don't want to.
I tried: setti... | You can turn any specific warning into an error, using the #pragma warning(error:nnnn) directive. In your case, the warning is:
warning C4706: assignment within conditional expression
So, adding the relevant #pragma directive to the code will generate a compiler error:
#include <iostream>
#pragma warning(error:4706)
... |
74,005,282 | 74,005,487 | C++ : unexpected behavior when incrementing a value from multiple threads | I'm currently learning about threads and my professor in class showed us this example attempting to demonstrate concurrency for threads
#include <iostream>
using namespace std;
void* threadHandler(void * val) {
long long* a = (long long *) val;
for (long long i = 0; i<100000; i++)
(*a)++;
... | pthread_t t1, t2;
Your professor is showing you historical POSIX thread API, that was mostly used in ancient times, back when dinosaurs roamed the Earth mostly armed with C (C++ has not been invented yet). Modern C++ uses std::threads to implement multiple execution threads. However, whether it's POSIX threads, or mod... |
74,005,470 | 74,005,594 | ID3D11RenderTargetView gets removed on ID3D11DeviceContext::OMSetRenderTargets() | I built a very simple, okay nothing, program that just clears the render target. Eventually when I call ID3D11DeviceContext::OMSetRenderTargets() the ID3D11RenderTargetView gets removed and I can't see why. My thought is somewhere at the creating of the IDXGISwapChain1 I specified something wrong.
Once:
UINT deviceFlag... | I assume that you are using Microsoft::WRL::ComPtr to manage m_pTarget. So when invoking m_pContext->OMSetRenderTargets(1u, &m_pTarget, nullptr); an overloaded operator & is being used rather than just taking an address of pointer to pass it as a pointer to first element of array containing a single pointer. Overloaded... |
74,006,203 | 74,006,245 | Why is my value converted from int to char? | #include<iostream>
#include<string>
class Person_t{
private:
uint8_t age;
public:
void introduce_myself(){
std::cout << "I am " << age << " yo" << std::endl;
}
Person_t()
: age{99}
{ };
};
int main(){
Person_t person1{};
person... | << age
age is a uint8_t, which is an alias for an underlying native type of a unsigned char. Your C++ library implements std::ostream's << overload for an unsigned char as a formatting operation for a single, lonely, character.
Simply cast it to an int.
<< static_cast<int>(age)
|
74,006,527 | 74,006,623 | slice container with O(1) constructor from iterable begin and end | I have a forward iterator. I want a simple iterable container which wraps it and exposes begin() and end().
I.E.
template <typename C>
void use_container(C c) {
std::cout << c.begin();
}
int main() {
std::vector<int> v {1,2,3,4,5,5};
auto begin_ = v.begin();
auto end_ = begin + 5;
use_container(/*create a container u... | C++20 added this with std::ranges::subrange. For example the following will call use_container with a range that is a view over part of v:
use_container(std::ranges::subrange{begin_, end_});
Demo
|
74,007,398 | 74,008,100 | After writing to a text file using c++ there are only some unreadable characters in that file | I wrote a program to write some integers to a text file using c++. But after running the code, there are only some unreadable characters inside the text file.
How do I fix it?
My code is as follows.
#include <iostream>
using namespace std;
int main(){
FILE *fp;
fp=fopen("my.txt","w");
for (int i =1; i<= 1... |
after running the code, there are only some unreadable characters inside the text file. How do I fix it? ... This is how it shows the text file after running the code
The problem is that you expect it to be a text file, but putw writes the ints to the file in binary format.
In order to get readable characters in a te... |
74,007,648 | 74,075,428 | How to call worker thread function from main thread in Emscripten app? | I need to access local fonts of browser in WASM/Emscripten program. I am able to to that using queryLocalFonts API from here https://wicg.github.io/local-font-access/
Now accessing and processing local fonts is taking too long I need to do it in worker thread. Calling the API from worker thread is not supported yet so ... | I have not used Emscripten's worker API. I can think of 2 other possibilities I can recommend. One is to load the wasm module in a worker OR use pthread and create a function to run in a separate worker internally through Emscripten's thread emulation.
Let's start with pthread support. You'd need the flags USE_PTHREADS... |
74,008,249 | 74,008,445 | Does division operator ( / ) in C++ return the floor value in case of num with same sign and ceil value when both the numbers are of opposite sign? | In C++ , when both numerator and denominator are integers and of same sign , then division operator gives the floor value of the quotient . But when they are of opposite sign , then it gives ceil value . Is my understanding correct or is there more to it ?
| You have it right. Some 20th-century hardware engineer decided to do it this way, and as far as I know this is how all microprocessors now natively do it. Mathematically, it's often a little inconvenient, which is why Python (for example) corrects in software always to round toward toward floor.
For additional insigh... |
74,008,493 | 74,008,751 | Multithreaded concurrent file reading/writing, managing container of processes | Wholly new to multithreading.
I am writing a program which takes as input a vector of objects and an integer for the number of threads to dedicate. The nature of the objects isn't important, only that each has several members that are file paths to large text files. Here's a simplified version:
// Not very important. R... | Given that the example you show is fairly simple, a for loop of fixed size, no strange dependencies, a very simple solution could be to use OpenMP which would allow you to do what you describe (providing I understood correctly) by adding a single line
void multi_file_proc(std::vector<OBJ> objs, int n) {
std::vector<s... |
74,008,646 | 74,008,995 | Is it a bad idea to acquire a lock in a destructor? | Say we have something along the lines of the following pseudocode, with the goal of achieving both concurrency and taking advantage of RAII:
class Foo {
public:
vector<int> nums;
mutex lock;
};
class Bar {
public:
Bar(Foo &foo) : m_foo(foo)
{
lock_guard<mutex>(foo.lock);
m_num = foo.nu... | There's nothing inherently wrong with locking a mutex in a destructor. For instance, shared resources might need to be made thread-safe. Releasing ownership of a shared resource, then, might require locking a mutex. If RAII just fell apart in multithreaded programming, it wouldn't be a very useful tool. Indeed, access ... |
74,008,941 | 74,009,871 | Conditionally passing ownership for members | Assume the following sketch:
struct C {
(either T or T&) m_t;
C(T& t):
(instantiate m_t as T& m_t(t))
{}
C(T&& t):
(instantiate m_t as T(t))
{}
};
such that a C either has or has not ownership of t, depending on how the C was constructed. Is that possible, possibly without resorting... | Something along these lines perhaps:
struct C {
std::optional<T> t_holder;
T& m_t;
C(T& t) : m_t(t) {}
C(T&& t) : t_holder(std::move(t)), m_t(*t_holder) {}
};
Would also need a copy and/or move constructor (the implicit one won't do the right thing); and the copy/move assignment operators would have to be dele... |
74,009,327 | 74,009,383 | How to free member variable malloc memory in a destructor | //Constructor
page_frames = (Page*) malloc(page_count*PAGE_SIZE);
for (uint32_t i = 0 ; i < page_count; ++i) {
page_frames = new Page[PAGE_SIZE];
page_frames++;
}
//Destructor
free(page_frames)
page_frames is a member variable of type Page*.
Whether I try to deallocate the memory in the ... | I'm assuming page_frames is a member variable declared as Page* page_frames in your class declaration. And you are attempting to create an "array of Pages"
This:
page_frames = (Page*) malloc(page_count*PAGE_SIZE);
for (uint32_t i = 0 ; i < page_count; ++i) {
page_frames = new Page[PAGE_SIZE];
page_frames++;
}
... |
74,009,492 | 74,009,748 | regular expression not evaluating string correctly | I'm trying to split a string based on space except when inside quotes. This is the regex I found online (\\w+|\".*?\"). However, when I try to use std::regex to split a string, I get only empty strings.
This is the code I have to split:
std::regex exp("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
std::sregex_token_iterator it... | From documentation for std::sregex_token_iterator:
submatch - the index of the submatch that should be returned. "0" represents the entire match, and "-1" represents the parts that are not matched (e.g, the stuff between matches).
Since you're passing -1, it means you're printing the parts that didn't match, not t... |
74,009,750 | 74,011,054 | My pulse duration calculation is inaccurate. Why? | I'm studying arduino. I generated pulse waves using arduino analog PWM output.
Mega pin No.4 -> 980Hz output => approximately 1000Hz => 1ms duration/pulse => 1000us
I used 50% duty cycle, so 500us pulse output.
I connected PWM output to digital input No.10 pin.
And here is my code. (for HIGH pulse duration)
int aoPin ... | Change where you call micros() the first time, so you know you do it at a rising edge:
unsigned long startMicros = 0;
analogWrite(aoPin, 128); // half duty cycle of 980Hz (arduino Mega pin No.4)
while (digitalRead(diPin)); // wait while input is high
while (!digitalRead(diPin)); // wait while input is low
st... |
74,010,128 | 74,010,201 | C++: Console outputting weird numbers when printing array | I'm beginning to learn about C++. I've been putting it off for a long time and I decided to start learning it.
Currently, I'm having trouble finding the issue with my program. My program is supposed to take integers from the input, insert it into an array, and then sort it. Everything is working correctly-- even the so... | I assume as selection sort algorithm.
/*Sorting program*/
using namespace std;
int *sortArray(int *array, int size) {
for (int i = 0; i < size; i++) {
int lowest = i;
for (int k = i; k < size; k++) {
if (array[k] < array[i] && array[k] < array[lowest]) {
cout << array[k] << " is less than "... |
74,010,238 | 74,010,587 | Qt::nativeEvent doesnt get called | Why does the nativeEvent function never get called?
// .h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
bool nativeEvent(const QByteArray& eventType, void* message, long*);
//privat... | The signature of QWidget::nativeEvent() is:
bool QWidget::nativeEvent(
const QByteArray &eventType, void *message, qintptr *result)
Thereby, qintptr is an
Integral type for representing pointers in a signed integer (useful for hashing, etc.).
Typedef for either qint32 or qint64. This type is guaranteed to be the sa... |
74,010,936 | 74,012,598 | How to convert R to C++ for Rcpp | The following R code chunk is very inefficient in terms of speed and I need it to be significantly faster as in the original problem the length(dt) is quite large.
Can you help me convert the following R code chunk to C++ in order to utilize RCPP function in R? My knowledge of C++ is very close to 0 and can't figure ou... | There are several errors in your C++ code, probably too many to list in a concise answer. However, the following corrections seem to follow your logic, and compiles to give similar answers to your R loop in less time:
Rcpp::cppFunction("
NumericVector cumyRes(double a, double b, double timedt, NumericVector dt,
... |
74,011,785 | 74,013,597 | QCommandLineParser --help and --help-all options are not translated | I have got this result when using https://doc.qt.io/qt-5/qcommandlineparser.html#addHelpOption:
Использование: ./build/Debug/client/myapp [параметры]
Параметры:
-h, --help Displays help on commandline options.
--help-all Displays help including Qt specific options.
-v, --version ... | The translation files (*.ts) are in Qt sources, so you need to install Qt framework with source files. The text you are referring to can be found in Src/qttranslations/translations/qtbase_ru.ts. It depends on the Qt version which you are using, but AFAIK it seems to be translated in the latest Qt 6.4. If it is not tran... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.