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 |
|---|---|---|---|---|
63,765,095 | 63,765,150 | How to loop through dynamic 2d array with different length in C++ | I have a 2d array in which the columns'size length is not the same. So how to loop all elements in that 2d array dynamically?
string** arr = new string*[4];
arr[0] = new string[5];
arr[1] = new string[3];
arr[2] = new string[4];
arr[3] = new string[2];
| Using dynamic arrays like that becomes harder to maintain and doesn't really give you any benefits over using a std::vector. You would need to store the size of each array separately.
Example:
#include <iterator>
#include <memory>
#include <utility>
template<typename T>
struct myarr {
myarr() = default;
myarr(... |
63,765,130 | 63,765,264 | What does 'INT' - 'INT' denotes in c++? | What does this statement really means in C++?
int num= '3'-'0';//or any integer in place of 3.
| Chars are just integers, so '3' is a char but it also has an integer value. But that value is not 3, on my system the value of '3' is 51 and the value of '0' is 48 so '3' - '0' equals 3.
Now on your system the values of '3' and '0' might be different. But C++ guarantees that whatever the values of the chars '3' - '0' m... |
63,765,400 | 63,820,383 | About thrust::execution_policy when copying data from device to host | I use thrust::copy to transfer data from device to host in a multi-GPU system. Each GPU has a equally sized partition of the data. Using OpenMP, I call the function on each device. On my current system I am working on 4 GPUs.
#pragma omp parallel for
for (size_t i = 0; i < devices.size(); ++i)
{
const int device =... | The Thrust doc on the thrust::device states the following:
Raw pointers allocated by host APIs should not be mixed with a thrust::device algorithm invocation when the device backend is CUDA
To my understanding, this means that host-device copy with thrust::device execution policy is invalid, in the first place, unles... |
63,766,021 | 63,769,117 | Callback fuction is not getting called | I am trying to implement ROS GotoGoal in c++, here is the code
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "geometry_msgs/Pose2D.h"
#include "turtlesim/Pose.h"
class Turtle {
public :
Turtle(int argc,char** argv){
ros::init(argc,argv,"mover");
ros::NodeHandle n;
pose = turtlesim::Pose... | I think you misunderstood what the sleep does. Unlike spin it doesn't actually perform all the ROS communication events. It's just a convenience for accurate sleep. See Difference between spin and rate.sleep in ROS.
Fortunately the fix is really easy, just add a spinOnce:
while( distance(goalPose) >= d && ros::ok()) {
... |
63,766,036 | 63,766,329 | Should association method call counterpart's association method? | Is it correct to call the method that associates the other object from the association method, or should we call both methods to associate them from outside these functions? Thank you.
#include <set>
class B;
class A {
public:
void associate(B &b) {
b_.insert(&b);
b.associate(*this);
}
priv... | Why not simply check whether it is already associated, and if not, do it?
void A::associate(B &b) {
if(not b_.contains(&b)) {
b_.insert(&b);
b.associate(*this);
}
}
Goal should be to design your code robust. This way, you can call associate as often as you want and it will work just fine.... |
63,766,057 | 63,766,214 | Why universal reference have to use template for the member function instead of class? | For example:
This is NOT universal reference:
template<typename T>
class C {
public:
void gogo(T&& c);
};
But this is:
template<typename A>
class C {
public:
template<typename B>
void gogo(B&& par);
}
| In the second snippet, B&& par is not necessarily an universal reference. It's considered to be universal only if you let the compiler deduce B when the call is made:
C<float> c;
c.gogo(42); // T is deduced as int, `par` acts as an universal reference.
c.gogo<int>(42); // T is fixed, `par` is a regular rvalue reference... |
63,766,142 | 63,766,381 | Deque in which all pushes/pops (front/back) and get_min() are O(1) operations | I am just wondering, whether it's possible to implement a structure (list/deque) which would have O(1) complexity (const/amortized doesn't matter) for get_min(), push_back(), push_front(), pop_back(), pop_front() operations?
It's definitely possible to implement stack or even queue (for them push() and pop() are availa... | It is indeed possible to build a min-deque where the push-front, push-back, and find-min operations work in worst-case time O(1) and the pop-front and pop-back operations take amortized time O(1). The easiest route that I know goes like this:
First, make a stack that supports push, pop, and find-min in time O(1). We’l... |
63,766,506 | 63,766,700 | How do I speed up a for loop with unrelated data? | A very simple example of passing an array of integers to a for loop shown below. If those integers are unrelated to each other, how can I make it so that a "for loop" iterates over all of them at the same time?
int waffles[3] = { 0 };
for (int i = 0; i < 3; i++) {
waffles[i] = i;
}
What I get
clock 1: waffles[0] ... | As @François Andrieux comment points out:
The compiler will very likely unroll that loop to the most efficient form for the targeted platform.
See how this code compiles in Godbolt's Compler Explorer here.
Clang puts 0 and 1 using the same instruction:
movabs rax, 4294967296
mov qword ptr [rsp + ... |
63,766,633 | 63,767,951 | Segmentation fault for thrust::host execution policy | I try to copy data from host to device and back, but not with the CUDA API but the thrust library. I allocated memory in a thrust::host_vector, and try to copy it to a thrust::device_vector. However, when using thrust::copy with the thrust::host execution policy for any data transfer from host <-> device, the program c... | You shouldn't use an execution policy of either thrust::host or thrust::device when using thrust::copy to copy data between host and device.
The reason for this is fairly evident by reading the documentation for thrust::device (for example).
Instead of relying on implicit algorithm dispatch through iterator system tag... |
63,766,803 | 63,766,862 | Will my code run faster with minimum amount of variables? | let's say as an example that we have two types of code :
FIRST:
float calculateAComplicatedValue(float x,float y)
{
int XasInt = floor(x);
int YasInt = floor(y);
float uniqueValueFrom2Numbers = ((x+y) * ((x+y)+1) / 2 ) + y;
float lerp = 0.5f * (y - x) + x;
float finalValue = ((XasInt * YasInt) + (... | No. The number of variables you use will (generally) not matter. Once you turn on your compilers optimizer it will figure out how to remove the intermediate unnecessary variables and the end result will be the same.
For an unoptimized (debug) build (which is the default for most compilers), there may be a tiny differen... |
63,766,902 | 63,766,917 | How to declare and use 2d array of pointers in C++ | For example, I have 2d array of pointers type int. I have two questions. First, how do I declare static 2d array? and how many options I can loop all elements from the 2d array?
| You can declare two declare with 2 rows and 5 columns like below:
int** intPtr = new int*[2];
intPtr[0] = new int[5]{ 1,2,3,4,5 };
intPtr[1] = new int[5]{ 6,7,8,9,10 };
You can loop all elements from the 2d array like below:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 5; j++)
cout << *(intPtr[i] + j)... |
63,766,944 | 63,767,087 | Why am I getting a Segmentation error with big integers? | I wrote a code as follows:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
long long int n,s,p,q,i;
cin>>n>>s>>p>>q;
long long int a[n];
a[0] = s%(long long int)pow(2,31);
for(i=1;i<n;i++)
{
a[i] = a[i-1]*p... | long long int a[n];
Will not do you any good, like everybody said it's better to use vectors, your code should look something like this:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
long long int n,s,p,q,i;
cin>>n>>s>>p>>q;
... |
63,767,082 | 63,767,189 | Illegal use of explicit template arguments while combating recursion errors | I am attempting to implement the SHA256 hash-function for use in-program with some compile-time abilities. A step in the pre-processing is padding the message/ input data given a formula. The amount of padding naturally has to be a positive integer. The algorithm relies on chunk processing and each chunk can only hold ... | In C++17 and later, this can be fixed by using if constexpr, like this:
template <uint32_t DataLength, uint32_t ChunkSize, uint32_t Chunks>
int GetBitsToAppend() {
constexpr int BitsToAppend = ChunkSize*Chunks - DataLength - 1 - (ChunkSize / 8);
if constexpr (0 > BitsToAppend)
return GetBitsToAppend<Dat... |
63,767,595 | 63,767,657 | Why is my C++ program's copy constructor called twice? | I can't figure out why my output start with "ACCB.." - my expectation was "ACB.."
Why is the copy constructor of class A called twice?
#include <iostream>
using namespace std;
class A
{
int x, y, z;
public:
A(int x, int y, int z) :x(x), y(y), z(z) { cout << "A"; }
A(A& a) :x(a.x), y(a.y), z(a.z) {... | Your copy constructor is being called 2 times because you are making 2 copies. 1 is being made implicitly by the compiler, and 1 is being made explicitly in your own code.
In your B constructor, its x parameter is being passed by value. That is an implicit copy being made when i in main() is assigned to x. Then, an exp... |
63,767,607 | 63,770,753 | ld Mac OS 10.13.6 : unknown option: -EL | I'm trying to compile android linux kernel (4.4) on my iMac but it keeps showing this error, here the full output:
juampi@iMacEscritorio /Volumes/roms/kernels/msm8998 make -j4 O=out ARCH=arm64 \
CC='/Users/juampi/Downloads/android-ndk-r21b/toolchains/llvm/prebuilt/darwin-x86_64/bin/clang' \
CLANG_TRIPLE=aar... | Thanks to Alan Birtles comment I realized that I could (and should) use the ld from the toolchain. I did not know how to do that exactly so I backed up Mac ld and cp the one from the toolchain to /usr/bin. If someone knows how to do it correctly please answer
EDIT: The correct way of doing what I stated before is setti... |
63,767,669 | 63,776,812 | Parent is null in ListView delegate after upgrade to Qt 5.15 | A ListView with a most simple delegate produces lots of warnings "21:35:31.911 warning T#16084047 unknown - qrc:/main.qml:15: TypeError: Cannot read property 'left' of null" if trying to set it's delegate anchors property and scrolling the list (which makes delegates to be destroyed/created). It was not the case in Qt ... | This is the result of a behaviour change in Qt 5.15. The first issue was reported here, with a more detailed summary here. The new documentation says:
Delegates are instantiated as needed and may be destroyed at any time.
As such, state should never be stored in a delegate. Delegates are
usually parented to ListView's... |
63,767,805 | 63,776,143 | What is the significance of returning the return value of a lambda expression from a function? | Since C++17 it is possible to use a lambda expression in a constexpr function.
In the related document Wording for constexpr lambda this code example is shown:
constexpr int AddEleven(int n) {
return [n] { return n + 11; }();
}
Is this just a toy example to demonstrate the language feature, or is there an actual... | Immediately-invoked lambdas are useful to provide a statement-friendly scope within an expression, typically to initialize const variables in a more complex way than constructor parameters permit:
auto const v = [&] {
std::vector<int> v;
// do some stuff
for(/*...*/)
v.push_back(/*...*/);
retu... |
63,768,063 | 63,771,603 | How can Monotonic array problem be solved in Complexity O(n)? | An array is monotonic if it is either increasing or monotone decreasing.
Example:
Input: [1,2,2,3]
Output: true
Input: [3,2,2,1]
Output: true
Input: [1,3,2]
Output: false
Here is my code with O(nlogn) time complexity. I used sorting and an extra array to solve the problem. My code is given below:
bool isMonotonic(v... | Here is the code for O(n) for the monotonic array problem.
We don't need to sort at first with another array. Here, I considered if all the elements are the same, it's still monotonic.
Now if the second element is bigger than the first, if the whole array needs to be in increasing order, else it can't be monotone. And... |
63,768,418 | 63,799,632 | why QCPColorMap is not setting my value for QCPRange? | i have a problem with colormap sizing.
I set the maximum and minimum x sizes, but when the map is drawn, the right border of the map is larger than the maximum x size that I entered in the code:
qMap->data()->setRange(QCPRange(data->m_xmin, data->m_xmax), QCPRange(data->m_ymin, data->m_ymax));
Why is the value of my v... | Have you tried using setTightBoundary?
|
63,768,420 | 63,770,436 | shortcut ctrl-q not handled in win32 | why this code not show me messagebox with "ctrl-q pressed" message when i press ctrl-q in win32?
case WM_CHAR:
switch(wParam) {
case 'q':
if(GetKeyState(VK_CONTROL) < 0)
MessageBox(NULL, L"ctrl-q pressed", L"caption", MB_OK);
... | I created a sample to test, the code is as follows:
#include <Windows.h>
#include <iostream>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR szCmdLine, _In_ int iCmdShow)
{
static TCHAR szAppName[] = TEXT("hello win... |
63,768,496 | 63,768,775 | How to delete rows and columns from an associative NxN matrix in O(n) in C++? | I have an associative NxN matrix and a vector containing all columns:
std::map<std::string,std::map<std::string,int>> A;
std::vector<std::string> columns; //this has size n
An element would look like this: A["abc"]["bcd"] = 2
I want to remove the row "abc" (so basically A["abc"]) and the column "abc" (so basically A[*... | You could use a std::map<std::pair<std::string, std::string>, int>, where the pair of strings are the row and column values.
Then you can use the custom std::erase_if algorithm that works on a std::map, which runs in O(n) time:
std::erase_if(A, [](const auto& item) {
auto const& [key, value] = item;
return key.... |
63,768,538 | 63,795,206 | OpenCL - multiple threads on a gpu | After having parallelized a C++ code via OpenMP, I am now considering to use the GPU (a Radeon Pro Vega II) to speed up specific parts of my code. Being an OpenCL neophyte,I am currently searching for examples that can show me how to implement a multicore CPU - GPU interaction.
Here is what I want to achieve. Suppose t... | The GPU works with a queue of kernel calls and (PCIe-) memory transfers. Within this queue, it can work on non-blocking memory transfers and a kernel at the same time, but not on two consecutive kernels. You could do several queues (one per CPU core), then the kernels from different queues can be executed in parallel, ... |
63,768,563 | 63,768,730 | constexpr constructor's parameter type 'std::function' is not a literal type | I'm writting a simple C++ HTTP server framework. In my Server class, I can add Route's. Every route consists of a path, an HTTP method and a Controller (which is a pipeline of functions to be called when the request was made.) That Controller class is constructed by receiving a list of std::function's (or, more precise... |
why std::function's can't be literal types? Is there any way to circumvent this limitation?
Because it uses type erasure in order to accept any callable. This requires polymorphism which cannot be constexpr until C++20 which will allow constexpr virtual.
You could use templates and capture the callable directly, but ... |
63,768,955 | 63,768,985 | How to Sum an Array element-wise, in reverse? | The issue i'm having is I have an array of ones, such that:
double foo[5] = {1, 1, 1, 1, 1};
And what i'm trying to do is take foo[4] and keep that as it's original value, and then sum each in reverse. The end result would have a new matrix, called foosum, that looks like this:
foosum[5] = {5, 4, 3, 2, 1};
The last li... | You're looking for std::partial_sum which you can use like this:
std::partial_sum(std::rbegin(foo), std::rend(foo), std::rbegin(foosum));
Also, note that sizeof(foo) is not going to do what you want. Just do:
double foosum[std::size(foo)];
Here's a demo.
|
63,769,115 | 63,780,582 | Why is numpy's cumsum so much faster than manual C++'s loop? | I am trying to understand why is numpy's cumsum function so much faster than a manual c++ loop. I am using pybind to provide mapping from C++'s code to python.
Numbers first:
[nav] In [24]: x = np.arange(100_000, dtype=np.float32)
[nav] In [25]: %timeit np.cumsum(x)
295 µs ± 34.9 µs per loop (mean ± std. dev. of 7 run... | The problem is in the argument of cumsum. const std::vector<float>& is still doing a rather expensive copy. Directly taking py::array_t<float> as an argument resolves this issue.
More details are present at: https://github.com/pybind/pybind11/issues/1042
|
63,769,260 | 63,769,353 | C++ : Why redeclare a template's generic data type after one use? | I was wondering why a template's definition of a generic data type can only be used once.
template<class T>
T x;
T y; // error: identifier 'T' not defined
template<class T>
T x, y; // error: expected ';' instead of ','
If I make a class, T can be used as many times as I want within the class definition. If I were... | The fact that your last declaration works is a bug in whatever compiler you are using. A template declaration can only declare a single entity[1]. That's just the rules of c++, so you have to have 2 templated declarations for your 2 variable templates.
|
63,769,268 | 63,769,359 | Does one definition rule apply to dynamically loading shared libraries at runtime? | If I load a dll or so library at runtime using dlopen() on unix or LoadLibrary() on windows, do i need to ensure that the symbols in the library do not have the same names as symbols in my program? Also is it possible to load multiple shared libraries that define the same functions?
Edit: I am specifically asking about... | Objects in a shared library loaded by dlopen do not appear in the namespace of the main program. You need to call dlsym with the name of the object as a string to get a pointer to it.
Using your example of having two libraries dynamically loaded having a global with the same name:
void *lib1 = dlopen("lib1.so", RTLD_L... |
63,769,623 | 63,772,703 | c++ write protobuf incrementally to file | I have the following protobuf:
message FrameData {
... arbitrarily complex ...
}
message DataDump {
optional uint64 headerField1 = 1;
optional uint64 headerField2 = 2;
optional uint64 headerField3 = 3;
repeated FrameData frameData = 4;
}
I'm creating the frameData protobufs iteratively one by one and I w... | Protobuf messages (especially proto2 syntax messages) can be concatenated to merge their contents. Figuring how exactly that works requires reading the protobuf encoding format documentation.
In your case, you can first write DataDump message with the header fields into the file. After that, put whatever number of item... |
63,769,830 | 63,769,887 | What is the case where SIG_ERR of Linux signal function can occur? | I would like to know which case is SIG_ERR among the return values of the signal function.
__sighandler_t oldHandler = signal( SIGSEGV, newSignalHandler );
if( oldHandler == SIG_ERR )
{
// In what case?
}
| The man page for each system call is supposed to list all possible error conditions under the "ERRORS" heading, along with the corresponding values to which errno is set in each case.
The man page for signal(2) shows only:
EINVAL signum is invalid.
This occurs if signum (the first argument) isn't the number of a vali... |
63,770,093 | 63,770,367 | Exception thrown when trying to change a pointer in a void function | I am trying to make a void function where it changes the pointer that I pass. The code is throwing an exception on one of the lines and i'm not sure why. Could it be I cannot pass the arrays as pointers then implement math on it? I thought I deallocated the pointers to fix it but this seemed to not work.
Void function:... | It looks like you want to pass two 1D arrays to func2().
One way to do that is remove the [] from the function signature as
(int one, double *value1, int two, double *value2, double *final1)
Within the function, change *value1[i] to value1[i], and similarly for value2. And remove the & when calling the function from t... |
63,770,231 | 64,063,379 | OpenCV JNI: Java/native handling of Mat - possibility for delete getting called twice? | I'm working on a project where I have a Mat that is allocated on the heap in native code (at the request of some Java code), like so:
Mat* mat = new Mat(height, width, type, pointer_to_some_native_data_buffer);
I then create a Mat object in Java, and point it to that native Mat by using a pointer returned from native ... | Since you're deleting the native Mat and the implementation of n_delete is:
JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1delete
(JNIEnv*, jclass, jlong self)
{
delete (Mat*) self;
}
the GC will delete the cv::Mat pointer twice, which is BAD. You can find here a more in depth description on what deleting a ... |
63,770,311 | 63,770,371 | Assigning base data from derived class with move produces an error | I am new to the new feature of C++ such as moving semantic (moving constructor and moving assignment operator). The code below produces an error in IDE as follows.
How to fix it?
#include <iostream>
using namespace std;
class HeavyData {};
class Base
{
protected:
HeavyData data;
public:
Base(HeavyData data)... | Don't initialize base-class data in the derived class's constructor. Invoke the base class constructor first, then your derived class's data.
Derived(Derived const &&src) :
Base(std::move(src)), extra{std::move(src.extra)} ()
|
63,770,467 | 63,770,510 | c++ template - More than one instance of overloaded function matches the argument list | Why did only the last invocation of max raise error?
error C2668: 'max': ambiguous call to overloaded function
#include <iostream>
#include <type_traits>
template<typename T1, typename T2>
auto max(T1 t1, T2 t2)
{
return t1 < t2 ? t2 : t1;
}
template<typename RT, typename T1, typename T2>
RT max (T1 a, T2 b)
{
... | Given max<long double>(4.5, 4);, for the 1st max its 1st template parameter T1 is specified as long double, T2 is deduced from 4 as int. For the 2nd max RT is specified as long double, T1 is deduced as double and T2 is deduced as int. Then the 2nd one wins in overload resolution because it's an exact match while the 1s... |
63,770,514 | 63,907,493 | Is it possible to open 2 streams from the same microphone on Oboe? | I'm trying to open 2 input streams from the same microphone on Oboe but it's not working.
One of the audio inputs I'm opening is like this:
defaultBuilder().setDirection(oboe::Direction::Input)
->setFormat(oboe::AudioFormat::Float) // For now
->setChannelCount(1) // Mono in for effects processing
... | I'm not an android developer, so excuse me for my french =) but from what I saw android uses ALSA/OSS as default kernel driver for audio, ALSA doesn't support opening more then one pcm on the same device also the device doesn't support more then one stream.
you can read more about ALSA here: https://www.linuxjournal.co... |
63,770,819 | 63,770,937 | When signal handler is not called when segment fault occurs? | Below is the operation method of my program, and there was a case where the registered handler was not called when the program was terminated due to the occurrence of a segment fault.
Is there a case where the registered handler can be terminated without being called when a segment fault occurs?
When initializing prog... | A well-formed, well-defined C++ application will never result in a segfault.
A segfault is a result of undefined behavior; but when undefined behavior occurs, by definition you can not expect any specific result or behavior. You have no expectation that a seg fault will occur as a result of undefined behavior, and even... |
63,771,194 | 63,771,918 | Win32 Event Handlng - Checking if charger is plugged in | I'm trying to do my first Windows app with C++ and I'm really struggling with how to implement event handlers. I'm reading through the Win32 documentation, but it's really sparse on examples. Unfortunately, I can't seem to find much on YouTube or other written sources for much beyond making the first window.
The basic... | Once you have a window handle hWnd, call the RegisterPowerSettingNotification function.
RegisterPowerSettingNotification(hWnd, &GUID_ACDC_POWER_SOURCE, DEVICE_NOTIFY_WINDOW_HANDLE);
In your window procedure, look for WM_POWERBROADCAST messages and check wParam for the power management event.
switch (message)
{
case ... |
63,771,659 | 63,771,679 | no matching function for call to a function in merge sort | I am trying to write a merge sort algorithm in C++.
If i try to compile the following code, i get the error:
mergeSort.cpp:9:19: error: no matching function for call to 'merge(std::vector&, int&, int&, int&)'
I tried everything in my knowledge to fix this problem and find similar ones online, but I can't figure it out ... | Put this line before the sort function:
void merge(std::vector<int> &v, int &a, int &k, int &b);
|
63,771,818 | 63,771,858 | no suitable conversion function from "std::string" to "const char *" exists c++ | It's a simple program for version numbers directories. It fails to compile with this error:
no suitable conversion function from "std::string" to "const char *" exists
#include <iostream>
#include <stdio.h>
#include <io.h>
using namespace std;
int main() {
int max = 10, daily_patch = 0, monthly_patch = 0, yearl... | mkdir() is from the POSIX API, which expects the C language, so it expects a c-style string. So use mkdir(dir.c_str());
If you want to use a C++ API and you have a recent compiler, you could use std::filesystem::create_directory(dir);.
|
63,772,782 | 63,773,401 | C++ : base64 to PNG backslash issue | I'm trying to convert a png file to a base64 but when I'm write the output to a file, I have a lot of backslash like this : data:image\/png;base64
My code :
string encoded_png;
Mat img; // Load an image here
vector<uchar> buf;
cv::imencode(".png", img, buf);
auto base64_png = reinterpret_cast<const unsigned char*>(buf... | Escaping / as \/ is perfectly valid in JSON. Any parser should interpret the escaped character as just a /.
|
63,772,826 | 63,773,084 | list::iterator invalid for moved-to list? | I have used a decent amount of C++, but not so much std::list ..
In my current project I need a std::list<..> data member, as well as keep track to a position in the list with a std::list<..>::iterator. The object must also be movable, but a default move constructor is not possible in my case. Here std::list does somet... | Iterators should be preserved when moving a container.
However end iterators of a container don't point to an element and are therefore allowed to be invalidated when moving a container.
If you change your code to work with begin rather than end then it works as you expect.
#include <list>
#include <vector>
#include <i... |
63,772,967 | 63,773,267 | Using vector container hangs while using array computes quick for 2D array | I came across an example from leetcode, and looking at solutions I tried to implement it in C++ using vector as follows,
class Solution {
public:
int minScoreTriangulation(std::vector<int>& A) {
std::vector<std::vector<int>> memo(A.size(), std::vector<int>(A.size(), 0));
return tri(A, 0, A.size() - 1, memo);
... | The issue is that you are passing a std::vector<std::vector<int>> by value instead of by reference:
int tri(std::vector<int>& A, int i, int k,
std::vector<std::vector<int>> memo) // <-- Passed by value
This will incur a copy each time memo is passed.
Maybe a very smart optimizing compiler could optimize the c... |
63,773,286 | 63,773,405 | What happens when BEGIN_MESSAGE_MAP is written as BEGIN_MESSAGE_MAP(Class, GrandParentClass)? | I came across a piece of code where BEGIN_MESSAGE_MAP for a class has it's Grandparent Class as the second parameter. I know that when it's the parent class, if the child class doesn't handle the message, it checks whether the parent class does. I couldn't find documentation for the case of the Grandparent class. Is th... | BEGIN_MESSAGE_MAP is a macro, so you can look at the expanded code and see what it does. The exact definition may vary with the version, but it is more or lees:
#define BEGIN_MESSAGE_MAP(theClass, baseClass) \
const AFX_MSGMAP* PASCAL theClass::_GetBaseMessageMap() \
{ return &baseClass::messageMap; } \
... |
63,773,830 | 63,774,187 | Plotting a 3D surface from data | I have written C++ code to numerically solve a PDE. I would like to plot the result. I have outputted the data to an ascii file, as 3 columns of numbers. The x-coordinate, the y-coordinate and the z-coordinate. This might look like
0.01 7 -3
-12 1.2 -0.24
...
I often have in excess of 1000 data points. I want to plot ... | You could coerce the data into the correct format for plotting with the base R function persp. This requires a vector of unique x values, a vector of unique y values, and a matrix of z values which is a length(unique(x)) by length(unique(y)) matrix.
Suppose your data looks like this:
x <- y <- seq(-pi, pi, length = ... |
63,773,871 | 63,774,037 | C++ concatenation; string + double; operator+ vs operator+= | gcc v10.2.0, -std=c++11
I'm not trying to convert the double value to a literal string using 'std::to_string()'. Trying to acheive a similar effect of adding an integer to a string but with a double value instead.
Expected output: "abcdA"
string s { "abcd" };
double d { 65.1 };
// s = s + d; // Error. no match for ... | operator += is a member function, and not a template by itself. So for a given string instance, its RHS argument is char. The compiler will look for a conversion to this type.
operator + is a free function template, templated so that it works with any basic_string instantiation:
template<class CharT, class Traits, clas... |
63,774,068 | 63,774,458 | I have a problem with substr function(C++) | Well, I am supposed to return the middle character of a word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.Like "test" => "es" or "testing" => "t".
And This is what I have wroten =>
#include <iostream>
std::string get_middle(std::string input)
{... | First, your main method is incorrect. Kindly change "Main" to "main" and return some integer value.
This is how you can achieve your task.
#include <iostream>
using namespace std;
std::string get_middle(std::string input)
{
if (input.length() % 2 == 0) {
return input.substr((input.length() / 2)-1, 2);
... |
63,774,109 | 63,774,277 | Replacing boost with std implementation | What is the correct way to replace this:
std::ostringstream buf;
std::for_each(bd.begin(), bd.end(), buf << boost::lambda::constant(" ") << boost::lambda::_1);
With an implementation that doesn't use boost? This is what I've tried:
std::string backspace("&nbps;");
std::ostringstream buf;
std::for_each(bd... | boost::lambda is a marvellous monstrosity that kind of backported lambdas to C++03. The equivalent to your code is:
std::ostringstream buf;
std::for_each(bd.begin(), bd.end(), [&](auto const &v) { buf << " " << v; });
... or even:
std::ostringstream buf;
for(auto const &v : bd)
buf << " " << v;
|
63,775,054 | 63,775,915 | Avoid C++ object files from being added to Ctags tags file | I had used the following command to generate my tags file to be used by vim in a C++ project:
ctags -R --c++-kinds=+p --fields=+iamS --extra=+fq --language-force=C++ /usr/include /home/user/audioprism/lib/essentia/ --exclude=.git --exclude=/home/user/audioprism/lib/essentia/src/examples -f /home/user/audioprism/tags
I... | Do you really need --langage-force? My experiments with lh-tags and my everyday work on C++ projects taught me that ex-ctags and universal-ctags are already able to sort out C++ files on their own based on the extension. I may use this parameter when running ctags on a temporary (extension-less) file where I've dumped ... |
63,775,986 | 63,778,859 | Combine multiple event logs | I am trying to export multiple event logs from windows. The export of one event log works fine but when I try to combine them I have a problem: the file size is good but the number of events is not. (The size of log.evt is the sum of the log files but when I open it with event viewer the number of events is the one fro... | I've managed to solve this by using EvtExportLog.
void Msw::create_error_log() {
LPWSTR pQuery = L"<QueryList>"
L" <Query Id='0'>"
L" <Select Path='Application'>*</Select>"
L" </Query>"
L" <Query Id='1'>"
L" <Select Path='System'>*</Select>"
L" </Query>"
... |
63,776,096 | 63,788,705 | Pin data for P/Invoke access | I am passing data from C#-Code to C++-Code and vice versa using P/Invoke. This works fine so far.
Lately I read a few articles (e.g. this one) about the need of pinning these data because the GC might rearrange or delete them while C++ is performing its tasks.
I consulted some Microsoft articles but for me they are not... | The rules here are conditional to what you're invoking, so it is only possible to give vague advice without a specific example, but:
If the method that you're invoking via P/Invoke only uses the pointer for the duration of that P/Invoke call, then: in almost all cases you're fine and passing an implicit pointer, or usi... |
63,776,537 | 63,776,583 | Destructor called twice with static object | test1.hpp
struct obj{
obj(){}
~obj(){cout<<"destroyed"<<endl;}
};
static obj x;
test1.cpp
#include "test1.hpp"
main.cpp
#include "test1.hpp"
int main(){...}
the destructor is getting called twice, why is this happening?
gcc-7.5.0
os-ubuntu
|
why is this happening?
Because the variable is declared static. This means that the variable has internal linkage. Which means that each translation unit has their own object. You have defined the variable in two translation units, and therefore you have two objects.
If you didn't want this, then the variable shouldn... |
63,776,963 | 63,777,434 | Using pybind11 to expose C++ functionality with preexisting embedded python interpreter | I am trying this type of coding for the first time and hence please pardon my lack of knowledge.
Requirement: I have a C++ code in which I have embedded python interpreter so that i can import/use python libraries with C++ using pybind11. Further, I want to make a wrapper of this complete C++ code (along with python in... | scoped_interpreter_guard is just a RAII wrapper around initialize_interpreter and finalize_interpreter. You can just call finalize_interpreter yourself instead of Py_Finalize.
|
63,776,969 | 63,777,010 | Is it legal to use the insert member function to insert a range into an empty vector? | Is it legal to insert into the std::vector named myvec when it is empty? Like so:
myvec.insert(myvec.end(), other.begin(), other.end());
I'm not sure where myvec.end() would point in that case.
Also, when myvec is empty, is the above different from the following?
myvec.insert(myvec.begin(), other.begin(), other.end())... | Yes, it's perfectly legal. From cppreference:
Causes reallocation if the new size() is greater than the old capacity(). If the new size() is greater than capacity(),
when myvec is empty, is the above different from the following?
No, because when a vector is empty, vector::begin() == vector::end(). So they are bot... |
63,777,013 | 63,777,114 | I need help fixing my C++ program - No errors, Not printing what I want it to | My program is not printing out "123" when I enter "qwe" there are no error messages. Just this: Unhandled exception at 0x78E7F2F6 (ucrtbased.dll) in TextEncode.exe: An invalid parameter was passed to a function that considers invalid parameters fatal.
and when i try to run it it says: This
Here is the code:
#include <i... | This loop:
for(int length = input.length(); length != 0; length--)
iterates from input.length() to 1. However the valid indices are input.length() - 1 to 0. Indexing into a std::string with the length of the string will return the \0 character, which is not what you want. Note that before c++11, indexing into this pos... |
63,777,466 | 63,777,806 | std::uninitialized_move with specific allocator | I'm writing a custom container template class that, as many (if not all) the containers in the stl, can use a specified allocator type.
To implement the range insert function, I need to move some of the elements in the container a number of spaces forward, where the memory is still uninitialized. To do this I want to u... |
Should I use this functions (portability)?
You shouldn't use the GCC internal functions.
No, there doesn't seem to be standard equivalents. You can write your own versions of those functions. If you do, note that CustomAlloc::construct is an optional function (for example, std::allocator doesn't have this function si... |
63,777,967 | 63,778,030 | What is the proper way to use static_assert in a non-instantiation template? | For example I got some template classes:
template <typename T, typename = void>
struct A {
void Print() {
static_assert(false, "fall into unsupported Print function");
}
};
// an instantiation if T is a unsigned type
template <typename T>
struct A<T, typename std::enable_if_t<std::is_unsigned<T>::value>> {
vo... | If the expression inside static_assert depends on a template parameter, the assertion will be deferred until instantiation. You could, for example, define the following class template, deferred_false:
#include <type_traits> // std::false_type
template<typename>
struct deferred_false: std::false_type {};
Then, use it ... |
63,778,379 | 63,780,509 | Why my C++ Graphics Program is not showing any output with g++ compiler? | I have written a code in C++, which is given below. The program is compiling successfully. But, when I'm trying to run the .exe file, then I am not getting the desired output.
My Code:
#include<graphics.h>
#include<stdio.h>
#include<conio.h>
#include<dos.h>
int main( )
{
int gd = DETECT, gm;
initgraph(&gd, &gm... | Edit : You are missing -L before path pointing to your libbgi.a library. More details are available here : Directory Options
Literally no one uses graphics.h these days. There are much better alternatives, as pointed by others.
But there are a lot of questions on StackOverflow referring to error code -1073741819 (0xC... |
63,778,837 | 63,779,001 | Is `std::atof` guaranteed to produce identical output when given identical string input? | I'm reading double values from file as strings and parsing them with std::atof. Afterwards, I'm using the values as keys in a unordered map. It's seems to be working correctly, but is it guaranteed to work in 100% of the cases?
I'm asking the question because it's extremely hard to produce identical double value if you... | You can round trip a number with DBL_DIG significant digits or fewer via a std::string. Typically DBL_DIG is 15 but that depends on the floating point scheme used on your platform.
That's not quite the same as what you are asking. For example, it's possible on some platforms to change the floating point rounding mode a... |
63,779,520 | 63,779,560 | c++ how to call static function of another class in namespace | I am new to C++, in the following code, I want to call the A::f function
namespace Top
{
class B
{
public:
void hello()
{
Top::A::f();
}
};
class A
{
public:
static void f()
{
printf("123\n");
}
};
}
int main()
{
Top::B b;
b.hello();
return 0;
}
But t... | You cannot call a function before it is declared. Switch the two classes such that when you define B the compiler already knows A::f:
namespace Top
{
class A
{
public:
static void f()
{
printf("123\n");
}
};
class B
{
public:
void hello()
{
Top::A::f();
}
};
}
... |
63,779,692 | 63,779,879 | Can't build hello world in C++ with Code::Blocks (20.03), OS: Linux | I am looking to learn a new language, C++, but I experience some difficulties with Code::Blocks 20.03 (CB). I am currently running CB on my DELL XPS 13-9360 with Linux, Ubuntu 20.04.1 LTS. I installed CB with the instructions on this site: http://ubuntuhandbook.org/index.php/2020/03/install-codeblocks-20-03-ubuntu-18-... | I'm afraid you were bitten by this code::blocks bug, which seems to have been plaguing Code::Blocks for a while now:
#993 Will not compile sources on build if path contains international characters
You can try renaming your homework directory from "École" to "Ecole" to see if that fixes it.
|
63,779,700 | 63,784,047 | classes with a lot of members | I am attempting to create a D&D encounter simulator.
I have therefore created a class called "Actor" to emulate the behaviour of the players and the monsters. The problem is that while the class for the moment only have 3 member variable, as the simulation gets more accurate it will become necessary to add more member ... |
This leads to a constructor with a lot of parameters so the question then becomes; Is there a better way to organize this data, since it can all vary with every instance of the actor class?
Right now the user is required to type in all the states by hand, though I have plans to make file reading for monsters accessibl... |
63,779,785 | 63,779,820 | Reinterpret cast to different type C++ | While reading about Reinterpret cast, I was checking the following code.
class Type1 {
public:
Type1() {
a = "Class Type 1";
}
void get1()
{
std::cout << a;
}
private:
std::string a;
};
class Type2 {
public:
Type2() {
b = "class Type 2";
}
void get2()
... | What you are doing is undefined behavior. There is no correct answer to this.
It is illegal in C++ to use a pointer/reference resulting from a reinterpret_cast between two types of an unrelated hierarchy -- and so any code that generates from such cannot be reasoned about.
With undefined behavior, the compiler is free ... |
63,780,438 | 63,780,931 | How can I iterate over CString and compare its characters to int? | I'm writing a dialog based MFC application in Visual Studio 2017 in C++. In the dialog I added a list control where the user can change the values of the cells as shown in the picture below:
after he changes the values, I want to check if those values are valid (so if he accidentally pressed the wrong button he will b... | You don't need to use std::string to process your strings in this case: CString works fine.
Assuming that your CString cvalue is the string you want to check, you can write a simple loop like this:
// Check cvalue for characters different than '0' and '1'
for (int i = 0; i < cvalue.GetLength(); i++)
{
TCHAR currCha... |
63,780,447 | 63,785,686 | How to store data in boost::program_options::variable_map? | I am currently trying to rework some code that was handed down to me. The original point of the code is to read a configuration file, and to set up the different options in the file in a boost::program_options::variable_map, which is then read throughout other parts of the code which is already working fine.
Here is th... | Yeah you can.
Be aware that you will have to decide how to "mock"/"fake" the other semantics of it though. (E.g. you might want to masquerade the options as having been defaulted)
Conceptually, variable_map would be a map<string, variable_value>. variable_value:
Class holding value of option. Contains details about ho... |
63,781,207 | 63,781,355 | Is there are any differences between different typename orders in class partial specializatoin definition? | code shows as below
template<typename t1, typename t2, typename t3>
class Test {
};
and there are two kinds of partial specializatoin when specify typename t1 as bool
// 1
template<typename t5, typename t6>
class Test<bool, t5, t6> {
public:
t5 n1;
t6 n2;
};
// 2
template<typename t5, typename t6>
class Te... | These two specializations are different. With Test<bool, X, Y> t, specialization (1) will have t.n1 of type X, and specialization (2) will have t.n1 of type Y. Demo
You can of course fix that easily, by swapping the type parameters you use for n1 and n2 at the same time you swap them in the list that follows Test. The ... |
63,782,107 | 63,782,143 | Is it safe to use std::string::c_str() to modify the underlying std::string? | I came across some code which has several instances of the bellow example:
std::string str = "This is my string";
char* ptr = const_cast<char*>(str.c_str());
ptr[5] = 'w';
ptr[6] = 'a';
In this simplified example there is an assignment of std::string::c_str(), which returns const char*, to a char* pointer using cons... | The reference for c_str that you cited is quite clear on the matter:
The program shall not modify any of the values stored in the character array; otherwise, the behavior is undefined.
The fact that it happens to work doesn't mean anything. Undefined behavior means the program could do the "right" thing if it wants t... |
63,782,349 | 63,782,382 | What happens if we use extra parenthesis() in mathematical expression? | double res = (double)((a*b)/(a+b));
After trying the above code with inputs 80,70 I am getting the output 37 not 37.333 but after removing one parenthesis i got the right answer.
The right code is:
double res = (double)(a*b)/(a+b);
I am using:
gcc version 9.3.0 (Ubuntu 9.3.0-10ubuntu2)
| double res = (double)((a*b)/(a+b));
Casting to double after integer math is applied, where values might have been truncated. Resort to operator precedence.
double res = (double)(a*b)/(a+b);
Here the cast is performed before the divison.
|
63,782,452 | 63,782,592 | c++20 views with parameter pack or initialiser list | I want to take a variable amount of arguments to a function and then get a view to them. I need to apply multiple functions to each one. I have been trying to get this to work with both parameter packs and initialiser lists. How come these solutions don't work and is there any way to do this?
Ideally the final function... | One way I've found to do this is to set the paramater type to std::initializer_list and then change the line:
data | transform(func3);
to:
for (const auto &datum: data) {func3(datum);}
This is because the return type of func3 is void, you can only use std::views::transform with functions which return something.
Demo he... |
63,782,555 | 63,782,627 | Bad instanition in function that is not itself instantiated. Difference in behaviour between clang and gcc | Consider the following c++ program:
template<typename X>
struct S
{
X x;
};
template<typename>
void f()
{
S<void> s;
}
int main()
{
}
When compiled with "-std=c++17 -pedantic-errors" it gives a compilation error with clang, but gives no compilation errors with gcc.
What does the c++ standard say about this p... | Your function template makes the program ill-formed, no diagnostic required.
[temp.res]
8 The validity of a template may be checked prior to any
instantiation. [ Note: Knowing which names are type names allows the
syntax of every template to be checked in this way. — end note ] The
program is ill-formed, no diagnostic... |
63,782,683 | 63,782,854 | how to add include paths to clang globally | I know this one way of adding include paths to clang:-
clang++ -I <dir> a.cpp
but with this, that path is only added for that particular file, and u have to write that every time linting, so how can I add some include paths globally to clint.
| There are also some environment variables which Clang looks at for include paths. For c++, they would be CPATH (both C and C++) and CPLUS_INCLUDE_PATH (C++ only) (And LIBRARY_PATH for the linker). So you can add something like this to your shell startup file if you are using bash or similar:
export CPLUS_INCLUDE_PATH="... |
63,783,486 | 63,783,509 | How can I make a selectionSort in C++ function involving a class, and with an overload of operation < for an array? |
I do not know how to how to call my operator< function into my selectionSort function.
The selectionSort function is supposed to arrange the blog objects in the array from newest to oldest.
The operator< function is comparing the days elapsed since the blog post of each blog.
I could use some help on how to set up my ... | The whole point of overloading an operator is so that you don't have to spell it out like a function call.
So for this line:
if (blog[j].operator<())
apart from the fact that you're missing the argument to operator<, you can just compare 2 Blog objects like this:
if (blog[j] < blog[i])
If you explicitly want to spell... |
63,783,816 | 63,784,225 | How does C++ know how to cast to a certain type? | If I write
long long int module = (long long int)GetModuleHandle(L"test.dll");
how does C++ know how to cast a HMODULE? As If I'm correct HMODULE should be a struct.
I understand how this works for basic types such as int, float and so on but
for programmer generated ones there must be like a translation, right?
| Well, it can't really, unless the code tells it how to, such as via a conversion operator or constructor.
There are a few built-in rules for primitive numerical things like int to float, or void* to int… though this latter example can only be done by a reinterpret_cast or a C-style cast like yours. That's because the c... |
63,784,527 | 63,784,665 | What is wrong with my equation or conversions? |
R (in feet) = (velocity (in ft/s))^2 / g (which is 9.8 m/s^2) * sin(2theta).
I checked various inputs using websites like this one https://www.ajdesigner.com/phpprojectilemotion/range_equation.php#ajscroll to check if my code was giving the right answer but it isn't and I don't know why. Any simple solutions?? Here i... | Your v0 can't be in feet cause gravity is in meters.
Change 5280.0 to 1609.3 (mi to m) and it works.
|
63,784,635 | 63,825,560 | Are SYCL and OpenACC competing frameworks? or complementary? | I'm gathering information about heterogeneous computing. I've come across SYCL and OpenACC. I gather that OpenACC has many pragma directives (similar to OpenMP) to abstract GPU calculations (either OpenCL or CUDA or both??). However, it seems to me that SYCL also tries to abstract GPU portions of the code.
So, are SYCL... | There are quite a lot of resources for both OpenACC and SYCL on the internet, you could check those to understand more. They are quite different, OpenACC is more similar to OpenMP but is focused on supporting mostly just Nvidia hardware. SYCL can be used to target a more diverse set of processors from different vendors... |
63,785,232 | 63,785,779 | Problem Deleting Node of a Binary Search Tree | I am implementing a binary search tree in C ++, but the code has an error, when deleting a node with 2 children the resulting tree is not well connected, the method to delete a node with 0 or 1 child works well. This code is based in this answer: https://stackoverflow.com/a/31698320/11053027 .
Edit:
For example if a ad... | It's hard to be certain, since you haven't given us a minimal complete example, but I think the problem is here:
if (nChildren == 2) {
child = getSuccesor(node);
remove(*child);
child->parent = node.parent;
child->left = node.left;
child->right = node.right;
So now child knows its children. But they don't kn... |
63,785,351 | 63,785,489 | Template Parameter iteration | Trying to find a simpler way to iterate through a set of Variadic template parameters.
My class holds a tuple of objects represented by the Variadic template parameters. I want to perform a common operation on all the members of the tuple and return an aggregated result.
A simplified Example would be:
template<typename... | You can use std::apply, which unpacks the tuple into a parameter pack, letting you write a fold-expression, like this:
std::size_t getSize() const
{
return std::apply([](auto... a) {
return (a.getSize() + ...);
}, data);
}
Here's a demo.
|
63,785,508 | 63,785,763 | How to specify a time duration in Boost Semaphore | I'm attempting to use the timed_wait function in boost::interprocess::interprocess_semaphore.
bool timed_wait(const boost::posix_time::ptime & abs_time)
In all of the Boost documentation and Stack Overflow questions that I've researched, there doesn't appear to be a single straightforward example on how to use timed_w... | Looks like the base should be UTC:
Live On Coliru
#include <boost/interprocess/sync/interprocess_semaphore.hpp>
#include <iostream>
namespace pt = boost::posix_time;
int main() {
using clock = boost::interprocess::microsec_clock;
boost::interprocess::interprocess_semaphore sem(3);
auto deadline = clock::... |
63,785,538 | 63,815,803 | C++ Event Handler With Registration Style, Notifier Method | I found this code for event handler with registration style in c++.
Can anyone explain me, what the below code does?
#include <algorithm>
#include <functional>
#include <list>
class Button {
public:
typedef void (*OnPress)(Button *, void *closure);
private:
typedef std::pair<OnPress, void... | Somewhere there are functions with the signature:
void function_name(Button* btn, void* ptrToSomeData);
The functions with the second parameter (ptrToSomeData) can be added into the list of event handlers with the function Button::AddOnButtonPress:
Button::AddOnButtonPress(function_name, &SomeData);
when the functi... |
63,785,589 | 63,787,587 | C++ choice of pass by value vs pass by reference for POD math structure classes for high performance applications considering cache coherency | For many high performance applications, such as game engines or financial software, considerations of cache coherency, memory layout, and cache misses are crucial for maintaining smooth performance. As the C++ standard has evolved, especially with the introduction of Move Semantics and C++14, it has become less clear w... | I see the question title is on the choice of pass-by-value vs. pass-by-reference, though it sounds like what you are after more broadly is the best practice to efficiently passing around 3D vectors and other common PODs. Passing data is fundamental and intertwined with programming paradigm, so there isn't a consensus o... |
63,785,787 | 63,786,220 | Flex regular expression for strings with either single or double quotes | I am writing a regular expression for a lexical analyzer for class. I presently have a regular expression written for regular strings with double quotes, however my professor wants us to account for single quotes, too.
Here is my current regular expression:
I am unsure as to how to make it accept both kinds.
Thank you... | (F)lex really doesn't have any mechanism which will accept two different kinds of quotes, other than putting the two patterns together with |. Usually, it's more readable to just write multiple patterns:
["]([^"\\\n]|\\(.|\n))*["] { /* A double-quoted string with escapes and splices */ }
[']([^'\\\n]|\\(.|\n))*['] ... |
63,785,864 | 63,786,041 | Accessing and modifying array of structures inside function | I'm having trouble trying to access and modify an array of structures through a function. I'm currently getting an error "expression must be a pointer to a complete type". I would appreciate any help.
#include <iostream>
#include <iomanip>
using namespace std;
const int NUM_PRODS = 9;
int main()
{
int id[NUM_PRODS... | Big thanks to cigien for the answer, in order to fix the "expression must be a pointer to a complete type" the structure must be outside main; additionally the -> operands should be replaced with "." for accessing the structure elements of the array to create a finished code that will look like this.
#include <iostream... |
63,786,183 | 63,800,285 | sampling GL_DEPTH_COMPONENTs of type GL_UNSIGNED_SHORT in GLSL shader | I have access to a depth camera's output. I want to visualise this in opengl using a compute shader.
The depth feed is given as a frame and i know the width and height ahead of time. How do I sample the texture and retrieve the depth value in the shader? Is this possible? I've read through the OpenGl types here and can... | If you use perspective projection, then the depth value is not linear. See LearnOpenGL - Depth testing.
If all the depth values are near 0.0, and you use the following expression:
vec4 pixel = vec4(vec3(visibility), 1.0);
then all the pixels appear almost black. Actually the pixels are not completely black, but the di... |
63,786,278 | 63,789,488 | PyTorch C++ extension: How to index tensor and update it? | I'm creating a PyTorch C++ extension and after much research I can't figure out how to index a tensor and update its values. I found out how to iterate over a tensor's entries using the data_ptr() method, but that's not applicable to my use case.
Given is a matrix M, a list of lists (blocks) of index pairs P and a func... | What I wanted to do can be done using the
tensor.accessor<scalar_dtype, num_dimensions>()
method. If executing on the GPU instead use scalars.packed_accessor64<scalar_dtype, num_dimensions, torch::RestrictPtrTraits>()
or
scalars.packed_accessor32<scalar_dtype, num_dimensions, torch::RestrictPtrTraits>() (depending on t... |
63,786,379 | 63,818,471 | How to write an image to STDOUT with Wincodec.h (WIC) | I came across this example and couldn't figure out how to change stream->InitializeFromFilename to something that outputs to STDOUT, inside the HRESULT SavePixelsToFile32bppPBGRA(UINT width, UINT height, UINT stride, LPBYTE pixels, LPWSTR filePath, const GUID &format) function. Tried using stream->InitializeFromMemory ... | Thanks to @SimonMourier, I was able to update his code to achieve what was needed.
SavePixelsToFile32bppPBGRA now writes the data to an IStream pointer, streamOut. It also invokes a new function at the end, to output data.
HRESULT SavePixelsToFile32bppPBGRA(UINT width, UINT height, UINT stride, LPBYTE pixels, const GUI... |
63,786,750 | 63,786,897 | In the PyTorch C++ extension, how can I access a single element in a tensor and convert it to a standard c++ datatype? | I am writing a c++ extension for pytorch, in which I need to access the elements of a tensor by index, and I also need to convert the element to a standard c++ type. Here is a short example. Suppose I have a 2d tensor a and I need to access a[i][j] and convert it to float.
#include <torch/extension.h>
float get(torch:... | Edited
#include <torch/extension.h>
float get(torch::Tensor a, int i, int j)
{
return a[i][j].item<float>();
}
|
63,786,972 | 63,787,686 | Is making the whole object constant same as making the whole object and the internal objects constant? | In a nutshell, the question is if the following 2 statements are equivalent:
const std::vector<std::vector<int>>
and
const std::vector<const std::vector<int>>
Because, out of the following 2 codes, the first one does not compile!
code1
#include <vector>
long findMaxSum(const std::vector<const std::vector<int>>& vecs... | They're not quite the same, but there's really not a whole lot you can do about it.
As you've found, attempting to create a vector with elements that are const will generally fail.
You could make the outer collection an std::array--it doesn't place as tight of requirements on the elements it contains, so an std::array<... |
63,788,149 | 63,788,356 | how can i check array length in a function? | In my file I have created function length that must return length of auto type array, but instead of right answer it everytime returns 1.
#include <iostream>
using namespace std;
int length(auto arr){
return sizeof(arr) / sizeof(*arr);
}
int main(){
int arr[] = {1,2,3,4,5,0};
// Test
cout << length(ar... | You are using a C-style array, and this type cannot be copied.
If we assume that your compiler has a version that supports
auto parameters, it's like if it had a template parameter
that would be deduced to int * here, because instead
of being copied, a C-style array decays to int *.
In this case, sizeof(arr) is sizeof(... |
63,788,589 | 63,788,838 | Why this C++ program not working for few testcases? | On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed).
Examples:
Input: N = 1, K = 1
Output: 0
Inp... | Your finals string remains with old contents. Seems you need to clear it at every loop turn.
Anyway, your approach is not suitable for large inputs - so instead of (huge) string generation consider calculation of needed symbol with some math.
|
63,789,000 | 63,789,504 | How to use a struct as member in a template class | I am trying to write an adjacency list to save the graph.
And here is my code, the class Graph has a member called Node. The Node can save any type of message, and many children with the cost to them.
After Node thers is a nodes member to save all of the node in graph.
template<typename T>
class Graph {
public:
str... | use shared_ptr replace the using Ptr = std::shared_ptr;
template<typename T>
class Graph {
public:
struct Node {
T val;
std::vector<std::pair<std::shared_ptr<Node>, int>> children;
Node() {}
Node(T data) : val(data), children() {}
};
typename std::vector<std::shared_ptr<Nod... |
63,789,266 | 63,789,379 | Conversion of boost placeholders with arithmetic to std | I am working on converting a C++ project which used boost and placeholders to transform a map the existing logic was:
inline const std::vector<uint32_t> average(const std::pair<uint16_t, std::vector<uint32_t> >& left,
const std::pair<uint16_t, std::vector<uint32_t> >& right)
{... | Just use a lambda.
In general case you can use const auto refs to avoid coping of parameters:
std::transform(left.second.begin(), left.second.end(), right.second.begin(), std::back_inserter(result), [] (auto const &a, auto const &b) { return (a+b)/2; });
In case of small numeric types like int you can pass them by val... |
63,789,423 | 63,790,336 | Do wee need a lock for uint64_t in single writer multi-reader situation? | class Foo {
public:
void set(uint64_t new_var) { var_ = new_var; }
uint64_t get() { return var_; }
private:
uint64_t var_;
};
Is there necessary need a lock in set and get if one writer multi-reader?
|
Is there necessary need a lock in set and get if one writer multi-reader?
You don't necessarily need a lock, but you need synchronization, which can be achieved either by locking a mutex or simply declaring the variable atomic.
In C++: std::atomic<uint64_t> var_;
In C: _Atomic uint64_t var_;
Regardless of the data ... |
63,789,443 | 63,789,759 | I can't understand the use of std::istream_iterator | I can't understand the code below.
(from https://www.boost.org/doc/libs/1_74_0/more/getting_started/unix-variants.html)
#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
using namespace boost::lambda;
typedef std::istream_iterator<int> in;
std::fo... |
Could anyone explain to me the syntax of first and last syntax and meaning in the example code?
The first iterator seems to be constructed with initial value std::cin, but what's the use of in() for the last value?
If you look at the description of the constructor of std::istream_iterator you can see that in() co... |
63,789,686 | 63,790,222 | How to pass IWebBrowser2::Navigate2 arguments? | I want to implement Internet Explorer webview control on my window.
I found this answer, on how to do that.
There is a problem: Navigate2 method from the answer is different from the headers I have. In the posters’s code, seems it has only one argument, and maybe others are by default, but I have 5 arguments with the s... | It appears that you failed to check if GetDlgControl succeeded. When it fails, ctrl has an unspecified value and might be null.
Of course, that leaves the question why it would fail, but that's another issue.
|
63,790,108 | 63,793,289 | requirements for custom container type to use with views | I start to play with std::ranges and want understand how views really work. So I try to write my own container and iterator type and want to use it in a view.
But something seems to be missing but the compiler only tells me that there is no begin() method inside the view but not why.
Example:
#include <iostream>
#inclu... | MyIterator does not model std::input_or_output_iterator because:
It needs to be default constructible.
std::iter_difference_t<MyIterator> must be valid, and
the pre-increment operator must return a reference.
MyIterator is not a std::sentinel_for<MyIterator, MyIterator> because its operators == and != take references... |
63,790,206 | 63,809,844 | How to use Qt Test module to test my own application? | I have a simple console application as below and I want to learn how to use Qt Test to test its functionalities. Honestly, I am trying to learn how to use Qt Test module.
MyApplication.pro
QT -= gui
CONFIG += c++11 console
CONFIG -= app_bundle
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += \
main.cpp \
pen.... | First, create a Qt Test application(TestPen). Since you want to test functionality of Pen class, you should add required header and source files to test project's .pro file(TestPen.pro) like:
SOURCES += ../pen.cpp
HEADERS += ../pen.h
Then you can include pen.h in your tst_testpen.cpp and test your Pen class' functiona... |
63,790,216 | 63,790,394 | Declaring variables of abstract type in C++ | I'd want to define a general class with some functions and nested classes with virtual functions:
class c_foo {
public:
class c_subfoo {
public:
virtual int do_subfoo(void) = 0;
};
int do_foo(void);
};
The function c_foo::do_foo() would call func... | Pure virtual function basically says: you have to override this function.
And override means you have to derive from c_subfoo and provide a different implementation.
And that means you cannot instantiate object of c_subfoo directly.
So this leaves you different options:
1.use pointer/reference to some subsubfoo, for ex... |
63,790,243 | 63,790,392 | std::stringstream across threads doesn't work as expected | I'm sending streaming data between threads using std::iostreams but struggling to extract the data, here's a contrived example:
#include <sstream>
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <mutex>
using namespace std::chrono_literals;
int main()
{
auto stream = std::string... | Problem is caused by fact that you are reading data before there is anything to read (it was written).
When you have tried to read data from empty stream error flags are getting set and then any following read/write operation on such stream are not executed until error flags are cleared.
You need something what will en... |
63,790,578 | 63,836,572 | How to find maximum dereferenceable-level of the parameter T using template | I am designing a "dereferencer" class, for fun.
I wrote some structs and aliass :
template <class _T>
using deref_type = decltype(*std::declval<_T>());
template <class _T, class _SFINAE>
struct is_derefable : std::false_type {};
template <class _T>
struct is_derefable< _T, deref_type<_T> > : std::true_type
{
usin... | After a few days of work, I was able to write code that works without causing an error in MSVC13.
First of all, I needed a robust module to check the dereferenceability of the type.
Since the struct-level SFINAE check fails, I took another method that deduces the return type from overloaded functions with auto->decltyp... |
63,790,821 | 63,791,326 | How to block until WiringPi finishes to sent serial data (UART)? | Device description (for context, skip it if you don't feel comfortable with electronic):
For a simple device, the communication is done in half-duplex UART (TX and RX are on the same wire), in the following way:
One pin (write-mode) indicate if the UART is sending or receiving (1: TX, 0:RX)
One pin write to the wire (... | I see 2 ways to implement this:
1. I can't test this right now, but it seems you could use the
void serialFlush (int fd) ;
According to the docs "This discards all data received, or waiting to be send down the given device" see at http://wiringpi.com/reference/serial-library/
(Edit: after re-reading that sentence, it... |
63,791,115 | 63,791,249 | Waiting for a thread to finish and future | Having such simple code:
void func(std::promise<int>* p) {
int a = 10, b = 5;
int result = a + b;
std::cout << "From inside the Thread...." << std::endl;
p->set_value(result);
}
int FP_main() {
std::promise<int> p;
std::future<int> f = p.get_future();
std::thread th(func, &p);
int ret =... | Because the thread is not the promise.
Promise is finished, but thread is not.
p->set_value(result);
// ...
// HERE
// ...
}
That are the last lines of func. The thread will now do its cleanups, will call destructors, etc. All while the promise is finished. Of couse, in 'HERE' the thread may a ton of o... |
63,791,261 | 63,791,510 | GetCurrentDirectory() only retrieve disk name | I'v been doing some C++ programming I have stumbled on a weird behavior,
whenever I try to get current directory using GetCurrentDirectory() it gives me back only the letter of the current disk.
Here's the code :
TCHAR path[MAX_PATH + 1] = L"";
DWORD len = GetCurrentDirectory(MAX_PATH, path);
cout << (char *)path;
He... | The (char *) cast in cout << (char *)path makes the compiler believe that path points to a char, but it actually points to a wchar_t.
You want this (uses the multibyte character version of GetCurrentDirectory (hence the A in GetCurrentDirectory):
char path[MAX_PATH + 1] = "";
DWORD len = GetCurrentDirectoryA(MAX_PATH, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.