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,914,827 | 64,915,219 | Are C++20 new atomic_flag features supported in g++ / gcc? | According to cppreference, c++20 has rich (and, to me useful) support for atomic_flag operations.
However, it's not clear whether gcc yet supports these features, they're not anywhere to be found on gnu's feature summary. I'm currently using version 8, with -c++=2a set.
This code doesn't compile with GCC8:
#include <at... | atomic<bool> does everything atomic_flag does, just as efficiently on all normal C++ implementations. C++20 just added new stuff to atomic_flag to bring it up to the level of atomic<bool>. atomic_flag is guaranteed to be lock_free, but in practice on all platforms anyone cares about, so is atomic<bool>.
Don't expect ... |
64,914,885 | 64,915,041 | Generate same hash from strings in unpredicatable order C++ | I get in the input of my function list of strings.
But the order of these strings may be different for each function call.
I want to generate a hash from these strings, but it must be equal for two strings excluding order.
So, the hash of hello and world must be equal to the hash of world and hello.
The hash must be se... | You need to use any position independent hash either on bytes or use any hash on words and then use position independent hash on word's hashes.
Position independent hash can be any function that has same result when arguments are swapped: +, *, xor, etc.
|
64,915,291 | 64,915,605 | Is variable declaration cost neglectable on large scale? | I came accross a code written by my teacher :
int i;
for(i = 0; i < 10; i++){
//...
}
//...
for(i = 0; i < 10; i++){
//...
}
Instead, I would have written :
for(int i = 0; i < 10; i++){
//...
}
//...
for(int i = 0; i < 10; i++){
//...
}
With my way to write it the memory used to store the variable i i... | Do not wonder too much on how the compiler will translate your source code! Optimizing compilers could build the same machine code for both versions.
What matters is whether the code is readable and robust. This is the reason why best practices recommend to use the smaller possible scope for a variable. If you try to u... |
64,915,310 | 64,915,426 | Why got error, if not write '&' in the foreach loop? | I am just making some code for my program, but eventually I forgot to write a little symbol and got error, Please, help to understand what's wrong here.
The code I wanted to write -
int arr[3][2] = {with some values};
for(auto &i : arr) {
for(int j : i)
cout << j << " " ;
cout << endl;
}
The code I wro... | The element of arr is an array (int[2]). The problem is that if you declare i as non-reference, it'll be deduced as type int*, the array would decay to pointer and set to i during iteration. Pointers can't be used with range-based for loop. The error message from for(int j : i) is trying to tell you that there's no std... |
64,915,753 | 64,916,286 | If a function template has deduced return type, is there a way to call it without instantiating the definition? | Consider some function template such as:
template <class T>
const auto& foo() { static T t; return t; }
The definition would not be valid if T were to be void. Nonetheless, we are allowed to instantiate the declaration alone without triggering an error:
extern template const auto& foo<void>(); // explicit instantiati... |
What provision of the Standard requires the instantiation of the definition of foo<void> in this situation?
Albeit non-normative, the note in [dcl.spec.auto]/11 does mention that any use of a specialization (of a function template with a placeholder in its declared return type) will cause an implicit instantiation [e... |
64,916,103 | 64,916,138 | Why doesn't the value of my variable change even though I passed by reference | #include <iostream>
char toupper(char& letter){
switch(letter){
case 'a':
return 'A';
break;
case 'b':
return 'B';
break;
case 'c':
return 'C';
break;
default:
return letter;
}
}
int main()
... | You do indeed pass labRat by reference to the function, but you don't change the value of letter (which refers to labRat in the caller) in toupper.
It's not to everyone's taste1, but code like
return letter = 'A';
is one way of returning the value as well as setting the reference value. The assignment expression lette... |
64,916,486 | 64,930,941 | Entry Point Not Found - VS2019 OpenCV C++ | I'm using C++ through Visual Studio 2019. I was running my compiled *.exe files with no problems until I did a mistake reinstalling CUDA and insight, and then repairing Visual Studio.
Although there is no problem with the build, I'm now constantly getting the following error:
I uninstalled Visual Studio 2019, CUDA, an... | The error message in the picture usually means there is a dll conflict between the import library you linked to and the dll that was found when windows searched for the matching dll. One such place windows searches is all the folders of the PATH environment variable.
It was mentioned in the comments that you attempted ... |
64,916,896 | 64,917,185 | How to properly clean Vulkan objects? | Do VkObjects need to be nulled, or is it solved somehow in automatic way?
For example when I have Buffer class which is wrapper for
VkBuffer _buffer;
and destructor like this:
Buffer::~Buffer()
{
vkDestroyBuffer(_device.getLogicalDevice(), _buffer, nullptr);
if(_memory) {
vkFreeMemory(_device.getLogicalDevic... | When you have (properly) destroyed a Vulkan object, it is destroyed. That's the end of it. It's no different from destroying an object in C++ through its pointer: the object being pointed to is gone.
What you do with the pointer value itself is up to you (outside of passing its value as input to Vulkan APIs, which of c... |
64,917,288 | 64,917,446 | How to write multi-byte values to shared memory in C++14? | Assume that I have two processes that both share a memory block using shm_open and mmap and there exists a shared synchronization primitive - let's say a semaphore - that ensures exclusive access to the memory. I.e. no race conditions.
My understanding is that the pointer returned from mmap must still be marked as vola... |
My understanding is that the pointer returned from mmap must still be marked as volatile to prevent cached reads.
Your understanding is wrong. Don't use volatile for controlling memory visibility - that isn't what it is for. It will either be unnecessarily expensive, or insufficiently strict, or both.
Consider, for e... |
64,917,707 | 64,923,202 | Does an explicit instantiation declaration of a member function of a class template cause instantiation of the class template? | [dcl.spec.auto]/14 states [emphasis mine]:
An explicit instantiation declaration does not cause the instantiation of an entity declared using a placeholder type, but it also does not prevent that entity from being instantiated as needed to determine its type. [ Example:
template <typename T> auto f(T t) { return t; }
... | The argument that the class template must be instantiated is that declaration matching may need to know things about the class that plainly require instantiation. Consider the simplified example
template<class T>
struct A {void f(T) {}};
extern template void A<int>::f(int);
To know whether the member function exists... |
64,918,005 | 64,918,069 | Why can't I access inherited protected fields in a derived constructor's member initialization list? | I'm new to OOP. I recently learned some things about Inheritence in C++, and that a protected field can't be accessed from outside of the class, but it can be accessed in inherited classes. I have some problems with my code and I don't understand what is wrong:
class Base
{
protected:
int x;
int y;
int z;
p... | You can access them in Derived, but they are members of Base and cannot be initialized directly in the member initialization list of Derived. This also wouldn't work if they were public. Note that the Base class is initialized before the members of Derived are initialized.
To initialize the base, you can call its const... |
64,918,985 | 64,919,221 | First array elements lost in loop C++ | I'm facing a weird behavior. I process some data in a loop, then if it meets certain criteria, I put the values into an array, but since I don't know the size of the data meeting the criteria, my declaration is double arr[][4] = {0} (if not initialized, I receive an error).
With test data, I know the size must be 1852 ... | C++ arrays do not grow dynamically. You are going out of bounds of your array, which causes undefined behavior.
When you don't know up front how many elements you are dealing with, use a std::vector instead. In this case, I would say to use a vector of struct elements instead, since you are storing 4 double values pe... |
64,919,255 | 64,919,559 | Is passing arguments related by conversion to a template function call that uses template argument deduction bad thing? | AFAIK overloading a function for types that are relative by conversion or a function call that needs some cast applied to the argument to match a best a match are of bad design.
void foo(int)
{
std::cout << "foo(int)\n";
}
void foo(float)
{
std::cout << "foo(float)\n";
}
int main()
{
foo(5.3);// ambiguou... |
Or the problem is in the language itself? Because the compiler generates versions that can be relative by conversion?
Okay, they are related by conversion. Now which one should the compiler generate? What deterministic algorithm do you propose it employ to choose the best function to instantiate? Should it parse the ... |
64,919,408 | 64,959,157 | Asynchronous C++ library for python | I'm struggling with something that hopefuly someone here will be able to guide me through please.
I have an asynchronous python code(asyncio), and I wrote simple asynchronous client in C++ that is very similiar to this one: https://www.boost.org/doc/libs/1_74_0/doc/html/boost_asio/example/cpp03/timeouts/async_tcp_clien... | To make start_client not block the event loop, you need to release the GIL, and also hand it off to a thread pool (executor) managed by asyncio for that purpose:
async def client():
loop = asyncio.get_event_loop()
await loop.run_in_executor(
None, async_client.start_client, '0.0.0.0', '3000'
)
Idea... |
64,919,567 | 64,919,601 | Assigning Values to unsigned short* buffer | I am having issues assigning value to unsigned short* and unsigned char* buffers. The code looks something like this:
// Header File
unsigned short* short_buff;
unsigned char* char_buff;
// Implementation File
short_buff = new unsigned short[10];
memset(&short_buff, 0, 10);
char_buff = new unsigned char[10];
memset(&... | memset(short_buff, 0, 10*sizeof(short));
and
memset(char_buff, 0, 10*sizeof(char));
Two mistakes, & is wrong, you should pass the value of the pointer to memset not the address of the pointer variable. (This version memset(&short_buffer[0], ...); also works).
Secondly memset counts bytes not elements, so you need to ... |
64,920,265 | 64,920,284 | error: cannot bind non-const lvalue reference of type ‘Position&’ to an rvalue of type ‘Position’ | When I try to compile my program, my Race.cc file has an error.
error: cannot bind non-const lvalue reference of type ‘Position&’ to an rvalue of type ‘Position’
view.update(tortoise->getCurrPos(), tortoise->getCurrPos(), tortoise->getAvatar());
~~~~~~~~~~~~~~~~~~~~^~
I'm struggling to figure out how to... | Your update() is looking to take a Position by reference so that it can make modifications and have them percolate back to the object you're passing. However, tortoise->getCurrPos() returns a Position copy. If you want the changes in update() to affect your tortoise's Position member, you'll need to have getCurrPos() r... |
64,920,333 | 64,920,411 | Why the compiler cannot deduce the template arguments from std::make_shared? | I have this simple question from an exercise in "C++ primer, 5th ed":
Exercise 16.38: When we call make_shared (§ 12.1.1, p. 451), we have to provide an explicit template argument. Explain why that argument is needed and how it is used.
I've tried, then I've seen some answers and suggestions, but I'm not convinced ye... | For most variants of std::make_shared which return a std::shared_ptr<T> or std::shared_ptr<U[]> - no parameter has type T. Examples:
template< class T, class... Args >
shared_ptr<T> make_shared( Args&&... args );
template<class T>
shared_ptr<T> make_shared( std::size_t N );
(where in the latter example, T must be U[] ... |
64,920,530 | 64,920,585 | How to template a function with a mix of non-type template parameters and type template parameters? | Minimal Reproducible Example
#include <unordered_map>
#include <string>
template<class T, bool did_work>
class Test {
Test(T input) : field(input), success(did_work) {}
T field;
bool success;
};
template<typename A>
void func(std::unordered_map<std::string, Test<A, bool>> input1, A input2) {}
int main() ... | With template<class T, bool did_work> did_work is a non-type template parameter. What that means is that instead of passing a type to it, it takes a value. Since it needs a value, you make a Test like Test<A, true> or Test<A, false>, not Test<A, bool>.
For your function you can just add a non-type template parameter ... |
64,921,055 | 64,921,668 | How to change the hue of a part of a scene? | I have a rather complex QGraphicsScene with a bunch of lines. I want a very specific zone to have a different hue. For instance, a blue line passing through this zone would be displayed as red inside the zone, but remain blue outside.
Naturally, it would be possible to just draw three lines instead of one, but this req... | Solution
My approach to the problem would be to:
Subclass QGraphicsRectItem if the zone should be rectangular and reimplement its paint method
Set the composition mode of QPainter to an appropriate value, e.g. QPainter::RasterOp_SourceAndNotDestination:
painter->setCompositionMode(QPainter::RasterOp_SourceAndNotDest... |
64,921,466 | 64,921,517 | Is it possible to emplace a std::array in a container? If it is how? If not, why? | Given the simple code
#include <array>
#include <vector>
int main() {
std::vector<std::array<int,3>> v;
v.emplace_back(std::array<int,3>{1,2,3});
}
I'm first of all worried about what is really going on.
My understanding of emplace_back is that it constructs an element (in this case an std::array<int,3> with v... | Let me try to clarify a bit. First of, std::array<> is an aggregate. It does not have any user-defined constructors at all.
So it is quasi-movable (technical term is trivially movable), meaning you can construct it from temporary, but it is going to simply copy the underlying array. So what the code ends up doing is co... |
64,921,488 | 64,921,626 | Can I avoid a downcast here? | I am working on a suite of code for numerical PDEs. Previously we had separate codes for problems in different dimensions, and many classes of objects that make up a mesh, e.g. Cell, Face, Edge, Vertex. I am trying to write a dimension independent code, and trying to write a base class that contains information for all... | This
Vertex(..., size_t base_dimension)
: MeshObject(..., base_dimension, 0) {}
is not a downcast. It's just normal base class initialization. So, you want to make Vertex an alias for a zero-dimensional mesh, without having to write all the boilerplate?
You could write
template <size_t Dim>
class FixedDimensionMesh... |
64,922,092 | 64,922,199 | Win32Api Window Menu Activating issue | Running my program it runs and due to me having a menu with EXIT to Destroy the window it runs and immediately exits the window. Unsure how to fix my issue here on compiling the program to have it not run the WindowProcedure function and passing the argument EXITMENU resulting in the Window being destroyed.
*.CPP
#incl... | You are not handling the menu commands correctly in your WindowProcedure().
You have defined EXITMENU as 3, which is the same value as the WM_MOVE message. So, in your switch, you are destroying your window as soon as it receives a WM_MOVE message during window creation.
You need to instead handle the menu commands vi... |
64,922,379 | 64,922,990 | Inserting values into map with pair - error: expected primary-expression before ‘,’ token | I'm a little new to maps (and c programming in general) and am trying to insert some values into a map that takes a string as a key, and a paired <double,double> as the corresponding values.
When I try and compile the code, I am presented with the error:
error: expected primary-expression before ‘,’ token
values.inse... | Solution:
values.insert(make_pair("test",make_pair(0.12312312, 0.56756756)));
cout << values.size() << endl;
for(map<string, pair<double,double> >::const_iterator it = radar_values.begin(); it != values.end(); it++)
{
cout << it->first << endl;
cout << it->second.first << endl;
cou... |
64,922,793 | 64,924,781 | How can I get a more accurate result when dividing numbers in C++ | I am trying to estimate PI using C++ as a fun math project. I've run into an issues where I can only get it as precise as 6 decimal places.
I have tried using a float instead of a double but found the same result.
My code works by summing all the results of 1/n^2 where n=1 through to a defined limit. It then multiplies... | So even with long double as the floating point type used for this, there's some subtlety required because adding two long doubles of substantially different order of magnitudes can cause precision loss. See here for a discussion in Java but I believe it to be basically the same behavior in C++.
Code I used:
#include <i... |
64,923,343 | 64,923,560 | Why is std::pow(int, int) way faster than for loop with integer values? | Me and my friend wrote a program which calculates the polynomial:
P = abn + a2bn-1 + a3bn-2 + ... anb
He used the C++ std::pow(int, int) function, whereas I used two for loops as I've been taught that for loops with integers are faster than the std::pow(int, int) function or in worst case the speed is gonna be almost t... | It completely depends on the quality of std::pow implementation, and the optimization capability of your compiler
For example some standard libraries calculate pow(x, y) as exp(log(x)*y) even for integer exponents, therefor it may be inaccurate and slow, resulting in issues like these
Why does pow(5,2) become 24?
Why ... |
64,923,757 | 64,938,332 | How do I get the static versions of the modules? | I'm working on a game in SFML. It runs correctly on my computer, but if I send it to another computer then when I try to run it I get errors about not being able to find libraries. I did some research and I found that the reason is because I was using dynamic libraries, and to get the program to work on its own I need ... | I am sure you are using mingw compiler. You can add static arguments and try.
-static-libgcc -static-libstdc++
If this doesn't work try to search the two DLL files in your standard compiler path /bin folder and place them where your exe is located.
|
64,923,963 | 64,924,156 | Dynamic Arrays: Trying to properly expand the dynamic array and am trying to return a not NULL value from function |
I am trying to read the return value of the pointer_new_values variable.
The Dynamic Array's elements double once the array reaches it's max capacity using the growArray function.
#include <iostream>
//Using the returnValue variable in order to be able to see the return value of pointer_new_values.
int returnValue;... | There are couple of issues with your code,
Even though array is expanded size is not updated
All the elements are added to the index zero of the array
In function growArray expanded array size has to be returned, no statements are executed after encountering of return
delete[] has to be used inorder to release memory ... |
64,924,570 | 64,969,001 | How to prevent QListView from calling sizeHint of each item? | I have a QListView with a lot of items that are of various heights. I implement a custom delegate for painting items and set layout mode to Batched.
However, when the model is assigned, the list view requests sizeHint for every item in the model upfront, ignoring the Batched setting and thus ruining the performance bec... | Well it seems that I've found a solution, so I'll share it here for sake of anyone who has the same problem and googles this thread.
First of all, I've found that this is actually a bug in Qt registered back in 2011 and still open:
https://bugreports.qt.io/browse/QTBUG-16592
I've added my vote to it (and you should, to... |
64,924,677 | 64,924,974 | How to iterate over vector of shared pointers to a Class | I have a class:
class Company {
public:
int floors;
std::set<std::string> managers;
};
And another class which has the following:
class Another {
std::vector<std::shared_ptr<Company>> comp;
}
If I have this function which needs to find if any of the managers have the name in any of the Company cla... | bool Another::look_for(std::string name)
{
for (auto &c : comp) {
if (c->managers.find(name) != c->managers.end())
return true;
}
return false;
}
Alternatively:
#include <algorithm>
bool Another::look_for(std::string name)
{
return std::find_if(
comp.begin(), comp.end(),
... |
64,925,807 | 64,926,252 | How can I overload [] operator in C++ for a function of two args? | I have a class Priority Queue with method push() which takes two args: value and priority.
#include <vector>
#include <iostream>
class PriorityQueue
{
private:
std::vector<std::pair<int, int>> _queue;
public:
int top();
int pop();
void push(int, int);
int size();
PriorityQueue();
PriorityQ... | You have to return type which will do the push on operator=, something like:
class PriorityQueue
{
private:
std::vector<std::pair<int, int>> _queue;
struct Proxy
{
PriorityQueue* queue;
int priority;
Proxy& operator=(int value) { queue->push(priority, value); return *this; }
};... |
64,925,899 | 64,926,113 | poco library, static linking (MT) | I need to compile my program in Multi thread( run time ), and i've installed poco library for static mode and dll using vcpkg, and i've already added :
<PropertyGroup Label="Globals">
...
<VcpkgTriplet Condition="'$(Platform)'=='Win32'">x86-windows-static</VcpkgTriplet>
<VcpkgTriplet Condition="'$(Platform)'=='x64'"... | I finally figured out, How to solve this problem, after 3 days, we need to add crypt32.lib and ws2_32.lib to linker / additional dependencies.
I hope this helps someone in a similar circumstance :)
|
64,926,838 | 64,939,035 | Gnuplot and std::filesystem::remove | I'm trying to use gnuplot from C++ application, gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04). I've encountered strange behavior concerning plotting to files.
So, the reproducible example is:
#include <iostream>
#include <filesystem>
int main()
{
// whatever valid filename
std::string name1 = "/tmp/1.png";
... |
Why the std::filesystem::remove acts this strange?
You seem to misunderstand the return value and the error code (ec in your code) of std::filesystem::remove(). The function does not raise an error if the file you are trying to remove does not exist (ec will be zero). Only the function without error_code& returns fal... |
64,926,976 | 64,927,557 | What is the correct way to display widgets without calling QApplication::exec()? | For test purposes I'd like to create and display a widget. For now I only need the widget to render correctly but in the future I may want to extend this so I simulate various events to see how the widget behaves.
From various sources it would appear that the following should work:
QApplication app;
QPushButton button... | To test Qt GUI application you need at least QApplication instance and event loop being processed. The fastest way is just use QTEST_MAIN macro, this answer explains in a nice way what it does exactly. However, to have more flexibility (e.g. to use GTest, GMock) you can also simply create QAplication instance in your t... |
64,926,987 | 64,927,238 | Removing smart pointers | I'm testing some code examples for a CLR project. What would be this code equivalent without using smart pointers?
Microsoft::WRL::ComPtr<ID3D11Device1> m_d3dDevice;
Microsoft::WRL::ComPtr<IDXGIDevice1> dxgiDevice;
...
m_d3dDevice.As(&dxgiDevice);
I tried something like this, but I'm not sure if it's ok.
ID3D11Device1... | These are COM object pointers.
I am not sure why you would not want to use a COM smart pointer template class. They eliminate most reference counting issues that can drive you crazy. And they have almost zero overhead.
As such, you can use the ComPtr class or the legacy CComPtr from ATL as your smart ptr template typ... |
64,927,604 | 64,927,891 | How to resolve the segmentation fault in this code? | I am trying to make an infix calculator for which I am currently trying to convert numbers entered in a character array to double.
here's my code:
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
char exp[500];
const int SIZE = 100;
char temp[SIZE];
char op;
int strLen = 0, k... | This line for (int m = 0; exp[m] != ','; m++) //stopped working will always fail if there are no , characters since exp[m] != ',' will always be equal to true and so will reach beyond the end of the array of exp which triggers the "segmentation fault".
|
64,927,649 | 65,004,536 | C++ multithreading closes TCP connection | I work on a C++ server where I wait for an network connection. If I get one I put the socket into a new thread and listen for further inputs. But the problem is that as soon as I have the socket in a new thread the TCP connection is disconnected. I'm using the SFML library.
Here's some code:
main.cpp:
int main() {
... | This is something built on your current threaded code. It may be a good idea to use a single threaded design and use the sf::SocketSelector to wait for events on the listener and all the connected clients instead.
In this lazy solution disconnected clients will not be removed from the servers list of clients until a ne... |
64,927,686 | 64,930,400 | Issue linking against POCO::Net::SocketAddress | I'm working on an Android native project where I'm using NDK + CMake to build a native solution based on POCO C++. I'm getting a super weird link error when I comment this line in my cpp file:
//std::ostream& o = session.sendRequest(request);
this is the link error:
../NetSSL_OpenSSL/src/SecureSocketImpl.cpp:381: erro... | You need to recreate the inter-library dependencies such that CMake can construct the correct linker command line with dependencies after the libraries that depend on them.
Running through the libraries you listed, that should be at least the following (reconstructed from the Poco CMakeLists.txt).
target_link_libraries... |
64,928,085 | 64,928,270 | unique_ptr with virtual classes | Its probably something really dumb, but I do not understand the g++ output I am getting. I am trying to hold a pointer to a derived object to a virtual base class. When I run the commented code, it works fine and as expected, holding it in the unique_ptr does not compile.
Error message:
In file included from /usr/inclu... | As mentioned in the comments, the argument(s) to std::make_unique should be those required by the constructor of the created object. In your case, this would be an empty argument list (the derived constructor needs no argument). Further, you cannot create a unique_ptr object to your virtual base class; instead, that sh... |
64,928,088 | 64,928,246 | C++ Generic component system | I am trying to implement Entity-Components like in Unity3D in C++. What I would like to do is something that can be easily achieved in C#:
public T GetComponent<T>() where T : Component
{
foreach (Component component in _components)
{
if (component is T)
return component ... | dynamic_cast requires that the expression being casted, and the type being casted to, are pointers (or references).
You can't use dynamic_cast without using either pointers or references.
So the solution is probably:
if (dynamic_cast<T*>(component) != nullptr)
|
64,928,107 | 64,938,996 | Why gdb complain to me that No Source Available (with g++ -ggdb3) | For some reason I reinstalled my OS(manjaro linux) yesterday, and installed gcc and gdb by pacman, then I write a very small example program to make sure my environment is correct, because I am a beginner in linux and gdb. After compile,it went according to my expectations. Then I wanted to take a look at the STL sourc... |
Why gdb complain to me that No Source Available (with g++ -ggdb3)
Because you are stopped inside libstdc++, which was built in a temporary directory (here /build/gcc/src/gcc-build/...) and that directory is not present on your machine.
It is exceedingly unlikely that you actually need to look at the source of operato... |
64,928,386 | 64,929,951 | std::tie for less comparison and char arrays | I've always known that to implement in a fast way a operator< for a class, the fastest way that always works is to use std::tie.
E.g.
struct TestInt
{
int a = 0;
int b = 0;
};
TestInt first;
TestInt second(first);
bool aLess = std::tie( first.a, first.b)
< std::tie(second.a, second.b);
bool bLess = std::tie( first.... | You might mimic std::tie with special case for C-arrays, something along
template <typename T>
struct my_ref
{
using type = T&;
};
template <typename T, std::size_t N>
struct my_ref<T[N]>
{
using type = my_span<T/*, N*/>; // std::span doesn't provide comparison operators
};
template <typename T>
using my_ref_... |
64,928,418 | 65,418,780 | ARM Cortex M0+ __set_MSP C++17 compiler warning | I do have a working code for jumping from bootloader to application.
But now since C++17 the implementation for setting the Master Stack Pointer __set_MSP raises a compiler warning.
Code:
__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack)
{
__ASM volatile ("MSR msp, %0\n" : : "... | The clobber informs the compiler that the values of some registers are changed by the assembly statement, in addition to the input and output registers, so the compiler can create instructions to save and recover the values of those registers by pushing and popping from the stack.
Importantly GCC expects the SP to rema... |
64,928,586 | 64,928,764 | Replace references storage with std::shared_ptr and std::weak_ptr | I have a simple case where I know things can go wrong if I start to use threads. Godbolt here
#include <iostream>
#include <memory>
class team;
class member
{
public:
member(team& my_team) : my_team(my_team) {
std::cout << "ctor" << std::endl;
}
~member(){
std::cout << "dtor" << std::... | This example won't break if you add threads (well, no more than any other solution). As long as you protect access to team correctly, it will be fine.
Changing reference to std::shared_ptr/std::weak_ptr would be problematic. You will need some sort of initialize() function in team, which will be called manually after i... |
64,929,303 | 64,930,231 | condition_variable wait_for in C++ | I am working with condition_variable on Visual studio 2019. The condition_variable.wait_for() function returns std::cv_status::no_timeout without any notification.
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
std::condition_variable cv;
std::mutex mtx;
bool called = false;
void printThread... | Yes, it's a "spurious wakeup". This is explained on cppreference.com's reference page for wait_for:
It may also be unblocked spuriously. When unblocked, regardless of the
reason, lock is reacquired and wait_for() exits.
Translation: there are gremlins in your computer. They get grumpy, occasionally. And if they do ge... |
64,930,570 | 64,942,188 | How to compile for multiple versions of windows where Kernel32 entry point may not exist for some functions | The title may not be the most descriptive at first:
I have a program that utilizes a call to "Wow64EnableWow64FsRedirection" function which is required when the software runs on a Windows 7 and Windows 10 64-bit platform.
However, the same application must also be able to run on a 32-bit Windows XP platform. The proble... | Try hModule = LoadLibrary("kernel32.dll") and func = GetProcAddress(hModule, "Wow64DisableWow64FsRedirection") if header file is not available for specific platforms.
|
64,930,844 | 64,932,251 | Time recquired for OpenCL kernel deletion | I'm encountering an unexpected performance with my OpenCL code (more precisely, I use boost::compute 1.67.0). For now, I just want to add each elements of 2 buffers c[i] = a[i] + b[i].
I noticed some speed reduction in comparison of an existing SIMD implementation so I isolated each step to highlight which one is time ... | I'll point out that I've never used boost::compute, but it looks like it's a fairly thin wrapper over OpenCL, so the following should be correct:
Enqueueing the kernel does not wait for it to complete. The enqueue function returns an event, which you can then wait for, or you can wait for all tasks enqueued onto the qu... |
64,930,876 | 64,931,010 | CUDA is it possible to have out-of-bound access that results in no error? | So I've met a very strange behavior in CUDA.
I have multiple arrays on GPU, let's say one is float a[100];
I have a function that looks like the following:
float access(int i) {
if (i >= 100) printf("i is out of bound\n");
if (i+blockDim.x >= 100) printf("i+blockDim.x is out of bound\n");
return a[i] + a[i ... | Accessing an array just slightly out-of-bounds generally will not result in an obvious runtime error (although your code may still compute things incorrectly). The GPU runtime mechanisms do not test access validity down to the byte level.
If you make the access far enough out of bounds, you will eventually hit a runti... |
64,931,136 | 64,988,909 | CLion IDE (CMake): Project builds but no intelligence for external libraries | I've implemented the GLFW basic example.
The GLFW header file is reported as not being found and such the CLion IDE is reporting and error and not providing intellisense however the project correctly compiles and runs.
I've added the GLFW library as per the guidance in their documentation (See CMakeLists.txt).
The proj... | For anyone encountering this issue call Tools | Resync with Remote Hosts -
|
64,931,337 | 65,024,762 | How to read more than one line of input? | So I have built a small basic data encrypter (for learning purposes only). It is working perfectly fine but it reads only a single line of input. Is it my Editor problem or my code have some issues.
ps: I use CodeBlocks
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
std::string str;
... | You can do as
#include <iostream>
using namespace std;
int main() {
string str;
while (getline(cin, str)) {
cout << str << endl;
}
return 0;
}
|
64,931,610 | 65,034,564 | Embedding files in an iOS app (C++/Qt/cmake) | In an iOS c++/Qt application, I need to ship a few files and to keep them in their directory structure.
For the Android version, we bundle a zip which we unzip on the target before creating the QApplication.
On iOS, it seems that CMake is not capable of bundling files in a tree:
https://cmake.org/cmake/help/latest/prop... | So apparently the CMake method also works for directories.
target_sources(${QT_IOS_TARGET} PRIVATE ${_resource})
set_source_files_properties(${_resource} PROPERTIES MACOSX_PACKAGE_LOCATION Resources)
It will just be added at the root directory of the bundle and not within the Resources.
|
64,931,785 | 64,932,681 | Static variable that stores minimum number | I'm new to C++ so this might seem a little too easy but I can't figure it out.
I'm supposed to create a static member variable that stores the minimum age of any person object defined using this class.
Do I need to write the code in the default construct or in a static member function.
Also, can someone help me with ... | You can add following line in your constructor:
if (age2 < minAge || minAge == 0)
{
minAge = age2;
}
and I guess it would solve your problem.
you can also write a static member function with above code into it and call that function your constructor.
One thing I just want to highlig... |
64,931,885 | 64,935,273 | Windows 10 - emulating directory path | I have Windows 10 with the one partition - C. I would like to run the c++ application which has hardcoded paths to some directories on partition D (it fails when I run it from the partition C). Is it possible to deceive somehow that application ? I don't want to create a "physical" partition D.
| You can use the command-line SUBST command to create a drive letter D: that points to any existing folder within the C: drive.
|
64,932,083 | 64,936,650 | C++ auto deduce type of template member pointer | I have this code:
struct Test {
std::string s;
};
template <typename T,
auto T::* groupPtr>
struct Base{
using BaseType = typename std::decay<decltype(std::declval<T>().*groupPtr)>::type;
void Process(const Test * e){
printf("%s\n", e->s.c_str());
... | It seems c++ forgot to include auto deduction for member pointers in TMP. I have tried with c++20 and failed. This is a big issue. But we can have a workaround for the same as in the following.
Consindering your code should work but doesn't due to 'c++ limitations'. We will only modify a bit of it. Do as follows.
stru... |
64,932,109 | 64,932,690 | Remove space from last number in C++ | I trying to write a program about reconstruct a binary search tree from inorder and preorder traversal, then output the tree into postorder , I need to remove blank space after the last element from my tree is printed, but I not really sure how to do it.
My postorder code:
void postorder(Node* root)
{
if (root... | bool postorder(Node* root)
{
if (!root) {
return false;
}
if (postorder(root->left))
cout << " ";
if (postorder(root->right))
cout << " ";
return (cout << root->data);
}
|
64,932,290 | 64,932,326 | How to construct an object from a tuple when it does not have any constructor | If I have a class which has a defined constructor:
class Point
{
public:
Point(int x, int y);
// ...
};
And a std::tuple:
using Tuple = std::tuple<int,int>;
I can construct the class using the tuple by calling std::make_from_tuple:
void f()
{
Tuple tuple = {1,2};
auto point = std::make_from_tuple<Poin... | You can use std::apply to call from_coordinates with a std::tuple. That would look like
auto point = std::apply(Point::from_coordinates, tuple);
|
64,932,339 | 64,932,467 | Can't use "const reference of a function object" in a function parameter | I'm learning function objects, and I'm trying this by writing std::transform myself. I created an Increment struct. I will create an object from this struct and use it as a function object in the parameters of my transform function.
This is my Increment struct:
template<typename T>
struct Increment
{
T by_what;
... | Your compiler does quite a good job at explaining the issue:
candidate function not viable: 'this' argument has type 'const Increment', but method is not marked const
const object can only use const member functions. Change your functions to
template<typename T>
struct Increment
{
T by_what;
void increment(T&... |
64,932,518 | 64,933,038 | ffmpeg Get Audio Samples in a specific AVSampleFormat from AVFrame | I am looking at the example from ffmpeg docs:
Here
static int output_audio_frame(AVFrame *frame)
{
size_t unpadded_linesize = frame->nb_samples * av_get_bytes_per_sample(frame->format);
printf("audio_frame n:%d nb_samples:%d pts:%s\n",
audio_frame_count++, frame->nb_samples,
av_ts2timestr(... |
Encoding audio Example
Resampling audio Example
Transcoding Example
If you don't get the desired format from the decoder, you have to resample it, encode with AV_SAMPLE_FMT_FLT.
According to enum AVSampleFormat
The floating-point formats are based on full volume being in the range [-1.0, 1.0]. Any values outside thi... |
64,932,579 | 64,934,093 | Why C++20 format has no strong typedef for format string? | C++20 introduces the following format function (locale and wstring_view versions ignored since they do not affect the question):
template<class... Args>
std::string format(std::string_view fmt, const Args&... args);
There is nothing wrong with this, but I wonder why is there not an overload that accepts a "strong type... | The point of strong typedefs is to prevent this from working:
void takes_id(SomeIdType);
takes_id(42);
The point of format is to allow this to work:
format("User {} owes me {} points.", name, 100);
That is a string literal. Requiring a strong type means more burden on the users, having to write something like this:
... |
64,932,996 | 64,933,632 | ld tool can find the library but mingw cannot (linux) | Right now, I am trying to compile some C++ code that uses both PoDoFo and Magick++ (part of ImageMagick) using MinGW on linux. I'm using MinGW so I can compile for Windows. When I try to compile, I get this error:
/usr/lib/gcc/x86_64-w64-mingw32/10.2.0/../../../../x86_64-w64-mingw32/bin/ld: cannot find -lpodofo
Howeve... | Your ld find the library because it was compiled for linux which use elf64-x86-64 format. It is not compatible with mingw which will need libraries in pei format (probably pei-x86-64 format).
In order to use this library you need to find the mingw version of the library or cross compile it yourself.
|
64,933,023 | 64,940,474 | C++ not run an output properly | This is a clip of my code
void start_hang(){
cout << "*********************\n";
cout << " \n";
cout << " \n";
cout << " \n";
cout << " \n";
cout << " ... | The code is correct and there's no issue with it. The issue lies in the way you're compiling and executing.
On UNIX-like systems, the default name for the output binary from gcc is a.out (which is also an ancient executable format)
-o file
Place the primary output in file file. This applies to whatever sort of outpu... |
64,933,266 | 64,933,422 | Converting a hexadecimal number represented in ASCII characters to a decimal integer in C/C++ | my problem is as follows.
I'm reading a piece of ascii data from a sensor, let's say it's "400". It's stored in an array of characters. In hex (ascii) that would be { 0x34, 0x30, 0x30 }.
What I'm trying to get from that set of characters is an integer in decimal representative of hex 0x400, which would be 1024. All the... | As Eugene has suggested, all you need to do is replace atoi(radar_block) by strtol(radar_block, NULL, 16). That takes a "base" argument, which can be 10 for decimal, 16 for hex (which is what you want), etc or 0 to auto-detect using the C++ rules (leading "0x" for hex, leading "0" for octal).
You should never use atoi... |
64,933,429 | 64,933,558 | Delete pointers in a vector | Is this a right way of deleting pointers in a vector? Is it ok to use indices instead of itertors?
std::vector<int*> stuff;
int *a = new int(10);
int *b = new int(20);
int *c = new int(30);
stuff.push_back(a);
stuff.push_back(b);
stuff.push_back(c);
for (int i = 0; i < stuff.size(); i... |
Is this a right way of deleting pointers in a vector?
Your code performs as you expect it to (and the memory is deleted correctly).
Is it ok to use indices instead of itertors?
Yes.
That said, using iterators for accessing vector elements was added to the language to avoid indexing errors (which are some of the mos... |
64,933,487 | 64,945,206 | Why does CLion's integrated CMake fail to find installed packages? | I have a C++ project described by a CMakeLists.txt file from which CMake successfully generates a MAKE file if I call CMake from the terminal. (This is on Ubuntu.)
The project has dependencies on Boost and Eigen which are both installed on my system. I can see the Boost includes in /usr/include/boost, Boost binaries in... | Actually this behavior seems to have been a result of installing CLion as a flatpak package. I uninstalled and reinstalled as normal binaries and the problem goes away. (new to Linux here...)
This is the same issue as described here: Jetbrains YouTrack. The take away seems to be do not install JetBrains products via Fl... |
64,933,727 | 64,933,906 | c++ function to merge bytes of 2 values | I want to be able to merge bytes from two unsigned long parameters, taking exactly half of the bytes, the half that starts with the least significant byte of the second param and the rest of the first param.
For example:
x = 0x89ABCDEF12893456
y = 0x76543210ABCDEF19
result_merged = 0x89ABCDEFABCDEF19
First, I need to... | Your code is almost correct. You want this:
merged = (y & 0x00000000ffffffff) | (x & 0xffffffff00000000);
There is no need to distinguish between big and little endian. The high bits of a value are the high bits of the value.
The difference is only the representation in memory.
Example: storage of the value 0x12345678... |
64,933,816 | 64,934,176 | Repeat contents of a std::vector | Suppose I have a vector (potentially large) of trivial types, e.g.
std::vector<int> v{1,2,3};
What is the best way to repeat it n times?
E.g. 3 times would give the result {1,2,3,1,2,3,1,2,3}
Surely, this is a problem that arises often (numeric libraries usually have such a function build in). My naive solution:
templa... | With range-v3 you could write:
#include <range/v3/all.hpp>
namespace rv = ranges::views;
template<typename T>
auto repeat(const std::vector<T> &input, unsigned int times)
{
return rv::repeat_n(input, times)
| rv::join
| ranges::to<std::vector<T>>;
}
Here's a demo.
I suspect this will have... |
64,934,110 | 64,938,799 | Branching out templated code based on a non const bool | This is the function I'm trying to simplify:
void BaseCharacter::ClimbLadder(float AxisValue)
{
if (AxisValue > 0.f)
ClimbUpLadder<bIsClimbingLaddersFast>();
else if (AxisValue < 0.f)
ClimbDownLadder<bIsClimbingLaddersFast>();
}
With bIsClimbingLaddersFast being a Boolean member variable. Now, ... | A possible (totally untested code) solution.
template<bool climb>
void BaseCharacter::ClimbLadder(float AxisValue) {
if (AxisValue > 0.f)
ClimbUpLadder<climb>();
else if (AxisValue < 0.f)
ClimbDownLadder<climb>();
}
void BaseCharacter::ClimbLadder(float AxisValue) {
if (bIsClimbingLaddersFa... |
64,934,136 | 64,934,983 | Asking reference to the shared_ptr for underlying element_type | I have very wild type and a shared_ptr pointing to it. I initialize this shared ptr to nullptr. Then I would like to construct respective object and provide the wild type as a parameter of make_shared. I would like to ask pointer to that type.
std::shared_ptr<cl::make_kernel<cl::Buffer&,
... | decltype(ptr) will be the type of the shared_ptr itself, not its element type. You are correct to use decltype() on the dereferenced type of the shared_ptr. That will be evaluated at compile-time, not at runtime, so the nullptr is not an issue at all:
std::shared_ptr<...> pointer = nullptr;
auto ptr = std::make_share... |
64,934,334 | 64,937,811 | Sample 3 integers without replacement in C++ | I want to sample three integers among {0, 1, ..., n-1} without replacement.
Here is how I proceed so far:
#include <random>
/* constructs vector {0, 1, ..., n-1} --------------------------------------- */
template <class T>
std::vector<T> integers_n(T n) {
std::vector<T> out(n);
for(T i = 0; i < n; i++) {
out[... | You can sample without replacement from 0, ..., n - 1 without allocating any additional memory; elem is unneeded. The key is to simulate a few steps of the Fisher-Yates Shuffle, as seen in David Eisenstat's answer to my related question.
// std::array<int, 3> requires no heap allocation, so is a better choice.
std::arr... |
64,934,352 | 64,934,899 | Compiler optimization on the traveling salesman problem | I am playing with the travelling salesman problem and am looking at the version where:
the towns are points in 2d space and there are paths from every town to all others and the lengths are the distances between the points. So it's very easy to implement the naive solution where you check all permutations of n points a... | Your factorial function is overflowing. Try replacing it with one returning int64_t and see your code taking 3 years to terminate for n > 20.
constexpr uint64_t factorial(unsigned int n) {
return n ? n * factorial(n-1) : 1;
}
Also, you don't need to calculate this at all. The std::next_permutation function returns 0... |
64,936,117 | 64,943,449 | Proper size initialization of a custom two dimensional vector class | I'm trying to write my own Vector2D class and I'm running into an issue when I try to initialize the size of the Vector2D in the constructor.
#include <vector>
template <typename T>
class Vector2D
{
public:
explicit Vector2D(const size_t& rows, const size_t& columns)
: m_data(rows, std::vector<T>{ columns ... | The warning told you everything you needed to know, you were choosing to ignore it. Here's your constructor.
explicit Vector2D(const size_t& rows, const size_t& columns)
: m_data(rows, std::vector<T>{ columns })
{}
The initialization section is using the std::initializer_list constructor of std::vector to ... |
64,936,896 | 64,937,041 | How to call a default constructor defined in another cpp file | I am trying to call a default constructor Process() from another(main.cpp) file.
process.h:
#ifndef PROCESS_H
#define PROCESS_H
#include <iostream>
#include <string.h>
// Car class with its attributes
class Process {
public:
std::string mbox;
std::string msg;
// Car(int year, std::string model, std::... | TL;DR
Remove explicit Process() = default; from the cpp file. In the class definition change Process(); to Process() = default;
Explanation
Defaulting a constructor, destructor, or special member function is done in the class definition. Once defaulted, nothing else need be done.
In addition, explicit is used to preven... |
64,937,258 | 64,937,378 | I want a class template to have a sort method only if the type passed to the template is an int | First of all, I know this question has been answered, but I don't really understand how to do it
I'm creating my own vector class (for learning purposes), and I want it to have a sort method that I've alreay coded only if the type passed to the template is int.
template<typename T>
class vector
{
T* _arr = new T[5]... | C++20 has nice requires for that:
template <typename T>
class vector
{
T* _arr = new T[5]{ 0 };
size_t _size = 0;
public:
void sort() requires(std::is_same_v<T, int>)
{
// whatever
}
};
For previous version, you have to use SFINAE
template <typename T>
class vector
{
T* _arr = new ... |
64,937,835 | 64,937,894 | How do I define a constructor outside of a template class? | I have a class template with one constructor inside that is not yet defined.
My goal is to define this constructor outside of the class template.
Is this possible? How can I do this? I have checked my C++ book and searched the web, but I cannot seem to find an answer. Any help would be appreciated. Thank you.
#include ... | Syntax would be
template <class T>
Calculate<T>::Calculate()
{
std::cout << "Constructor";
}
|
64,937,944 | 64,938,088 | What is the best way for streaming C++ struct data through TCP socket in Real-time between two projects in the same solution? | Basically I have a struct:
typedef struct MyStruct1 {
vector<MyStruct2> data;
chrono::high_resolution_clock::time_point time_stamp;
} MyStruct1;
MyStruct2 is a struct that contains some opencv data such as: Point2f. I want to share this between two projects that are in the same VS solution via TCP socket (because ... | TCP provides a stream of bytes. To send something over TCP, you need to serialize it into a stream of bytes. You can't just write the MyStruct1 object over the TCP connection. That will never work correctly because the object's internal representation in memory will contain data meaningful only inside the process and t... |
64,937,992 | 64,938,028 | Directly compare Two 8 Bit (1 Byte) values in C++ | I'm wondering, is there a way to compare 8 bit/1 byte values similarly to the way that we could compare an int?
For example:
// Start with these as false
bool int_comp = false;
bool byte_comp = false;
// Set the ints
int a_int = 128;
int b_int = 128;
// Set the bytes
char a_byte = 0xC0; // 11000000
char b_byte = 0xC0... |
I'm wondering, is there a way to compare 8 bit values similarly to the way that we could compare an int?
Yes, there is. Example:
std::uint8_t a_octet = 0xC0; // 11000000
std::uint8_t b_octet = 0xC0; // 11000000
if (a_octet == b_octet)
... is there a way to compare 1 byte values ...
Yes, there is. Example:
unsigned... |
64,938,024 | 65,055,716 | How can I hand a wchar_t* over to espeak without getting German characters spoken incorrectly? | I'm using espeak-ng to turn German-language traffic messages into speech. See this example text:
B6 Weserstraße B71 Seeborg vorübergehende Begrenzung der Breite.
B213 Wildeshauser Landstraße Delmenhorst-Deichhorst wegen Baustelle gesperrt.
The espeak method call looks like this:
unsigned int spoken_message_uuid = 0;
... | OK, this is not exactly a solution, yet a mere workaround, but at least it works: I hand over a string instead of a wstring. The original string turned out to be UTF-8-encoded, so that all the special characters fit into a string resp. char* variable. Here is the adapted code:
unsigned int spoken_message_uuid = 0;
esp... |
64,938,190 | 64,938,355 | Copy lStream to byte array | HRESULT hr = URLOpenBlockingStreamW(nullptr, cstring, &pStream, 0, nullptr);
if (FAILED(hr))
{
return 1;
}
char buffer[4096];
do
{
DWORD bytesRead = 0;
hr = pStream->Read(buffer, sizeof(buffer), &bytesRead);
if (bytesRead > 0)
{
std::cout.write(buffer, bytesRead);
}
} ... | IStream has a Stat() method for querying the size of the stream (among other things). Query the size, then allocate a byte array of that size, then Read() into the array.
If Stat() cannot determine the size (because the download is streaming and doesn't know the full size up front), then just use a std::vector as your... |
64,938,806 | 64,938,807 | Why is an object not moved if += is in the return statement | I imitated std::vector::operator+() from Visual Studio. It looks similar to this:
A operator+(const int diff) const {
A temp = *this;
return temp += diff;
}
Though I have a move constructor, it uses the copy constructor, but when I use this:
A operator+(const int diff) const {
A temp = *this;
temp += d... | The article below explains it, but in short:
example: returns a reference and the compiler can't be convinced the value isn't used elsewhere.
example: returns a locally created value and is safe to move.
You can also fix it by returning std::move(temp += diff), but this is often not preferred as it prevents t... |
64,938,877 | 64,938,913 | How to iterate through a list of the pointers of objects in C++ | I'm learning how to use C++ STL and algorithms.
Currently, I want to iterate a list of the pointer of objects.
This is my approach so far:
for (list<Course*>::iterator it = this->course_list.begin();
it != this->course_list.end(); ++it){
cout<<it->course_code<<endl;
}
this is a method inside a cl... | So the iterator functions as a pointer to the underlying data. Meaning lets say I had a vector of integers like below
vector<int> test = {1, 2, 3, 4, 5};
for(auto it = test.begin(); it != test.end()l ++it){
cout << *it << endl;
}
This will do what you desire, you basically need to dereference the iterator to get t... |
64,938,907 | 64,939,970 | How to check for INT_MAX without overflowing int | I created a BigInt class which allows for huge numbers (from any bases 2-36) far beyond the integer max by storing each digit in a vector. I need to be able to convert this back to an integer but return the int max/min instead if the max is reached, otherwise there will ofc be an integer overflow.
My question is how ca... | Preliminary info: you need to check for overflow before calculating something that overflows. If the overflow already happened, it's too late.
Adding an overflow check to your version of to_int() is tricky because you build up your value starting from the one's place. Because of this approach, you try to add pow(base, ... |
64,939,093 | 64,939,105 | Why do I get garbage when I try to parse the binary file in C++? | I'm trying to parse .wav files in C++.
The 44 bytes in the header of the .wav file are some of the file's meta information, which I am trying to parse.
I parsed it in Python and got the following, which should be correct
Chunk_id : RIFF
Chunk_size : 468556
Format : WAVE
fmt_id : fmt
fmt_size : 16
audio_forma... | In this line and the other lines to print char something[4];:
ss << "ChunkID: " << wavechunk->ChunkID << "\n";
std::stringstream will read until null-character '\0' but the array doesn't contain that, so it will read beyond the allocated buffer.
You will have to specify the size to print for properly printing the ... |
64,939,103 | 64,939,378 | gltf how are the animation matrices supposed to be computed? | I am trying to get animations to work for complex glTF models I am trying the RiggedFigure.
In particular I am trying to calculate the globalTransformOfJointNode as described here: https://github.com/KhronosGroup/glTF-Tutorials/blob/master/gltfTutorial/gltfTutorial_020_Skins.md
For that I have this function:
std::vecto... | I feel the spec should be more clear about this. So as it turns out you should NOT apply the transform of thr nodes and only calculate the animation matrix, the animation matrices already contain the node matrix premultiplied.
TL;DR:
Do this:
skeleton_matrices[child - start_joint] = skeleton_matrices[parent - start_joi... |
64,939,305 | 64,939,568 | How to properly instantiate an object in one container and store a shared_ptr to it in a separate container? | Suppose we have a struct or class that stores some data:
struct Foo
{
int bar;
}
Suppose also that I'd like to store two separate vectors; one that contains the actual instances of Foo, and a vector of shared_ptr that would allow me to access that data arbitrarily:
std::vector<Foo> data; // Where the data actually... | A shared_ptr does not mean "points to an object managed by someone else." A shared_ptr means "points to an object that will be deleted when the last shared_ptr to it is gone." A vector owns its elements. A shared_ptr owns what it points to. An object cannot have two owners, unless those owners have a prearranged agreem... |
64,939,419 | 64,941,429 | Prepend to static string at compile time | I'm having trouble expanding an array reference. When I pass the array reference to a function template as an argument, the constant nature of the array reference seems to be lost:
#include <cstdlib>
#include <utility>
template<const char ... C>
struct hint_for_opt_cls_holder {
constexpr static const char value[] ... | Arguments are not constexpr, you have to turn them in type:
gcc/clang have an extension to allow to build UDL from literal string:
// That template uses the extension
template<typename Char, Char... Cs>
constexpr auto operator"" _cs() -> std::integer_sequence<Char, Cs...> {
return {};
}
See my answer from String-i... |
64,939,580 | 64,939,863 | Could someone please explain why my program isn't sorting the values properly? | For my assignment, we have to build .h file that links the sort.cpp file and the testsort.cpp file. However when I compile and run the testsort.cpp program it doesnt provide the sorted array. Rather it just outputs the original array. I tired to add a return function to the sort.cpp file but i get the following error:
... | The way you are using sort.h and sort.cpp is wrong. Your insertion sort function in sort.cpp is never being called. What I tried was that I replaced your blank insertion sort function in sort.h with the function written in sort.cpp. And deleted sort.cpp file. Also you need to change the datatype of value in your insert... |
64,940,006 | 64,940,191 | C++ std::pair<T,T> variadic template | I've got a situation like this
template<typename T, unsigned int N, std::pair<T,T>... pairs>
struct Base{
static constexpr std::pair<T,T> SOME_STATIC_ARRAY[N] = {pairs...};
};
struct Derived : Base<int,3,std::pair<int,int>(1,2),std::pair<int,int>(2,3),std::pair<int,int>(3,4)>{
};
I want to have something lik... | A non-type template parameter can only be one of a short list of types of objects:
A value that has an integral type or enumeration
A pointer or reference to a class object
A pointer or reference to a function
A pointer or reference to a class member function
std::nullptr_t
Your temporary constructed instances of std... |
64,940,126 | 64,940,270 | How to assign return value of a function into a variable in c++? | i want to assign a returned value of a function into a Variable in C++, but the program is exit without any output.
int numberPosition = binarySearch(arr, num, searchNumber);
program output screenshot
Full code---
#include <iostream>
using namespace std;
int binarySearch(int arr[], int num, int searchNumber){
in... | Here This code works. You need to declare the length of array with variable num after you have taken the input value of num.
#include <iostream>
using namespace std;
int binarySearch(int arr[], int num, int searchNumber){
int start=0, end=num;
while(start<=end){
int mid = (start+end) / 2;
if(arr[mid] == sear... |
64,940,744 | 64,940,931 | What is the correct way of filtering the output of group_by with Range-v3? | The following code does not compile because x cannot be compared with a std::vector<int>, as x is a more complex structure handled by Range-v3 (which is good, because it's lazy, unlike std::vector<int>).
How can I write the filtering lambda to cope with that, possibly without forcing an unnecessary conversion of x to s... | You might still transform the view into vector:
| ranges::views::filter([](auto const& x){ return (x | ranges::to_vector) != std::vector<int>{3,4}; });
Demo
or without converting to vector, use ranges::equal:
ranges::view::filter([](auto const& x){ return !ranges::equal(x, std::vector<int>{3,4}); })
Demo
|
64,940,843 | 64,940,884 | Void value not ignored as it ought to be Error | I am using Doubly Linked List Data Structure of CPP and have written the following code
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
list <int> l1[64];
l1[1].push_back(100);
l1[2].push_back(200);
int p=l1[1].pop_front();
cout<<p<<endl;
p=l1[2].... | pop_front does not return anything. The reason is that it would be impossible to implement the strong exception safety guarantee if it did. To access the front element of your list use front. Here's your code rewritten.
int main()
{
list <int> l1[64];
l1[1].push_back(100);
l1[2].push_back(200);
int... |
64,941,114 | 64,944,069 | Weird behaivour when trying to simulate gravity | I'm trying to simulate Newtonian gravity with C++ and GLM. I'm using GLM vectors and this equation I found on Wikipedia
I translated this into code:
const static double g_const = 6.67430E-11;
void gravitate(object& obj1,object& obj2) {
glm::vec2 distance = glm::abs(obj2.position-obj1.position);
glm::vec2 unitve... | You using wrong function for Calculating the distance between the two objects,
You have used glm::abs(gentype const &x) which is just for calculating the absolute value of x, i.e. if x < 0 then it returns -x and if x >= it simply returns as it is.
You can used glm::distance(point1, point2) for calculating the distance ... |
64,941,432 | 64,941,739 | std::exchange working differently with VC++ and gcc | following code:
#include <utility>
int main()
{
auto pos = 0;
auto rel = pos - std::exchange(pos, pos + 1);
return rel; // g++: 0, VC++: 1
}
If you try the code on rextester with the VC++ compiler then the result is 1, with gcc on godbolt the result is 0 (results are apparently not returned with gcc using rext... | Binary operator - is note associated with a sequence point, meaning it is not specified in which order expressions A and B will be evaluated in A - B:
Consider two functions f() and g(). In C and C++, the + operator is not associated with a sequence point, and therefore in the expression f()+g() it is possible that ei... |
64,941,820 | 64,941,909 | How do i loop a function from another function in c++ | Quick question, well at least i'm hoping it is.
How do I loop a function using a for loop.
for example, i'm trying to convert kelvin to Fahrenheit. If the user inputs 350 the program loops starting from 0 up to 350 and converts each one to Fahrenheit.
my code is below. I'm sure its something really simple.
#include <io... | I just updated your code to create a minimal example.This is just to show you how it is done.
I just called the function where you are printing the values. As you are passing arguments by ref. all you had to do is to call the function with different inputs and the value of Farenheit variable will be changed in the loo... |
64,941,862 | 64,941,991 | Why is std:string not returning 0 on comparing sub strings of same text? | It's probably some simple oversight, but I'm perplexed on why the second compare doesn't return 0 in the following code:
#include <iostream>
int main()
{
std::string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
std::string text2 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.... | It's because compare function when passed the pos & len parameter, compares the whole of the first string with the second one. The first string is longer than part of the second string which you are comparing.
If you substring the first string also, then it will return true
result = text2.compare(0, 10, text, 0, 10);
... |
64,942,328 | 64,942,395 | Template deduction guide fails with 'too many initializers' error | I was reading on template deduction then tried to create one.
as follows:-
#include <iostream>
#include <array>
using namespace std;
template<int i,typename A,typename... B> struct deducted{
};
//Deduction guide
template<typename A,typename... B> deducted(A a,B... b)->deducted<0,A,B...>;
//
int main(){
deducted a... | You have too many initializers because there's noting to receive what you initialize it with.
Example fix:
#include <type_traits>
template<int i, typename A, typename... B>
struct deducted{
A a;
std::common_type_t<B...> arr[sizeof...(B)];
};
Demo
|
64,942,418 | 64,942,459 | std::transform with an overloaded conversion function | I want to transform all objects - which are of type, say, char - from one container c and store the results - which are of type foo - in a different container v. The desired conversion function is an overloaded function - call it to_foo.
Consider the following example:
#include <algorithm>
#include <vector>
struct... | You have to explicitly tell it which overload to use by casting to_foo:
std::transform(c.begin(), c.end(), v.begin(), static_cast<foo (*)(char)>(to_foo));
The type of the unary operation parameter of std::transform is a different template argument than the one used for the iterators. So it has to use the type of the v... |
64,942,468 | 64,942,730 | Convert reinterpret_cast from C++ to Python | I have this piece of code in C++ that I want to convert to Python:
int main() {
char buf[21] = "211000026850KBAALHAA";
std::cout << reinterpret_cast<const uint32_t*>(buf+12) << "\n";
const uint32_t *num = reinterpret_cast<const uint32_t*>(buf+12);
std::cout << num[0] << " " << num[1] << "\n";
}
which p... | The unpack_from function from the struct module is perfect for this.
https://docs.python.org/3.9/library/struct.html#struct.unpack_from
Unpack from buffer starting at position offset, according to the format string format. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes, starting... |
64,942,963 | 70,539,139 | aws lambda c++ runtime seg fault (but works locally) | I am trying to get a simple example running on aws c++ runtime, but it keeps seg faulting when I invoke the lambda function. To start with, the example shown in: https://aws.amazon.com/blogs/compute/introducing-the-c-lambda-runtime/ works fine. So, now, I fetch something from a bucket like so:
#include <aws/core/Aws.h>... | Maybe a little bit late to provide input now, but anyway in case someone encounters similar problems with rapidcsv on AWS Lambda:
One potential difference between local and AWS is the available RAM. By following the basic tutorial one ends up with a lambda function with 128 MB RAM (aws lambda create-function ... --memo... |
64,942,985 | 64,943,053 | exiting out of a loop using getline when you encounter a newline character | this might be the most basic of questions, but I have a problem exiting out of a loop using getline. Let's say a user enters these words using std::cin in the console:
/*
word
word_one
word_two
word_three
word_four
*/
And let' say we have defined an empty vector of vector of strings vector< vector<string> >. The desi... | The problem is you are checking for "\n" where you have to check for "". This is because getline does not copy the "\n" character, so it will be an empty string.
using namespace std;
int main(){
vector< vector<string> > vv;
vector<string> v;
string line;
while(getline(cin, line)){
if(line == ""... |
64,943,298 | 64,943,331 | My code works for C++ but not when converted to C language | I am providing the code that I converted to the C language and the converted code as well. The code works just as desired in C++ but I am unable to enter the value of the 'Operator' variable in the C language version.
This is the C++ code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
in... | Unlike the equivalent C++ code inputing a character using %c does not skip whitespace. To do that you should add a space before the %c, like this
scanf(" %c",&Operator); // skip whitespace then read a char
|
64,943,474 | 64,943,725 | How to properly empty stringstream buffer? | I have read How do you clear a stringstream variable? to clear the buffer by stringstream.str(""), or in other words - setting empty string. But if I do so, it won't clear it:
date.hpp:
#include <sstream>
#include <time.h>
#define fmt "%m/%d/%y"
class Date
{
std::stringstream buffer;
struct tm date;
temp... | The problem you are having is that calling buffer.str("") doesn't reset the stream state flags so if a previous operation failed or reached the end of the stream no other reads will succeed. The following should fix the issue:
buffer.str("");
buffer.clear();
Your code seems unnecessarily convoluted. If all you are try... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.