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 |
|---|---|---|---|---|
74,215,648 | 74,225,369 | How to suppress unscoped enum warning in custom namespace? | I have some enums inside of my own namespace, yet I still get that annoying warning about "pollution in the global namespace". Why am I getting this error since they aren't even in the global namespace? How could I get rid of this warning? The exact warning is:
C26812, The enum type 'Adventure_Game::itemType' is unscop... | The MSVC warning C26812 is not from the C/C++ compiler. It's coming from the Static Code Analysis (/analyze) feature and specifically from the C++ Core Guidelines Checker.
The "recommended solution" that the checker is telling you about is to use C++11 strongly typed enumerations. That said, you can just suppress the w... |
74,216,441 | 74,217,144 | how to get rid of warning: control reaches end of non-void function c++ | I wrote this code and don't understand why there´s a warning, as far as I can tell every branch has a return value. How could I fix this?
bool ValidDate(int d, int m, int a) {
if ((m < 1) || (m > 12)) {
return false;
} else {
if ((m == 1) || (m == 3) || (m == 5) || (m == 7) || (m == 8) || (m == ... | The warning arises because the compiler does not know that the else if (m == 2) condition will always be true when that condition is checked, as all other possibilities must have been exhausted. Since the compiler does not perform this kind of analysis, you as the programmer might as well help the compiler by explicitl... |
74,216,539 | 74,216,612 | Question about new placement related to class constructor | As far as I know the new keyword performs the process of allocating memory and call constructor of object.
class X{
public:
int x;
X(int a):x(a){std::cout<<"X(int a)"<<std::endl;}
~X(){std::cout<<"Delete X"<<std::endl;}
};
int main()
{
X* ptr = new X{2};
// allocate mem sizeof(X);
// call constr... | new expressions and operator new are not the same thing. Unfortunately, they have names that suggest that operator new is like e.g. an operator overload operator+ for the + operator, which is however not the case.
A new expression may call an operator new overload, but that is only for the allocation step you are talki... |
74,217,172 | 74,219,814 | How to read alpha channel from .webm video using ffmpeg in c++ | Background
I have a .webm file (pix_fmt: yuva420p) converted from .mov video file in order to reduce file size and I would like to read the video data using c++, so I followed using this repo as a reference.
This works perfectly on .mov video.
Problem
By using same repo, however, there is no alpha channel data (pure ze... | You have to force the decoder.
Set the following before avformat_open_input()
AVCodec *vcodec;
vcodec = avcodec_find_decoder_by_name("libvpx-vp9");
av_fmt_ctx->video_codec = vcodec;
av_fmt_ctx->video_codec_id = vcodec->id;
You don't need to set pixel format or any scaler args.
This assumes that your libavcodec is link... |
74,217,816 | 74,230,127 | NodeJS function called from v8 SWIG C++ seg. faults | I have some c++ code which I am compiling with SWIG (you can clone the code here), it defines the javascript "theFunction" which will be executed from C++ once setup :
v8::Persistent<v8::Function> theFunction;
/** Class to test the wasm setup
*/
class Test {
...
}
I am extending it in my swig Test.i template to setup... | Change the following Call method :
func2->Call(SWIGV8_CURRENT_CONTEXT(), ret, argc, argv);
To this :
func2->Call(SWIGV8_CURRENT_CONTEXT(), func2, argc, argv);
|
74,218,474 | 74,223,140 | Is there any way to create a lookup table at compile time or in preprocessor for a factory creational pattern in c++? | I have developed code for image processing that can load, with the help of a json file, different image processing processes depending on the data in the json file. When the file is readed, in some point is reached a function that depending the type of process specified in file it creates the corresponding process that... | You might change the if-else chain by a map.
std::/*unordered_*/map<QString, std::function<BaseProcess*(QJsonObject &)>> processFactory;
BaseProcess* getSpecificObject(QString id, QJsonObject &proc)
{
if (auto it = processFactory.find(id); it != processFactory.end()) {
return it->second(proc);
}
qD... |
74,218,524 | 74,218,699 | Allocating on heap and then use shared pointer, how to free the data | I have the following scenario.
I have a allocated a chunk of data using new, then assigned the block of data to a smart pointer in the class DNA_ImageBlob, how do I free T*blob data ?
template <class T>
void DNA_ImageBlob<T>::Reset(int h, int w, int c)
{
SetWidth(w);
SetHeight(h);
SetDepth(c);
T *blob =... | Here is an example, if you have questions just ask.
#include <vector>
#include <cstdint>
#include <iostream>
// Blob is a RAII class, meaning its destructor will
// cleanup all resources it owns (in this case memory held by vector)
class Blob
{
public:
Blob(std::size_t width, std::size_t depth, std::size_t heigh... |
74,219,608 | 74,219,889 | Determine duplicates/pairs in an array in C++ | I have been doing this problem for 2 days now, and I still can't figure out how to do this properly.
In this program, I have to input the number of sticks available (let's say 5). Then, the user will be asked to input the lengths of each stick (space-separated integer). Let's say the lengths of each stick respectively ... | Instead of storing all the lengths and then comparing them, count how many there are of each length directly.
These values are known to be positive and at most 100, so you can use an int[100] array for this as well:
int counts[MAX] = {}; // Initialize array to all zeros.
for(int i = 0; i < numberOfSticks; i++) {
i... |
74,219,738 | 74,220,390 | why does memory_order_seq_cst didn't protect my atomic-operation running sequence? | #include <assert.h>
#include <atomic>
#include <iostream>
#include <thread>
std::atomic_bool b(false);
std::atomic_bool lock{false};
void producer() {
b.store(true, std::memory_order_seq_cst);
lock.store(true, std::memory_order_seq_cst);
}
void consume() {
while (!lock.load(std::memory_order_seq_cst))
;
a... | void producer() {
b.store(true, std::memory_order_seq_cst); // 1
lock.store(true, std::memory_order_seq_cst); // 2
}
void consume() {
while (!lock.load(std::memory_order_seq_cst))
; // 3
assert(b.load(std::memory_order_seq_cst)); // 4
b.store(false, ... |
74,222,925 | 74,223,441 | Building red-black tree with vector of lists in C++ | vector<list<Nodo<string>*>> lista;
i have this vector of lists and I'm trying to write a method to insert elements into it
template <typename T> void HashRBT<T>:: riempimento()
{
for(auto &it:vett_dati)
{ int key=it.first;
string value=(it.second);
int id=hashFunctionDivsion(key);
... | Break the problem down and look at it without the logic of your rb tree.
std::vector<int> vec{10,20}; // vector of size 2
vec.at(0); // fine: element 0 exists.
vec.at(1); // fine: element 1 exists.
vec.at(2); // will throw because vector has size 2, so only elements 0 and 1
vec.resize(3); // now vector has size 3: elem... |
74,223,378 | 74,229,330 | wxWidgets - setting an image as background | I am trying to set an image as the background but I have no idea how to do it.
It has been hours. The first lines of code I copied from somebody and they seemed alright but it still doesn't work.
The error that I have appears in a separate window and says it cannot load/find the image.
#include "MainFrame.h"
#include <... | I can't help you with the program not being able to find the image - the image needs to exist either in the application's working folder or on an absolute path.
You can get around this by including the image in the executable. Unfortunately there is no consistent cross-platform way to do this - windows and mac have se... |
74,223,559 | 74,223,606 | ifstream unable to load in two or more files correctly [C++] | I'm making an "Identity generator" where the computer randomly picks lines from .txt files.
Although it works fine with the first part of the code, when I repeat that code and change the variables it still uses the old txt file.
Expected result:
Full name: {random first name} {random sur name}
Address: {random address}... | You never clear lines, so the start of the vector is always going to be your list of first names. You do reset total_lines to 0 before reading each file, so your random range is 0..total_lines each time, so you're always picking from the start of the array, which again, is all first names.
Assuming lines is a std::vect... |
74,223,602 | 74,224,913 | Should i use std::string in a web server for parsing a client request? | I'm coding a little HTTP 1.1 web server in C++98 (c++ version mandated by my school) and i haven't make a decision about which data type i'm gonna use to perform the request parsing, and how.
Since i'll be receiving read-only (by read-only i mean that i don't have to modify the buffer) data from a user-agent, would it ... | Definitely. It's a school project, not a high-performance production server (in which case you'd be using a more modern C++ variant).
The biggest performance problem you'd typically have with std::string is not parsing, but string building. a + b + c + d + e can be rather inefficient. Details, really: just start by wri... |
74,224,218 | 74,224,431 | What happens when glDraw*Instanced() is called with primcount greater than how many times a vertex attribute can get updated? | In my opengl program (opengl 3.3 core profile) i have an array with N float elements in it. I pass the array to a VBO and specify it as an array of vertex attributes at index 0. Here data is the array:
glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW);
glVertexAttribPointer(0, 1, GL_FLOAT, GL_FALSE, siz... | You get the exact same thing that happens if you render more vertices than there is storage in the buffer objects: out-of-bound reads. If robust memory accesses are enabled in your context, then this value will be either zero or some other value within the storage of the buffer object. Without robust accesses however, ... |
74,224,268 | 74,232,322 | Link Static CUDA Library using CMake | I have the following project structure:
| CMakeLists.txt (1)
| main.cpp
| cudalib/
| CMakeLists.txt (2)
| cppfunction.cpp
| cudafunction.cu
| cudalib.h
and I am trying to build the content of the cudalib folder as a static library that is afterwards linked to by the main project. This process usual... | I found the answer after hours of trouble.
There are two resources that gave me the hints I needed:
https://developer.nvidia.com/blog/building-cuda-applications-cmake/
https://gist.github.com/gavinb/c993f71cf33d2354515c4452a3f8ef30
You have to link the mainapp against the CUDA runtime:
CMakeLists.txt (1)
cmake_minimum_... |
74,224,485 | 74,229,054 | Is it possible to iterate through a vector of vectors columnwise? | I have a vector of vectors of strings. I want to find the lengths of the longest string in each column. All the subvectors are of the same length and have an element stored in it, so it would be rather easy to find it with two for loops and reversed indices.
vector<vector<string>> myvec = {
... | Here is a solution using C++20 ranges and lambdas that is similar to Nelfeals answer:
// returns a function returning the i-th element of an iterable container
auto ith_element = [](size_t i) {
return [i](auto const& v){
return v[i];
};
};
// returns a range over the i-th column
auto column = [ith_elem... |
74,225,934 | 74,226,088 | new (ptr) T() == static_cast<T*>(ptr)? | I want to implement something like rust's dyn trait(I know this doesn't work for multiple inheritance)
template<template<typename> typename Trait>
class Dyn
{
struct _SizeCaler:Trait<void>{ void* _p;};
char _buffer[sizeof(_SizeCaler)];
public:
template<typename T>
Dyn(T* value){
static_assert(s... | The expressions new (ptr) T() and static_cast<T*>(ptr), where ptr has type void*, will return the same address, ptr (as long as T is a scalar type -- array types are allowed to have overhead when dynamically allocated)
However, the semantics are quite different.
In new (ptr) T(), a new object of type T is created at t... |
74,226,129 | 74,248,507 | Why is IExplorerCommand::Invoke() no longer being called? | I have created a File Explorer context menu extension that uses the IExplorerCommand interface to add menu commands to the Windows 11 context menu.
This has been working fine, but after the last Windows update, it no longer works properly.
Although the menu commands still appear, nothing happens when I click on any of ... | Well, after wasting hours on this I finally have a solution!
My code was based on the PhotoStoreContextMenu sample code here:
https://github.com/microsoft/AppModelSamples/tree/master/Samples/SparsePackages/PhotoStoreContextMenu
This uses the Windows Runtime C++ Template Library (WRL), and defines the base classes used ... |
74,226,345 | 74,226,507 | Make simple calculations with C++ pre-processor | In my C++ application I configure some features in this way:
#define LED_SIZE 113
#define SEGMENT_SIZE 3
const int LED_SEGMENTS[SEGMENT_SIZE] = {30, 70, 13};
I would like to check if the sum of the literal values are equal to LED_SIZE:
30+70+13 = 113
I'm interested to do this at compile time, using a pre-p... |
using a pre-processor directives
It is not possible to access arrays using preprocessor directives. LED_SEGMENTS[0] means literally LED_SEGMENTS[0] for preprocessor, there is no array access in preprocessor.
You could stay with it in preprocessor world, and then write a variadic overloaded argument macro to calculate... |
74,226,424 | 74,226,646 | Logic involved in solving for binary tree maximum sum | This problem comes from leetcode which can be found here. I was reading a solution to this problem which is below
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int... | The expression l + r + root->val considers what would be the optimal path for which the highest participating node is the current node.
Consider that it could be possible that this optimal path would not include nodes from the left subtree. In that case we want to make sure that l is 0. That is what this max(0, dfs(roo... |
74,226,582 | 74,232,784 | Can I write a `concept` to accept a specific template class only? | I have a templated class:
template<Vector T>
struct diagonal_matrix;
Now, I want to create a concept DiagonalMatrix for all of templated class versions. So:
DiagonalMatrix<diagonal_matrix<std::vector<double>>> == true
DiagonalMatrix<diagonal_matrix<std::array<float, 4>>> == true
DiagonalMatrix<diagonal_matrix<std::... | If diagonal_matrix has a member aliases for all it's template parameters, you can substitute them into diagonal_matrix<>, then check you get what you started with.
template <typename M>
concept DiagonalMatrix = std::same_as<M, diagonal_matrix<typename M::vector_type>>;
|
74,226,681 | 74,227,141 | Why does MSVC say a call to a virtual constexpr functional call operator does not result in a constant expression? | I have a class that wraps an array. It inherits from an abstract base class defining one virtual constexpr method for the function-call operator. In the child class, I override said method and access the internal array:
#include <cstddef>
#include <array>
#include <initializer_list>
template <typename T, std::size_t N... | User @Barry agrees with me that it's definitely a bug in MSVC.
I've submitted this bug report.
Hopefully the issue gets resolved soon.
Thanks all for your comments and further insights, it's very helpful!
|
74,226,690 | 74,233,108 | TensorRT finding boundin box data after inference | I'm trying to use TensorRT for inference using my trained YOLOv5 model.
The model has been converted to an .engine file, which I have no problem loading and running the inference with. My problem is accessing the data.
What I basically end up getting as output is a 1x25200x85 tensor, which I have no way to process.
So ... | The output of the NN describes 25200 boxes with 85 numbers.
Each box represents a unique detection with its bounding rectangle and confidences for each coco class. There are potentially up to 25200 boxes (since the NN must have a static sized output) but in practise it only finds a handful of detections for each image.... |
74,226,968 | 74,236,802 | Breaking a WHILE Loop with a Function (+ a blocking Function) | I am working on a program using threads to treat demands of remote clients in C++. The server will wait for clients to connect, and launch a thread doing some things.
For the server to shut down, the user must do an external interrupt Crtl+C, and the code will handle the signal (using <csignal>) in order to shut everyt... | Thanks to @Blindy, I digged up about select(2) and came up with something. I will try to explain it here instead of marking @Blindy's answer as solution, since it took me some time to make it work and I want to save people from the headaches I had.
Here is the new while loop, using select() :
#include <csignal>
#includ... |
74,227,764 | 74,232,294 | MAP_FIXED_NOREPLACE not supported on Ubuntu 20 | When I run this code I get "mmap: Operation not supported", according to mmap man
that's because one of the flags is invalid (validated by MAP_SHARED_VALIDATE). The "bad" flag is MAP_FIXED_NOREPLACE
#include <fcntl.h>
#include <errno.h>
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>
int main(int argc, c... | The only way to answer your question is to look at the source.
Taking an excerpt from do_mmap:
switch (flags & MAP_TYPE) {
case MAP_SHARED:
/*
* Force use of MAP_SHARED_VALIDATE with non-legacy
* flags. E.g. MAP_SYNC is dangerous to use with
* MAP_SHARED as you... |
74,228,635 | 74,228,692 | How to use value of a class enum : char as a char argument of function? | In an endeavor to write cleaner code I'm (likely over-)using enums, like so:
enum class SoundFileCode : char {
PC_STARTUP = '1', // probably never used
LOADING_READY = '2',
VOICE_RECOGNITION_ON = '3',
VOICE_RECOGNITION_OFF = '4',
DISPENSING = '5'
};
I'd like to be able to pass that value to a function in a n... | enum class purposefully disallows implicit casts to the underlying type, so you'd either need static_cast<>, or - preferably - take the enum in the callee.
If neither of the above works, e.g. because the functions you call are in a library, you can still do the old trick of wrapping the enum into a namespace (or class)... |
74,229,538 | 74,230,025 | Why does the cast operator attempt to call the constructor first? | I have an object that stores some state in a member of type S. Upon request of the view method, it returns a view of it of the type T, obtaining it by casting.
template<typename S, typename T>
struct Viewer {
S m_state;
Viewer(const S& state): m_state(state) {}
auto view() {
// return m_state.operat... | You don't have to specialize the State constructor, but do something else to SFINEA out the constructor template so that the default copy constructor is called in this case.
struct State: std::tuple<int, int> {
template<typename T,
typename = std::enable_if_t<std::is_convertible_v<T, int>>>
State(c... |
74,229,580 | 74,230,178 | maya api save/keep data in memory generated by command? | I wrote a maya plugin (class).
Executing the plugin/command in maya will produce some data. Executing the plugin/command again in Maya will depend on the data generated after the last execution, but the data generated in the last execution will be destroyed with the destruction of the plugin class.How do I save/keep th... | The only storable database in Maya is the node graph, and the attributes on the nodes. If you have written a command that is generating data in the DG, you probably should have written that as a node (where the input attributes are your function arguments, and the output attributes are the function outputs)
Typically y... |
74,229,614 | 74,229,632 | Check if string contains Enum Value C++ | I am trying to solve an assignment and I searched in every possible way for an answer, but managed to only get "how to transform an enum into a string"
I have a string called type that can only contain "webApp", "MobileApp" and "DesktopApp". I have an enum that looks like this:
enum applicationType { webApp = 5, Mobile... | You simply can't.
The names of c++ objects, types and enum entries are not available as strings. They're effectively just placeholders, identifiers for things the compiler needs to identify. It discards these identifiers pretty early on the way from source code to machine code.
(As of c++20. Who knows what the future b... |
74,229,738 | 74,229,886 | Running a C++ Script In Visual Studio 2022 keeps deleting text within a file, not sure what's wrong with the code | I've been stuck working on this painful program for a few hours now in Visual Studio 2022, and am struggling to wrap my head around why it keeps deleting text in a different file each time I run it.
For reference: For a C++ related assignment I have, I have to design a program that opens a file (age.txt in this instanc... | First, a mini-code review:
#include<iostream> // Poor spacing
#include<string>
#include<fstream>
using namespace std; // Bad practice
int main() // I'm noticing that a lot of your lines all have an extra space at the end
{
ifstream din; // Don't front-load your declarations; declare when you need them.
ofs... |
74,230,074 | 74,230,238 | How do I correctly use 3D Perlin Noise as turbulence for my particle system? | So I am working on a particle system, mainly as a learning exercise on the CPU, using Visual Studio C++. It's looking pretty neat!
The latest thing I'm attempting is to add turbulence using 3D perlin noise. I found this fellow's code: https://blog.kazade.co.uk/2014/05/a-public-domain-c11-1d2d3d-perlin-noise.html
I impl... | I think you may have a few things backwards here.
3D Perlin noise defines a noise function that takes a 3D input, to provide you with a 1D output. What you need is something that takes a 3D input, and gives you a 3D output.
You could achieve this by having 3x3D noises....
noise::PerlinOctave3D perlinX(octaves, seedX, a... |
74,230,076 | 74,231,274 | clang-tidy complains on std::string in structs | struct Thing {
std::string something;
};
Clang-tidy complains:
warning: an exception may be thrown in function 'Thing' which should not throw exceptions [bugprone-exception-escape]
I know about the bugprone-exception-escape.FunctionsThatShouldNotThrow setting, but I could not figure out what to put there to suppress... | It is a bug in the check, see https://github.com/llvm/llvm-project/issues/54668, apparently introduced with LLVM 14. Going by the issue description there isn't really much you can do except suppressing it individually for each class.
If that is too much work, you might want to consider disabling the check until they ha... |
74,230,847 | 74,231,184 | C++ passing family of objects to class | I am trying to find a way to create a generic "car" class, with children that overload the parent's methods. Subsequently, I would like to have a user class that has as a member any class in the "car" family. Is there a way to achieve the desired functionality? Thank you!
The pseudocode below shows what my intial attem... | i think you should use virtual functions inside car and a reference pointer on assigning class toyota to car, the code i written below is working good.
#include <iostream>
using std::cout;
class Car
{
public:
Car(){cout << "A car";};
virtual void method1(){cout << "from car";};
};
class Toyota ... |
74,231,073 | 74,231,198 | Is there a function that gives you index of last char substring in string? | The find() function gives you index of first char of substring in string, I need last char.
I tried to get length of substring and sum it to first index but it is going out of bound.
// if( str2.substr(last char index, str2.find(part3)))
int sizeOfPart2 = part2.length();
int sizeOfPart3 = part3.length()... | You can do something like:
const std::string path = "repeatedstrieang";
std::string mysubstr = "ea";
auto firstCharPos = path.find("ea");
if(firstCharPos!=std::string::npos)
{
std::cout << firstCharPos + mysubstr.size() -1; //-1 because indexing starts from `0`
}
|
74,231,171 | 74,231,480 | How to return compile-constant string literal with C++ constexpr function | I have a constexpr function and I'm trying to strip the file name from the __FILE__ macro, that is, remove everything but the path. I sketched up this basic function to do so, and I made it constexpr in hopes that the compiler can deduce the result and just place that calculated result as a string in the final binary. ... | Because you don't want the full __FILE__ path in the final binary, we must copy the string to a std::array:
constexpr auto get_filename()
{
constexpr std::string_view filePath = __FILE__;
constexpr auto count = filePath.rfind("\\");
static_assert(count != std::string::npos);
std::array<char, count... |
74,231,905 | 74,241,864 | How to convert Eigen Martix to Torch Tensor? | I'm new to C++.
I use Libtorch and Eigen and want to convert Eigen::Martix to Torch::Tensor, but I could not.
I wrote the code below refering to https://github.com/andrewssobral/dtt
#include <torch/torch.h>
#include <Eigen/Dense>
#include <iostream>
int main(){
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,... | By default, libtorch will imagine that the tensor you are creating is a float tensor (see at the end of the print : CPUFloatType). Since your eigen matrix is double, you want to change this behavior like this :
auto options = torch::TensorOptions().dtype(torch::kDouble);
torch::Tensor T = torch::from_blob(E.data(), dim... |
74,232,191 | 74,232,346 | i made custom strsplit function but output is weird | #include <iostream>
using namespace std;
int ft_strlen(char *str, char ascii[])
{
int i = 0;
while (!ascii[(short)str[i]] && str[i])
++i;
return (i);
}
int word_count(char *s, char *ascii) {
int i = 0, cnt = 0;
while (s[i])
{
if (ascii[(short)s[i]])
while (ascii[(s... | It's been a ghastly number of years since I've done C code, but from what I recall, this line:
char **ans = (char **)malloc(wc);
will only give you one byte for each word in the string, when you actually need a pointer's length. I believe what you actually want there is:
char **ans = (char **)calloc(wc, sizeof(char*)... |
74,232,265 | 74,232,658 | std::format errors "no matching function" and "call to consteval function" | Platform: Win 10 64 bit
IDE: CLION 2022.2.4
Toolchain: VS 2022 Community Toolset v17.0 (CMAKE 3.23.2)
Build Tool ninja.exe
C++ compiler: cl.exe
#include <iostream>
#include <string>
#include <format>
int main() {
std::wstring test1 = L"Hällo, ";
std::wstring test2;
std::cout << std::format("Hello ... | The compiler that your editor uses for highlighting and intellisense doesn't support those features yet.
std::format is a c++20 feature. According to this page it is not yet supported in Clang. This has been discussed here.
|
74,232,544 | 74,242,188 | Make clang initializing an array by copy from constant when type has volatile copy-assignment operator | I have a class similar to
class A {
public:
constexpr A(int v) : v(v) { /* logic */};
A& operator=(const A&) = default;
// This is error: the parameter for an explicitly-defaulted copy assignment operator may not be volatile
// A& operator=(const volatile A&) = default;
// This disables initializi... | This seems like a bug in Clang; while the programmer may only expect memcpy to be well-defined when used on trivially copyable types, the compiler is permitted to replace a series of simple stores to adjacent memory locations with a memcpy call when it can determine that the result will be the same, regardless of wheth... |
74,233,537 | 74,236,137 | What is function with multiple variadic args? | I don't understand how this code works. Could anyone please enlighten me a bit. I was pretty much sure "the parameter pack should be the last argument"
void foo(auto&&...args1, auto&&... args2, auto&&... args3) {
std::cout << "args1:\n", ((std::cout << args1 << " "), ...);
std::cout << "args2:\n", ((std::cout <... | The program is ill-formed and gcc and clang are wrong in accepting the code. You can also confirm this by slightly modifying your code to as shown below. There is also an old gcc bug for this.
Basically, in case of function templates(in the modifed program shown below) multiple template parameter packs are permitted, a... |
74,233,806 | 74,234,298 | Problem using boost::multi_index with composite key member functions | I have the following container:
using KeyValue = mutable_pair<Key, Value>;
using MyContainer = boost::multi_index_container<
KeyValue,
boost::multi_index::indexed_by<
boost::multi_index::hashed_unique<
boost::multi_index::tag<KeyValueTag>,
boost::multi_index::composite_key<
... |
The code compiles fine
That's because templates members aren't instantiated unless you use them. You don't have valid indexes for your element type.
Your indexes are trying the equivalent of
KeyValue pair;
unsigned Key::(*pfoo)() = &Key::foo;
pair.*pfoo
Instead of
pair.first.*pfoo;
You need accessors for KeyValue,... |
74,234,003 | 74,234,112 | Can't assign value to vector in c++ | I am trying to assign value to a vector but I keep getting different errors. I am using clang++ version 14.0.0 to build the file and I am getting the error using vs code debugger.
Here are the different erros:
When i run this code
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int>... | clang++ on Mac defaults to using C++98 (-std=c++98) and in C++98 both errors are to be expected.
Just add
-std=c++11
(or later, like -std=c++14, -std=c++17 or -std=c++20) when compiling and both your snippets will compile fine.
|
74,234,635 | 74,235,105 | C++ - Sort map based on values, if values same sort based on key | I came across a problem where I needed to store two values, one id and other its influence, and id should be randomly accessible. Also it should be sorted based on influence and if both influence are same , sort based on id. With these things in mind, I used map,but is there a way to actually do it ?
I tried below comp... | From what I understand, you want a collection sorted by one value but quickly indexable by another. These two points are in contradiction. Sorting a collection by a key value makes it quicker to index by that key value. There is no easy way to make a collection quickly indexable in two different ways at the same time. ... |
74,235,475 | 74,242,216 | Why default assignment operator is not called from assignment-from-base-class operator? | Implementing a derived class from abstract base class with assignment operator by using dynamic cast in base-to-derived assignment operator, I'd like to call derived-to-derived assignment operator. This works.
#include <iostream>
using namespace std;
class base
{
public:
virtual base& operator = (const base& ) = ... | If you want to force derived classes D to implement the function D::operator=(const base&) and you also want them to be able to have their own defaulted copy-assignment operators, D::operator=(const D&) = default;, then:
make base::operator=(const base&) pure (as you have already done), and
provide an out-of-line defi... |
74,235,569 | 74,236,310 | How to use actually use abstract classes/interface in Windows API? | I'm aware that there's no actually built-in concepts of interfaces in C++, so in order to implement it one must use abstract classes which only contains pure virtual functions.
Now, In Microsoft Windows' API list, some of the classes there like IPropertyStorage, IPropertyStorage, and IStorage are interfaces (denoted by... |
How do you actually use the interfaces from Microsoft Windows' API?
That's easy: You acquire a pointer to an interface, and start using it. And when done, you Release() it. That's COM in a nutshell.
On to the harder question then: How do you actually get hold of a COM interface pointer? Essentially, there are two way... |
74,236,010 | 74,236,143 | My code gives different results on different compilers | My code gives different results on different compilers, the following code gives 499999998352516354 when I enter 1,1000000000 as my input on vs code which is the desired results while it gives 499999998352516352 on codeforces
#include <bits/stdc++.h>
using namespace std;
int main()
{
cout<<fixed<<setprecision(90);... | Use std::llround() function around pow() and your code will work.
It is because pow() gives floating value which can be incorrectly truncated to 1 less than needed. And llround() gives correct rounding to whole integer.
Below is fixed code, I also adjusted code formatting and changed to correct necessary C++ headers.
T... |
74,236,018 | 74,236,933 | Is possible to store only 1 color per triangle in OpenGL? | When I need to set color of some triangles, I need to define every vertex as follows:
{
float x;
float y;
float z;
float r;
float g;
float b;
float alpha;
}
But in this case, every vertex will have one color.
A triangle has 3 vertex, so it need 3 colors, and most of the time, every pixel of... | Yes, this is possible by storing the colors separately from the positions. There are multiple ways of mapping the vertices to colors:
Using an SSBO. For the vertex, store only the x, y, z-coordinates. Store all colors in a Shader Storage Buffer Object and use gl_VertexID as an index into the SSBO: color = ssbo_colors[... |
74,236,048 | 74,236,162 | Euler method in c++; Values getting too big too fast | i am trying to solve the equation of motion for a particle with mass m attached to a spring with a spring constant k. Both are set to 1 however.
The algorithm looks like this:
My (attempted) solution, written in c++, looks like this:
#include <iostream>
#include <iomanip>
#include <math.h>
#include <stdlib.h>
#include... | Your equation implementation is wrong. You are usint t instead of dt. Correct variant:
x_new = x_prev + delta * v_prev;
v_new = v_prev - delta * x_prev;
And a side note if you plan to develop your code further: common approach to implementation of ODE solver is to have a method with signature similar to
Output = solve... |
74,236,323 | 74,236,390 | C++ multiple definition of function when moving to another file | I'm trying to refactor my C++ project moving some function from a cpp file (example.cpp) to another (utils.cpp) in order to sort the project and reuse the same functions in other sources.
example.cpp:
double std_dev(std::vector<double> Mean, std::vector<double> Mean2, int n,int i){
if (n==0){
return 0;
... | A function can be declared several times (i.e. just the function prototype), and may not be defined several times (i.e. with body).
This is why .h files with declarations are used and can be included anywhere, and the implementation remains in a single .cpp.
The same holds for global variables: extern declaration in a... |
74,236,714 | 74,239,114 | How to get a clicked button id from QButtonGroup in qt 6.4 through signal and slot connection | i am new to qt and what to know how to get the id of the button that is clicked in qt through signal and slot.
connect(group, SIGNAL(buttonClicked(int)), this, SLOT(buttonWasClicked(int)));
This was the earlier syntax to get the id, but qt has declared buttonClicked(int) as obsolete and it no longer allows us use it. i... | The QButtonGroup::buttonClicked(int) signal is obsoleted but you can still use QButtonGroup:: buttonClicked(QAbstractButton *). Perhaps use it in conjunction with a lambda and your existing buttonWasClicked slot...
connect(group, &QButtonGroup::buttonClicked,
[this, group](QAbstractButton *button)
{
... |
74,237,153 | 74,237,323 | Process exited with return value 3221225725 C++ | I've faced the stack overflow problem. As far as I got, the problem is in the size of a string array.
If I put 10^4 size it works fine, but if the size is increased to 10^5, it throws an error.
using namespace std;
string getRow(int dig) {
string row = "";
if (dig) {
row += getRow((dig - 1) / 26);
... | 3221225725, or C00000FD in hex, is a code Windows uses when a stack overflow occurs. string inp[100000] creates 100000 strings on the stack, which is too large.
Here's how to program this correctly
vector<string> inp;
int n;
cin >> n;
inp.reserve(n); // reserve space for the strings
for(int i=0; i < n; i++)
{
... |
74,237,380 | 74,237,458 | Are there cases in C++ where the auto keyword can't be replaced by an explicit type? | I came across the following code:
auto x = new int[10][10];
Which compiles and runs correctly but I can't figure out what would be the type for defining x separately from the assignment.
When debugging the type shown is int(*)[10] for x but int (*) x[10]; (or any other combination I tried) is illegal.
So are there cas... | The type of x is int (*)[10]. There are different ways of figuring this out. The simplest is to just try assigning 5 to x and noticing what the error says:
error: invalid conversion from 'int' to 'int (*)[10]' [-fpermissive]
13 | x = 4;
| ^
| |
| int
Or just use static_... |
74,237,474 | 74,237,877 | Is it needed to change font weight when using High DPI monitors for wxWebview in wxWidgets library? | I am working with wxWebview widget with both IE and Edge backend in Windows 10.
My understanding so far is that IE does not respect high DPI monitors and does not scale fonts respectively. So in IE backend, I must handle the DPI change event and update my font size with FromDPI().
I set the fonts in a style tag like be... | @Reza,
I suggest dropping IE backend.
IE support will retire in a couple of month and then it will be Edge only.
So as long as Edge behaves correctly - it will be OK.
|
74,237,521 | 74,237,751 | C++ Convert Number to Text With Text | i want to numbers in the text entered by the user are converted into text and printed on the screen. Example:
cin>> My School Number is 5674
and i want to "my school number is five six seven four" output like this. I make only Convert to number to text but i cant put together text and numbers please help me
#include <i... | Here is a solution.
The key line is the int charToInt = a - '0';. Here is a link to more details on that technique.
If the value returned (charToInt) is between 0 and 9, then the character is a valid integer and can be converted. If not, then just print the original character.
I also changed cin to getline (documentati... |
74,237,535 | 74,237,576 | Understanding const pointer to const reference | below is a code snippet i don't quite understand.
See the two lines with comment.
Happy for every explanation or reference to a side where i can find an explanation.
I don't quite understand whats going on and what is wrong at out = *command;
#include <variant>
struct Buffer
{
struct StructA
{
... | In
bool GetCommand(const T& out) const
{
const T* command = std::get_if<T>(&Data);
if (command != nullptr)
{
out = *command; // don't understand
out is a reference to a const object of type T. out refers to an object that can't be modified. When you try to call the assignment operator = on it,... |
74,237,761 | 74,237,982 | RAII function invoke | Is there a class in standard library that will invoke provided function in its destructor?
Something like this
class Foo
{
public:
template<typename T>
Foo(T callback)
{
_callback = callback;
}
~Foo()
{
_callback();
}
private:
std::function<void()> _callback;
};
auto rai = Foo([](){ cout << "dtor";});
| there is an experimental scope_exit
example: https://godbolt.org/z/4r54GYo33
|
74,237,841 | 74,238,109 | What would be the fastest way to find an item by a multivalued key in C++? | I will need to parse thousands upon thousands of simple entries in C++. I've only ever programmed in C, so I might be missing some higher functions to make this task easier.
An entry consists of 4 separate values: a sender, a receiver, a date, and a type of mail. Three of these are string values, the last one is an int... | I suggest defining a class with an operator< that makes it possible to store instances of the class in a std::map. The std::map can be used to map from objects comparing equal to a count. Objects are considered equal if neither lhs < rhs nor rhs < lhs is true so only the operator< overload is necessary.
You could also... |
74,238,462 | 74,238,533 | How to call a function returning a function pointer? | I am trying to call a function pointer using an explicit dereference. But the compiler throws an error:
no operator "*" matches these operands.
Here's a simplified version of my code:
#include <functional>
#include <iostream>
int add(int a, int b)
{
return a + b;
}
std::function<int(int, int)> passFunction()
{
... |
I'm trying to call a pointer function using a explicit dereference. But compiler throws an error: 'no operator "*" matches these operands'.
Type matters!
The return type of the passFunction is not a pointer, rather std::function. It is not something of dereferencable. Hence, you get the compiler error.
The thing is... |
74,238,517 | 74,238,659 | Computing data on the fly vs. pre-computed table | A common technique to save some time is to use a table of pre-computed values, instead of computing the value every time on the fly. For example, for an integer approximation of the logarithm.
Could it happen that fetching a value for the first time will actually be slower than computing it because the table is far awa... |
Could it happen that fetching a value for the first time will actually be slower than computing it because the table is far away in memory (the DATA segment) and the access causes a page load?
Yes, it can happen. Whether a page load occurs is not the only consideration. This question is hugely dependent on system arc... |
74,238,912 | 74,242,494 | How to copy entire vector into deque using inbuilt function? (in C++) | I want to know that is there any inbuilt function to do this task
vector<int> v;
deque<int> d;
for(auto it:v){
d.push_back(it);
}
I just know this way to copy the values of a vector in deque and I want to know is there any inbuilt function to perform this task
| As Pepijn Kramer said in the comments 1 and 2, you can use the overload (2) for the assign member function that takes a range
d.assign(v.begin(),v.end());
or use the iterator-range constructor, overload (5)
std::deque<int> d{v.begin(),v.end()};
Or in C++23, you can do
auto d = std::ranges::to<std::deque>(v);
|
74,240,374 | 74,240,488 | MSVC insists on using inaccessible member from private-inherited base class, although it was re-defined as public | Consider this code (godbolt example):
#include <cstddef>
template< std::size_t... sizes >
class Impl
{
public:
static constexpr std::size_t
getDimension()
{
return sizeof...( sizes );
}
};
template< std::size_t... sizes >
class Wrapper : private Impl< sizes... >
{
using BaseType = Impl< si... | An ugly workaround exists. First, you might define an external template function for delegating to the proper class:
template<typename T>
constexpr std::size_t getDimension()
{
return T::getDimension();
}
This is so that MSVC's name resolution won't try to search in the private base classes. Then, you might write:... |
74,240,401 | 74,240,606 | Segmentation fault (core dumped) C++ error Process returned 139 (0x8B) | can someone please explain what's wrong with this code? I'm getting this error in console when I try to run the program.
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int main()
{
vector<int> nums = {2,1,9,4,4,56,90,3};
int target = 8;
unordered_map<int,int> m;
... | I bet you are doing two sum question. The reason for segmentation fault is find() may not always find your req_num in the map. By solving this problem, I modified your code and it works properly.
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int main()
{
vector<int> nums = {2... |
74,240,461 | 74,248,581 | QT - Draw a point at a user specified location in a 3D surface | I was going through the Surface example here
When the user clicks anywhere it draws a point
image surface
what i'd like to know is how to do this programatically,like, if a user gives 3 coordinates x, y, and z. How do I go about plotting such point?
| you can add a custom item like so:
QImage color = QImage(2, 2, QImage::Format_RGB32);
color.fill(Qt::cyan);
QVector3D positionOne = QVector3D(2.0f, 2.0f, 0.0f);
QCustom3DItem* item = new QCustom3DItem(":/items/monkey.obj", positionOne,
QVector3D(0.0f, 0.0f, 0.0f),
QQua... |
74,240,755 | 74,240,991 | Loading process and loading screens | Well, the purpose of the loading screens is to display to the user that data is being loaded (downloaded) in the background.
But where can you make loading screens, can you do it on every program as startup for example and how to do so?
| Once you have learned to display windows on the screen, you simply... display a window on the screen, with a progress bar, and every time your program loads something, you make the progress bar bigger.
This only makes sense if your program loads lots of things when it starts (such as large pictures or game levels). You... |
74,241,025 | 74,241,116 | My sorting algorithm doesn't function due to unknown reason | I'm trying to create a sorting algorithm, it contains a nested loop which compares each element of the array to all other elements in the array, and if an element is greater in value than any of its succeeding elements, they switch places with each other. But for some reason my program won't output anything and exits w... | It is not the bubble sort algorithm You are trying to implement the selection sort algorithm with redundant swaps.
These for loops
for(int j=i+1; j<=n; j++){ //O(n^2)
and
for(int x; x<=n; x++){
have invalid conditions that in general can result in undefined behavior if the passed array will have exactly n elements be... |
74,241,402 | 74,241,542 | How to default values to array when user input enter key using cin method? | I am writing a code where I am asking user to assign value to an array and where user press enter key I want to assign a default value to array elements. Any idea how to proceed with this ?
I have tried using cin.get() method but it is not working. Here is my code :
#include<iostream>
#include<math.h>
#include<cmath>... | I've tried to change minimal things to make your code work as you've expected. Bunch of stuff can be improved, array creation (see this), not including useless files, reducing the scope of local variables, also don't use using namespace std - see this.
#include <math.h> //useless
#include <cmath> //useless
#include <i... |
74,241,779 | 74,243,406 | Creating std::span from pybind array | void createSpanfromNumpy(pybind11::array_t<int>& inputA, std::vector<int>& inputB)
{
auto addressA = inputA.data();
auto addressB = inputB.data();
std::span<int> testSpanA{ inputA.data(), inputA.size()};
std::span<int> testSpanB{ inputB.data(), inputB.size() };
//do stuff with span
}
Trying t... | inputA.data() is a const int*.
Use a std::span<const int> or use pybind11::array_t::mutable_data.
|
74,241,829 | 74,242,022 | Create directory but only when not running from floppy | I'm trying to get my application to create a directory if it doesn't exist, but only if the application isn't running from a floppy drive. I'm making the assumption that drives A: and B: are floppies.
The code I'm using is as follows:
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char filen[_MAX_FNAME];
char ext[_MAX_EX... | You have "typos", in particular, your || should be &&:
toupper(drive[0]) != 'A' && toupper(drive[0]) != 'B'
which is equivalent to
!(toupper(drive[0]) == 'A' || toupper(drive[0]) == 'B')
|
74,241,837 | 74,241,953 | MSVC CRT Debug Heap assert passing C++ STL object across binary boundaries | We have a host application and a DLL both built with the same compiler settings etc both using the static CRT /MT. (tested with VS2019 and VS2022)
Eventually we pass some simple structs that contain a couple STL objects, for example
struct MyData
{
std::vector<std::string> entries;
};
...
MyData DLL::getMyData() c... | The simplest way to fix this is usually just to DLL export the MyData class (from memory defining the dtor as virtual can also fix this problem). Without that, because the dtor is inline, you are getting two copies of the dtor, one in the original DLL, one in exe. DLL::getMyData() is creating a new instance using the h... |
74,242,934 | 74,243,010 | How do I distinguish -std=c++17 and -std=gnu++17 at compile time? checking macros? | I am using the __int128 extension of g++. The problem with -std=c++17 is that some of the C++ library does not have all the support for that extension (i.e. std::make_unsigned<> fails). When using -std=gnu++17 it works fine.
I've added a header file that allows for the <limit> to work with __int128 when using -std=c++1... | I did this:
$ diff <(g++-11 -std=c++17 -E -dM -x c++ /dev/null|LC_ALL=C sort) \
<(g++-11 -std=gnu++17 -E -dM -x c++ /dev/null|LC_ALL=C sort)
And the output was:
180a181,182
> #define __GLIBCXX_BITSIZE_INT_N_0 128
> #define __GLIBCXX_TYPE_INT_N_0 __int128
315d316
< #define __STRICT_ANSI__ 1
424a426,427
> #define... |
74,243,826 | 74,244,054 | GMock EXPECT_CALL returns FAILED while comparing two char arguments inside the method | As the tittle, I'm using gmock to test my feature. But one of the issue occurred that EXPECT_CALL always check address of 2 char array instead of their value.
Below is my code example:
Base.h
//Create singleton class
class Base {
private:
static Base* _ptrInstance;
public:
static Base* getInstance();
void sendS... | With
EXPECT_CALL(*BaseMock, sendString("hello_world", 0));
You compare pointer.
According to reference/matchers.md, You might use StrEq
EXPECT_CALL(*BaseMock, sendString(StrEq("hello_world"), 0)));
|
74,243,898 | 74,243,979 | How can I pass bass and it's derived classes object's in a same method? | Let's say I've a class fruit and several class like apple,mango etc,Now i want to create a single function that would accept fruit and it's all derived classes object's as argument,How can i do so?
I have not tried anything yet!
| You can make the function parameter to be a reference or a pointer to the base class as shown below.
void eat(const Fruit* f)
{
//code here
}
Or
void eat(const Fruit& f)
{
//code here
}
You can remove the low-level const if you want to be able to make changes through f.
|
74,243,962 | 74,244,060 | Copy data to struct in a serial way in C++ | I have a packed struct like this one below
struct MyStruct
{
uint8_t a;
uint32_t b;
uint16_t c;
uint8_t d[4];
uint16_t e[2];
uint32_t crc_field;
} __attribute__((packed));
I want to store data to it in a serial way, meaning that I want to use memcpy or for loop to copy data from an array into t... | The MyStruct class is trivially copyable. It means that you can safely copy its byte representation in a buffer, and when you will copy back that representation into a MyStruct object, that object will take the original value. No need for an union here.
Simply, as the representation of scalar type is not defined in the... |
74,244,055 | 74,250,856 | In C++ get smallest integer type that can hold given amount of bits | If I have compile time constant num_bits how can I get smallest integer type that can hold this amount of bits?
Of course I can do:
Try it online!
#include <cstdint>
#include <type_traits>
std::size_t constexpr num_bits = 19;
using T =
std::conditional_t<num_bits <= 8, uint8_t,
std::conditional_t<num_bits <= 1... | There is currently no template type for this in the c++ standard library.
The standard library does have something to do the reverse of what you're looking for (std::numeric_limits<T>::max).
There is a proposal to add such functionality to the c++ standard library in p0102: "C++ Parametric Number Type Aliases". A simil... |
74,244,075 | 74,244,239 | When I try to use string.insert() it tells me there is a length error at memory location... How do I fix this? | #include <iostream>
#include <string>
#include <cstring>
using namespace std;
string empty(string str) {
for (int i = 0;i < str.length();i++) {
if (str[i] == ' ') {
str.insert(str[i], ",");
}
cout << str[i];
}
return st;
}
int main() {
... | You are getting a runtime error because the 1st parameter of insert() expects an index but you are passing it a char instead, and your input string happens to contain a character whose numeric value is larger than the string's length.
After fixing that, you will then run into a new problem with the loop getting stuck r... |
74,244,875 | 74,255,124 | Access vertex via vertex_index property? | Is there a built-in way in BGL to access a vertex via its vertex_index property?
using VertexProperties = boost::property<boost::vertex_index_t, int>;
using DirectedGraph = boost::adjacency_list<
boost::listS,
boost::vecS,
boost::directedS,
VertexProperties,
boost::no_property>;
using VertexDescriptor... | By far the most user-friendly solution in this realm is to use internal name properties. This is a mixin-feature for boost::adjacency_list (implemented in maybe_named_graph).
Moreover, your approach "repurposing" vertex_index_t for this is probably misguided: vertex indices are a library "contract" which assumes that i... |
74,245,830 | 74,246,419 | Unexpected termination after the first input | When I put 1000000000000 as the input the program terminates, and does not allow the user to enter x.
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int arr[n];
int x;
cin>>x;
int k=0;
for (int i = 1; i <= n; i+=2)
{
arr[k]=i;
k++;
}
for (int j = 2; j <= n; j+... | Your program has some errors, which even do not allow for compilation.
I added comments to your source code to show yout the problems:
#include <bits/stdc++.h> // This is not a C++ header. it is a comiler extension. Do not use it
using namespace std; // Do not use it. Always use scoped identifiers
int main() ... |
74,245,946 | 74,245,968 | Change color of single entity in OpenGL scene? | I'm trying to change the color of a single polygon shape (quads) in my exercises using legacy OpenGL (Freeglut+Glew), but obviously when i call glColor3f the colors of the entire models (texts included) in the scene get overwritten by the new color state set by the function.
The code is fairly simple:
void drawScene(vo... | glColor3f sets a global state. This state is kept until it is changed again. Set the state explicitly before each object. Alternatively, you can reset the color attribute to "white" after drawing an object.
glColor3f(colors.r, colors.g, colors.b);
glBegin(GL_QUADS);
glVertex3f(-2.0, 2.0, 0.0);
glVertex3f(-2.0, -2.0, 0... |
74,246,134 | 74,252,704 | Single-token and multi-token positional options with boost::program_options | I am writing a program that would receive as parameters a filename followed by multiple strings. Optionally it could take a -count argument;
./program [-count n] <filename> <string1> <string2> ...
This is the code I wrote:
PO::positional_options_description l_positionalOptions;
l_positionalOptions.add("file", ... | I figured it out. It's as dumb as it can get.
The issue was that I had a , after every entry in add_options().
This made it so only the first entry would get saved.
|
74,247,792 | 74,248,420 | Scale object in 2d to exactly overlay itself | I am trying to render an outline using Vulkan's stencil buffers. This technique involves rendering the object twice with the second one being scaled up in order to account for said outline. Normally this is done in 3D space in which the normal vectors for each vertex can be used to scale the object correctly. I however... | Lets draw an example of a single point of some 2D polygon.
The position of point M depends only on position of A and its two adjacent lines, I have added normals too - green and blue. Points P and Q line on the intersection of a shifted and non-shifted lines.
If we know the adjacent points of A - B , C and the distanc... |
74,247,829 | 74,248,282 | Can Cmake add 'time' before ./main in the command line to measure program execution time? | I am wanting to measure the time it takes for my C++ video processing program to process a video. I am using CLion to write the program and have Cmake set up to compile and automatically run the program with a test video. However, in order to find execution time I have been using the following command in the MacOS term... | It is possible to use add_custom_target to do what you want. I'll not consider this option further as it seems abusing the build system for something it wasn't designed to do. Yet it may have an advantage over using CLion configuration: it would be available to be used outside of CLion. That advantage seems minor: why ... |
74,248,524 | 74,249,421 | Trouble reading integer metadata from file | Trying to read the file size data from a bitmap file. I know that I have the offset (0x02) correct and can find the correct file size in a hex editor.
uint32_t getBMPSize(string bmpPath) {
char sizeread[2] = {};
uint32_t size;
ifstream bmpFile;
bmpFile.open(bmpPath);
uint16_t offset = 0x02;
... | Thanks. Fixed by reading directly to uint32_t using bmpFile.read(reinterpret_cast<char*>(&size), 4).
|
74,249,383 | 74,249,457 | std::condition_variable not working with std::this_thread::sleep_for() | Could someone explain why this code does not work as expected when the sleep call in producer() is uncommented? It works fine if the sleep call is moved out of the scope of the unique_lock.
To clarify:
Working as expected: producer() creates new messages that are stored in data those messages are then printed by consum... | Each iteration of the while loop in the producer thread takes a lock, computes data, sets ready=true, and then unlocks before repeating.
In the case of the sleep statement being uncommented out:
Since the mutex is still held by the OS while sleep is invoked, both the producer and consumer thread are effectively paused ... |
74,249,425 | 74,249,528 | C++: Have a class always cast as specified type | So I am not sure if this is at all possible in C++, but I would like to ensure that a class is always cast as another type by default.
Here is an example of what I would imagine this looks like:
class A : public always_cast<std::string> {
private:
std::string *actualData = new std::string("foo");
public:
operat... | What you're talking about is broadly conceptualized as the ability to overload "operator dot" in a similar way to how we can overload operator*. There have been many proposals in years past on providing this feature to C++, but none of them achieved consensus. My read of the committee is that, like UFCS, they've basica... |
74,249,667 | 74,249,685 | Why are normal C-array indices signed while stl indices are unsigned? | I understand why stl indices are unsigned, because you would never have a negative index. But for normal C arrays, the indices are signed. Why is this?
If there is a good reason for C array indices to be signed, why did they decide to make stl indices different?
| Array indexing in C is really just a pointer offset. x[y] is exactly the same as *(x + y). That allows you to do things like this:
int a[3] = { 1, 2, 3 };
int *p = a; /* p points to a[0] */
printf("p[1]=%d\n", p[1]); /* prints 2 */
p += 2; /* p points to a[2] */
p... |
74,250,094 | 74,256,115 | partial template specialization and deduction guides | I have a question on when deduction guides need to be specified, in particular why explicitly defining the constructor in the base template below removes the requirement for it. IOW, either the constructor in the base template needs to be defined or the deduction guide is needed for the snippet below to compile. I'm gu... | Class template argument deduction uses a set of implicit guides synthesized from the primary template definition, plus any explicit deduction-guides declared for the class template.
The partial specialization of Type does not participate in the generation of implicit guides. Nor would any explicit (full) specialization... |
74,250,649 | 74,250,775 | How to split strings and pass them to class vectors from file | For my university class in programming we have been working on Object Oriented Programming (OOP) and are currently working on a group project. The project is to create a cash register that holds items with their names, amounts, and prices. As well as have a way to track the coins given by the user then determine the co... | You are trying to do too many new things at once. Break the problem into pieces and solve them separately, then combine them. To break the string into pieces you can use find and substr, you just have to be careful and debug until you're sure it's working perfectly:
string s = "45 1.50 Chocolate Chip Cookies";
cout << ... |
74,250,767 | 74,293,147 | CMake output configured with vscode not running in terminal | Okay so I am new to using CMake and I was trying to get it to work in vscode. I am using the extension CMake Tools to run the build and configuration. I'm running a basic hello world program that writes an output as well to test everything out and what happens is when the executable produced gets run from the terminal ... | Okay so switching from MinGW to Mingw-w64 with MSYS2 everything works as expected to work. Not sure what caused this problem in MinGW though.
|
74,250,832 | 74,250,907 | how can i slice a V_BSTR in c++? | Am working on active Directory and I need to retrieve the userAccountControl attribute and check for an option so I used get method as follows
VARIANT var;
VariantInit(&var);
hr = pUsr->Get(CComBSTR("userAccountControl"), &var);
and stored it in an variant then converted it to V_BSTR to print the result..
if (SUCCEED... | You can convert the BSTR to std::wstring,
and then use std::wstring::substring to extract the last 3 characters:
#include <atlbase.h>
#include <assert.h>
#include <string>
#include <iostream>
int main() {
VARIANT var;
VariantInit(&var);
var.bstrVal = CComBSTR("0000000000010200");
// Convert BSTR to st... |
74,250,866 | 74,251,140 | Find digit in an integer at user requested position | I am trying to take a user entered integer (positive or negative) and let them pick a digit position and output the digit at that position.
int findDigAtPos(int number)
{
int position;
int result;
cout << "Enter digit position between 1 and " << std::to_string(number).length() << endl;
cin >> position;... | First, note that you shouldn't be using the pow function when working with integers, because it returns a double result, which can cause problems due to unexpected truncation of the result.
But, if you insist on using it, then you need to remember that the power of 10 by which to divide will decrease as the digit posit... |
74,251,092 | 74,251,401 | Get clicked item on QTreeWidget | class TreeWidget : public QTreeWidget
{
Q_OBJECT
public:
TreeWidget(QWidget* parent = 0) : QTreeWidget(parent)
{
connect(this, &QTreeWidget::itemClicked, this, &TreeWidget::onItemClicked);
}
public slots:
void onItemClicked(QTreeWidgetItem* item, int column)
{
auto _item... | In your code item: 0x2a64e3edfb0 is your object and 0x2a64e3edfb0 is your object's address in memory.
But your QTreeWidgetItem object has functions and properties like its text and you can get it like this:
void MainWindow::on_treeWidget_itemClicked(QTreeWidgetItem *item, int column)
{
qDebug() << "item: " << ite... |
74,251,265 | 74,251,324 | what is V_VT and what does it return? | Am working in Active Directory and i get to know that V_VT is used to get the type of the variant but when i used it and print it it shows 3 and what exactly does that mean? where can i fnd the documentation about it?
VARIANT var;
VariantInit(&var);
hr = pUsr->Get(CComBSTR("userAccountControl"), &var);
if (SUC... | I think you should not be using VT_V at all (macros are not typesafe)
V_VT(x) provides (as documentation states) a "convenient shorthand" to access VARIANT fields. E.g.V_VT(&vtXmlSource) = VT_UNKNOWN; is equivalent to
vtXmlSource.vt = VT_UNKNOWN;
BSTR's are wide character strings (with different allocator/deallocator),... |
74,253,209 | 74,253,249 | If the ownership is moved from one unique pointer into another, is calling the method of the earlier object an undefined behavior? | If the ownership is moved from one unique pointer into another, why can I call the method of that object, from which the ownership was transferred? In the example: why can I call the foo method of p1 pointer? Isn't this an undefined behavior?
#include <iostream>
#include <memory>
class Car {
public:
int data{42};... | You can make that call because it's valid syntax. That doesn't mean it isn't also undefined behavior.
Take a look at the unique_ptr move constructor (the 5th one on that page). It says:
stores the null pointer in u
This means, in your example, after the move, p1 stores a null pointer. So, dereferencing it in any way ... |
74,253,748 | 74,255,031 | How to get a userAccountControl Attribute in active directory | Am working on active directory and i need to get a value of a checkbox in userAccountControl
and want to know if the check box is checked or not..
I tried to get the value of it by using the code
VARIANT var;
VariantInit(&var);
hr = pUsr->Get(CComBSTR("userAccountControl"), &var);
if (SUCCEEDED(hr)) {
... | You want to look at the pwdLastSet attribute. The documentation for that says:
If this value is set to 0 and the User-Account-Control attribute does not contain the UF_DONT_EXPIRE_PASSWD flag, then the user must set the password at the next logon.
So two things must be true to force a password change on next logon:
... |
74,253,913 | 74,254,068 | How can I tell rust two traits have the same type? | I'm trying implement C++ adjacent_difference algo for rust iterator. std::adjacent_different by default uses the current value in a container subtracts its previous value, something like, if we have [5, 7, 16], then after adjacent_difference, we get [5, 7-5, 16-7]
I try to do it in rust as an iterator extension, but fo... | There are multiple ways you can tackle this.
For example, one option is just to specify the subtraction has the same type as the element itself:
impl<I> Iterator for AdjacentDifference<I>
where
I: Iterator,
I::Item: std::ops::Sub<Output = I::Item> + Copy,
{
type Item = <<I as Iterator>::Item as std::ops::Su... |
74,254,176 | 74,255,044 | sentinel node in cpp list does not work as expected | I am writing cpp-11 and want to create a list of list based on the data received. The data structure is std::list<char, std::list<char, int>>. The outer list stores a list of inner lists, and when several successive inner lists have the same label, then they should be grouped together, otherwise a new entry is created.... | Make it work first and then try to make it works better.
Here is a revision with sentinel nodes removed. Try to add it back and compare with your code.
#include <list>
#include <tuple>
#include <iostream>
using profileLoc = std::pair<char, size_t>;
using profileGrp = std::pair<char, std::list<profileLoc>>;
class MyIn... |
74,254,508 | 74,254,844 | C++ Why can't I get into an if condition if the statement is true? | I made a for loop in the constructor that goes through XML elements of bricks and creates the brick depending on what the Id is.
I even checked typeid in case mId wasnt a char but it's const char*. The std::cout << "Made it in"; never triggers. Here is the code:
Brick::Brick(int rowSpacing, int columnSpacing, const cha... | C Strings are character arrays and not first-class datatypes in C++ (is C as it happens(. As such you cannot use comparison operators on them. Semantically you are comparing the value of two pointers, not the content of two strings.
To that end, you either need a C-String comparison:
if( strcmp(brickElement->FirstChi... |
74,255,969 | 74,256,184 | How to store cout in string and then output the string to console? | I am trying to store the output of my program in a file, and even though I know there are various much simpler methods, I want to solve the problem using strings since I would like to know the logic behind it.
So far, I understand the implementation:
std:: stringstream s;
s << "string";
and I know at some point I will... | If your goal is to redirect std::cout to a std::string, you can use the cout.rdbuf() method to give std::cout a different buffer to write to, such as the buffer of a std::ostringstream (or a std::ofstream, etc).
The above linked documentation provides the following example of exactly this:
#include <iostream>
#include ... |
74,256,005 | 74,256,574 | Padded Structs (C++) | I have an 18 byte struct in C++. I want to read 18 bytes of data from a file straight into this struct. However, my C++ compiler pads the struct to be 20 bytes (4 byte aligned). This is relatively easy to get around for just my compiler alone but I would prefer to use a method that is more reliable cross-platform/cross... | You have several options, and as usual, you should choose whatever best fits your needs:
as stated before, don't read/write directly from/to memory, instead write each field separately (kind of how Java people would).
This is the, I think, most portable, but WAY slower than the later methods.
reorder the struct to ma... |
74,256,770 | 74,256,828 | Is ostream& operator<< better practice in a class than using std::cout? | In a Linked List class, I created a display method to print out the Linked List as it is currently formulated like so:
void LinkedList::display() {
Node* curr = m_head;
while (curr) {
std::cout << curr->n_data << " -> ";
curr = curr->n_next;
}
std::cout << std::endl;
}
One of the TA's who grad... | The simplest solution in this case would be to add a std::ostream parameter to your display() method, eg:
void LinkedList::display(std::ostream &out) const {
Node* curr = m_head;
while (curr) {
out << curr->n_data << " -> ";
curr = curr->n_next;
}
out << std::endl;
}
LinkedList list;
...
list.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.