question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
73,752,861 | 73,752,982 | Is there a way to append to global unordered_map from C++ file on compilation? | The problem
I want to make a little module system for my project, which will basically be a base class that users may extend with their code, include in the main project and be able to use this module in runtime.
E.g. we have a Renderer module, the base class defines all the mandatory functions to implement:
class Rend... | If you are using C++17 you could use a static inline (otherwise useless) member variable in some class to make sure the function is called, e.g. like this:
class Foo {
static inline void * bar_ = AppendVkRenderer();
};
But you might have to modify parts of your code to make sure s_RendererModules is initialized be... |
73,752,880 | 73,753,449 | What is the problem with fill() here ? I used normal for loop for assigning NULL and it worked , with fill() it was giving error | The code below is a Trie implementation in C++. Kindly checkout what is the problem in using fill(). And if any suggestions improving my implementation are welcome
Commented fill() in the TrieNode constructor function function is giving compile time error as mentioned in the snippet . Why this is behaving wierd with fi... | First, we convert your code tor a MRE.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
class TrieNode {
public:
std::vector<TrieNode*>vec;
bool end;
TrieNode() {
vec.resize(26); end = false;
std::fill(vec.begin() , vec.end(), NULL); // did not worked
}
b... |
73,753,498 | 73,753,578 | Calling a C file in C++ is giving errors | The reproduceable error code is:
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//#include <cstring>
//functions
#define true 1
#define false 0
#ifdef _MSC_VER
// define POSIX function strndup if not available
char* strndup(const char* s, size_t... | It seems you want to write code in plain C and then have the split function callable from C++.
Then you first of all need to make sure to build the source as plain C, which includes making sure the source file have a .c suffix, and not contain any C++ code (like the extern "C" part, or C++ header files like <cstring>).... |
73,753,596 | 73,753,709 | Why is my iterator not std::input_iterator? | Why doesn't the iterator below satisfy std::input_iterator concept? What did I miss?
template <class T>
struct IteratorSentinel {};
template <class T>
class Iterator
{
public:
using iterator_category = std::input_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using poin... | Your operator* is not const-qualified.
The std::input_iterator concept (through the std::indirectly_readable concept) requires that * can be applied to both const and non-const lvalues as well as rvalues of the type and that in all cases the same type is returned.
|
73,753,610 | 73,754,835 | Cannot open source file endian.h error – what is the problem? | Ever since updating to the Ventura public beta I keep getting these kinds of errors:
"cannot open sources file "endian.h" (dependancy of "iostream")"
I also keep getting prompts that clang++ requires the command line tools which I have already installed (when I run xcode-select --install it says that they are alr there... | Try to go to https://developer.apple.com/download/all/ and
look for: "Command Line Tools for Xcode 14.1" in the list of downloads then click the dmg download and install it
|
73,753,966 | 73,754,139 | Unable to convert std::string into std::basic_string<char8_t>, why? | I am facing the following problem, I am trying to convert an std::string object into an std::basic_string<char8_t> one, using the codecvt library. The code is the following:
#include <string>
#include <codecvt>
#include <locale>
int main()
{
std::string str = "Test string";
std::wstring_convert <std::codecvt_utf8... | C++ keywords: char8_t (since C++20)
As far as I understand char8_t is of char type as is your std::string. A simple cast should work.
|
73,754,094 | 73,756,015 | Why does `LD_DEBUG=libs` fail to display a library that loaded in an application? | Background:
I am trying to discover where libqbscore.so is loaded from, and when it happens. When I set LD_DEBUG=libs and run the program, /bin/qtcreator, I do not find libqbscore.so amidst the debug.
If however, I set LD_PRELOAD=/path/to/libqbscore.so, then I will start finding its occurences in the output.
Question:
... | It's because the qtcreator process does not load the libqbscore.so. The qbs child process loads it.
Because Qt Creator and Qbs are open source projects, their interactions can be analyzed by analyzing the source codes.
|
73,754,698 | 73,755,308 | How to create a common range? | Why doesn't std::ranges::common_view compile in the code below?
#include <ranges>
#include <vector>
#include <algorithm>
template <class T>
struct IteratorSentinel {};
template <class T>
class Iterator
{
public:
using iterator_category = std::input_iterator_tag;
using value_type = T;
using difference_t... | Your range is built out of an iterator/sentinel pair. The definition of a common range is a range where the sentinel type is an iterator. So the range itself is not a common range.
common_view can generate a common range from a non-common range. Which means that it will have to create two iterators. And since it starts... |
73,754,872 | 74,079,195 | SDL_DrawRect() does not draw a proper rect | When I try to draw a rectangle, the bottom line always is one pixel up on the right side:
The problem also persists when I change the size and position.
Below I have a minimal working solution that should reproduce the problem, if it's not my computer going crazy:
#include "SDL.h"
#include <iostream>
int main(int ar... | It seems like I solved the problem by changing from the Flatpak version of CLion to the native one installed from the JetBrains toolbox.
The problem only occurs when I run the compiled executable from inside CLion, so I think it's a CLion problem. I reported the problem to JetBrains here.
|
73,755,207 | 73,768,313 | Override std::tuple serializing functionality in boost::json | boost::json::tag_invoke works fine with structs, but is totally ignored with std::tuple.
Look the next example and mind how the two json arrays are diferent:
Coliru link: https://coliru.stacked-crooked.com/a/e8689f9c523cee2a
#include <iostream>
#include <string>
#include <vector>
#include <boost/json/src.hpp>
using na... | These functions are found via ADL. With std::tuple<double, double, int>, only overloads in the std:: namespace are searched, which your overload is not in, so it isn't found.
Boost suggests to either put it where ADL can find it, or in the boost:: namespace if not possible.
So you can put it in the boost namespace:
nam... |
73,755,655 | 73,756,437 | Code Exiting on above 500,000 number of input | I was performing sorting algorithm to calculate their runtime to execute, in which I was giving millions of number of input to sort, but my code is exiting on above 500,000 input and not showing any output. Is there anyway I can solve it.
int size;
cout<<"Enter size of the array: "<<endl;
cin>>size;
int a[size];
for(in... | You code crashes on 500'000 input because of stack overflow, you're allocating array on stack of too big size:
int a[size];
Stack size is usually few megabytes at most.
Also it is probably an extensions not of all compilers to have dynamically allocated array on stack, usually size should be a compile time constant.
To... |
73,756,141 | 73,760,102 | SDL doesn't render BMP image on mac | I have the following code in main.cpp:
#include <SDL2/SDL.h>
#include <iostream>
int main(){
SDL_Init(SDL_INIT_VIDEO);
bool quit = false;
SDL_Event event;
SDL_Window * window = SDL_CreateWindow("Chess",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 720, 640, 0);
SDL_Delay(100);
SDL_R... | As documentation says
The backbuffer should be considered invalidated after each present; do
not assume that previous contents will exist between frames. You are
strongly encouraged to call SDL_RenderClear() to initialize the
backbuffer before starting each new frame's drawing, even if you plan
to overwrite every pixe... |
73,756,285 | 73,756,504 | Is it OK to use lambda function parameter as a constant expression? | Why in this example the first call doesn't compile and the second one compiles?
consteval auto foo(auto x) {
static_assert(x);
}
int main(){
foo(42); // error: non-constant condition for static assertion
foo([]{}); // OK
}
If I understand correctly, the first one is wrong due to lvalue-to-rvalue convers... | static_assert(x); while passing []{} works, because a capture-less lambda has a conversion operator to function pointer and a function pointer can be converted to a bool (which is going to be true for everything but a null pointer which the conversion can't return).
An expression is a core constant expression as long a... |
73,756,505 | 73,757,504 | Qt6 Docker Ubuntu22.04 CMake Failed to find Qt component "Widgets" | I'm trying to build a small Qt6 application on a Docker container. It is running on Ubuntu:22.04. I have installed the qt6-base-dev package. Here is my small test app:
#include <QApplication>
#include <QWidget>
#include <iostream>
int main(int argc, char argv)
{
QApplication app(argc, argv);
QWidget widget;
... | I have installed libgl1-mesa-dev and libglvnd-dev and it worked perfectly !
|
73,756,597 | 73,756,922 | C++ Elliptic Integral of first kind | I'm working on a program that makes calculations in C++; one of which involves using the complete elliptic integral of the first kind.
Python and Mathematica produce these results
Python:
from scipy import special
print(special.ellipk(0.1))
print(special.ellipk(0.2))
print(special.ellipk(0.3))
with output
1.6124413487... | Elaborating on Steve's answer: there is no mistake or inaccuracy (select isn't broken). They are simply using different normalizations.
Specifically, if you carefully read the documentation, C++'s std::comp_ellint_1(k) returns
whereas Python's scipy.special.ellipk(m) returns
Note the k^2 versus m. So to get the re... |
73,756,772 | 73,757,959 | What is the issue in this inheritence cpp problem | class Temporary_Employee: public Employee{
//consolidated monthly pay
public:
int con_pay;
int sal;
Temporary_Employee(string name,int num,string des,int cp) :Employee(name,num,des){
con_pay=cp;
}
void salary(){
sal=con_pay;
}
void di... | It seems like you need make the data members in you "Employee" class as public. like this
Employee(...){
public:
{data members}
}
|
73,757,090 | 73,757,575 | Create matrix (2d-array) of size specified by parameter input in C++ | I am learning C++ with experiencein mostly Python, R and SQL.
The way arrays (and vectors which differes somehow from 1d-arrays? and matrices which are 2d-arrays?) work in C++ seems quite different as I cannot specify the size of dimension of the array with an argument from the function.
A toy-example of my goal is som... | Following your comment, I can see why you are confused in your attempts to use a matrix in code.
There are many types of containers in C++. Many of them you can find in the standard library (std::vector, std::list, std::set, ...), others you can create yourself or use other libraries. Plain arrays (like int a[5]) are a... |
73,757,346 | 73,757,438 | Global vector data disappearing when executing another function | I am facing a problem with global a vector. I actually have a vector of vectors of pairs, and I declared it as a global variable.
vector<vector<pair<int, float>>> numbers;
In the main function I do some push_backs passing a vector os pairs as an argument, which works just fine.
numbers.push_back(VectorOfPairs);
The pr... | you have a variable called numbers in main, and you pass this as an argument to those functions. That 'numbers' has nothing to do with the global valiable of the same name.
|
73,757,548 | 73,757,811 | Strange behavior with function that converts a vector2 to an angle in degrees | I am attempting to get a gun to rotate around the player based on a vector2 input
if the y component of the vector is positive it works perfectly as you can see here
Working as intended (Ignore my placeholder graphics)
if the y component is negative however, it returns the same value as if the y value was positive
Not ... | I'm unsure what you're after but I think you want the angle between v.x and v.y scaled to 0-512. In that case:
#include <cmath>
#include <numbers>
// ...
float angle = std::atan2(v.y, v.x);
if(angle < 0.) angle += 2 * std::numbers::pi_v<float>;
return angle * 512 / (2 * std::numbers::pi_v<float>);
// return angle * 2... |
73,757,693 | 73,757,808 | Precedence between multiple different operators Order of evaluation | I have some problems with how an expression Order of evaluation is executed.
int x = 1;
int y = 2;
int z = ++x || y++; // how this expression actually executed?
cout << x << " " << y << " " << z;
output: 2 2 1
I know if started from left to right with ++x it was evaluated and a short circuit will be ... | Order of evaluation and operator precedence are not the same thing.
Operator precedence here tells us that the expression ++x || y++ is equivalent to (++x) || (y++) rather than some other placement of parentheses, but that still doesn't tell us in which order the subexpressions are evaluated and operator precedence is ... |
73,758,012 | 73,758,063 | How to return an array in a function in cpp | This is my code
*int my_arr(int a) {
int arr[a];
for (int i = 0; i < a; i++) {
cin >> arr[i];
}
return arr;
}
I keep getting errors
| You can't return an array in cpp. Instead use vectors.
vector<int> my_arr(int a) {
vector<int> arr;
for (int i = 0; i < a; i++) {
int input;
cin >> input;
arr.push_back(input); // to push elements into vector
}
return arr;
}
|
73,758,079 | 73,759,565 | There is in Directx something similar to glfwSetWindowUserPointer? | So, I was using OpenGL with GLFW until now. Now I want to include DirectX in my project and I'm wondering, there is in directx, HWND something similar to glfwSetWindowUserPointer?
I have this struct:
struct WindowData
{
std::string Title;
int X, Y;
int Width, Height;
bool VSync;
... | There are some tutorials on the Internet that appear to cover how to integrate DirectX with GLFW windowing and the like. For details on creating a Direct3D 11 device, see this blog post.
That said, if you want to author a 'native' DirectX application, a Win32 rendering loop and Direct3D device setup is quite simple. Fo... |
73,758,245 | 73,758,366 | Does storing a returned reference into a variable allow you to access that variable? | I am confused as to why storing a reference to a member variable with an alias allows us to access it, while storing it with a variable does not allow us to access the same variable.
Let me clear up what I mean, say we have class Journey:
class Journey {
protected:
Coordinate start; //coordinate consists of x a... | Because you are calling a copy constructor when instantiating a Coordinate object with Coordinate a = j.getStart(). That is, Coordinate a is a copy of start, not a reference to it. Read here about copy constructors.
As for the question in the title, no, it doesn't. If you want some identifier to be a reference, you nee... |
73,758,252 | 73,758,309 | Target link multiple libraries in a project on clion | I am trying to use target_link_libraries in a project on clion, but when i run the project the following error is printed:
/usr/bin/ld: cannot find -lctop_common
/usr/bin/ld: cannot find -lctop_log
/usr/bin/ld: cannot find -lctop_util
/usr/bin/ld: cannot find -leigen
/usr/bin/ld: cannot find -lcrl
/usr/bin/ld: cannot f... | target_link_libraries tells cmake what libraries to link against (the -l flag that is). You have to specify where to find said libraries too! this can be done with target_link_directories... (the -L flag).
If you have these libraries in the lib folder, make sure they are compiled for the same platform as the executable... |
73,758,291 | 73,764,030 | Is there a way to specify the c++ standard of clangd without recompiling it? | I'm trying to use a feature in c++17(const lambdas) without having clangd error me. I've searched online and every answer tells me to recompile clangd with a flag. Is there truly no other way?
Edit: Clangd is not the compiler. It's a language server, which is a program made to be used with IDEs that basically checks yo... | Answer inspired by n. 1.8e9-where's-my-share m.
From https://clangd.llvm.org/config#compileflags:
You can create a config file for clangd. In the config file, you can specify the compiler options mimicked. For my question, do this:
CompileFlags:
Add: [-std=c++20]
|
73,758,360 | 73,758,499 | Why is it not correct when constructor is called recursively? | This is leetcode 341. When I write like this, it is correct:
class NestedIterator {
public:
vector<int> flatted;
int current=0;
NestedIterator(vector<NestedInteger> &nestedList) {
flatten(nestedList);
}
void flatten(vector<NestedInteger> &nestedList)
{
for(NestedInteger i:ne... | As others have mentioned, the iterator you create below the loop is not working because it has its own list that it populates and since you never keep any reference to it, after it is finished, it goes out of scope and is destroyed.
Try this instead:
class NestedIterator {
public:
vector<int> flatted;
int curre... |
73,758,579 | 73,760,157 | QPalette does not change the background of the button | I have the problem that the background of the button cannot be changed. Only the border is changed.
I assumed that some attribute prevented this. But I think I'm wrong on that point.
I've gone through the Qt documentation but can't find anything. I can only find examples on the internet that give me the same result. Is... | Here's the code I use to set the background color of a QPushButton (or any QAbstractButton):
// @param btn button to change colors of
// @param bc new background color for button
// @param optTextColor if non-NULL, the new color to use for the
// button's text label. If NULL, this function
// ... |
73,758,747 | 73,758,930 | Looking for the description of the algorithm to convert UTF8 to UTF16 | I have 3 bytes representing an unicode char encoded in utf8. For example I have E2 82 AC (UTF8) that represent the unicode char € (U+20AC). Is their any algorithm to make this conversion? I know their is the windows api MultiByteToWideChar but I would like to know if their is a simple mathematical relation between E2 8... | Converting a valid UTF-8 byte sequence directly to UTF-16 is doable with a little mathematical know-how.
Validating a UTF-8 byte sequence is trivial: simply check that the first byte matches one of the patterns below, and that (byte and $C0) = $80 is true for each subsequent byte in the sequence.
The first byte in a UT... |
73,760,751 | 73,760,972 | c++20 seems to be not supporting constexpr vector - is my installation incorrect | I just finished upgrading my compiler to C++20 on ubuntu 20.04. g++ version gives me the following output :
c++ (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0
I am trying the following code as suggested on stackoverflow
constexpr int f() {
std::vector<int> v = {1, 2, 3};
return v.size();
}
int main() {
static_asse... | You need to upgrade gcc to at least 12 to get the C++23 constexpr support for non-literal types as std::vector<int>.
From compiler support @ cppreference:
gcc
clang
EDG eccp
Non-literal variables (and labels and gotos) in constexpr functions
P2242R3
12
15
6.3
Feature test:
__cpp_constexpr >= 202110L
|
73,761,005 | 73,765,706 | Connect Qt to MariaDB Database | I am going to connect my program, which is written in Qt, to my database which is defined in MariaDB DBMS (XAMPP Software Package). So as you can see in the figure below, I have to install a MySQL connector instead of a MariaDB connector (This is what my book, Hand on-GUI programming with C++ and Qt said).
I installed... | So I had the same problem earlier. (windows)
then I found this link with debugged components.
https://github.com/thecodemonkey86/qt_mysql_driver/releases
and it worked.
I have the same server type as you, so it should work for you too. You have to put the appropriate files in the Qt folder. Only the current Qt versio... |
73,761,362 | 73,773,589 | Is it UB to access a non-existent object? | There seems to be no more silly question than this. But does the standard allow it?
Consider:
void* p = operator new(sizeof(std::string));
*static_cast<std::string*>(p) = "string";
[basic.life]/6:
Before the lifetime of an object has started but after the storage which the object will occupy has been allocated24 or, ... | [intro.object]/10
Some operations are described as implicitly creating objects within a specified region of storage. For each operation that is specified as implicitly creating objects, that operation implicitly creates and starts the lifetime of zero or more objects of implicit-lifetime types in its specified region ... |
73,762,161 | 73,762,196 | Is automating mutex like this in C++ safe? | I'm learning about mutex and threading right now. I was wondering if there's anything dangerous or inherently wrong with automating mutex with a class like this:
class AutoMutex
{
private:
std::mutex& m_Mutex;
public:
AutoMutex(std::mutex& m) : m_Mutex(m)
{
m_Mutex.lock();
}
~AutoMutex()
... | It's safe to use a RAII wrapper, and in fact safer than using mutex member functions directly, but it's also unnecessary to write since standard library already provides this. It's called std::lock_guard.
However, your implementation isn't entirely safe, because it's copyable, and a copy will attempt to re-unlock the m... |
73,762,265 | 73,763,891 | What is the expected behavior for ListObjects in GCP with a non existent path? (C++) | I expected the following C++/GCP code to return an empty list for a path which doesn't exist, but it doesn't seem to do so in practice:
for (auto&& object_metadata :
cli->ListObjects(bucket, path))
{
// how many time will this be hit?
}
Does anyone know what is the expected behavior? I couldn't fi... | TL;DR; the expected behavior is to return an empty set if the request is successful but there are no objects with that path, and to return a single element (with the error) if the request fails.
Loosely speaking, ListObjects() returns an input range of google::cloud::StatusOr<google::cloud::storage::ObjectMetadata>. I... |
73,762,352 | 73,770,476 | How to define default for pybind11 function as parameter | As per the pybind documentation, we can pass a function from Python to C++ via the following code:
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
int func_arg(const std::function<int(int)> &f) {
return f(10);
}
PYBIND11_MODULE(example, m) {
m.def("func_arg", &func_arg);
}
How can we define a... | One possibility is
namespace py = pybind11;
int func_arg(const std::function<int(int)> &f) {
return f(10);
}
std::function<int(int)> default_func = [](int) -> int { return 1; };
PYBIND11_MODULE(example, m) {
m.def("func_arg", &func_arg, py::arg("f")=default_func);
}
An even simpler one is just overload the ... |
73,763,951 | 73,764,250 | How do I joint iterate over 2 vectors by ref? | I'm trying to iterate over 2 vectors in one go using std::views::join
Here is what I'm trying:
std::vector<int> a {1, 2, 3}, b {4, 5, 6};
for (auto &v : {a, b} | std::views::join)
{
std::cout << v << std::endl;
}
This fails to compile. Now, if I change the code to:
for (auto &v : std::ranges::join... |
How do I jointly iterate over a and b in a way where I can modify
elements of a and b inside the loop?
You can use views::all to get references to two vectors and combine them into a new nested vector
std::vector<int> a {1, 2, 3}, b {4, 5, 6};
for (auto &v : std::vector{std::views::all(a), std::views::all(b)} // <-
... |
73,764,284 | 73,764,490 | 32 bit builtin population count for clang counts long long integer c++ | I was using the __builtin_popcount with clang compiler and I needed to count a 64 bit number (unsigned long long or uint64_t). From looking it up, __builtin_popcount counts 16 bits, __builtin_popcountl counts 32 bits, and __builtin_popcountll counts 64 bits. When I tested it, __builtin_popcountl was able to do calculat... | int __builtin_popcountl (unsigned long) is for unsigned longs.
int __builtin_popcountll (unsigned long long) is for unsigned long longs.
unsigned long is 64 bit on your platform, so the conversion from unsigned long long to unsigned long is lossless, and you can use __builtin_popcountl for 64 bit numbers too.
int is gu... |
73,764,752 | 74,234,608 | How to correctly format input and resize output data whille using TensorRT engine? | I'm trying implementing deep learning model into TensorRT runtime. The model conversion step is done quite OK and i'm pretty sure about it.
Now there's 2 parts i'm currently struggle with is memCpy data from host To Device (like openCV to Trt) and get the right output shape in order to get the right data. So my questio... | Could you please edit your question and tell us which model you're using if it's a commonly known NN, prehaps one we can download to test locally?
Then, the answer since it doesn't depend on the model (even though it would help to answer)
How actually a shape of input dims relate with memory buffer
If the input is Nx... |
73,764,769 | 73,764,787 | Vector of Arrays or Array of vectors cpp | int n = 10;
vector<int> adj[n];
Does this line create an array of vectors or a Vector of Arrays.
And how is it different from
vector<vector <int>> vect;
|
vector<int> adj[n];
Creates an array of n vectors of ints. However, if n is not a compile time constant, this is not standard C++, which does not support variable length arrays. Some compilers may implement it as an extension.
vector<vector <int>> vect;
This creates a vector of vectors of ints.
The dimensions of ... |
73,764,997 | 73,765,174 | Is there easier way to check for a variadic template type? | I've got a function
template<typename T, typename FuncT, typename ... Args>
static void Submit(Handle<T> handle, FuncT&& funcT, Args&& ... args);
Handle is a class that contains an index to the data inside some array. This data can be retrieved through a handle_cast function.
T& data = *handle_cast<T*>(handle);
I'm n... | You may be looking for something like this (not tested):
// Cloned from the standard std::forward
template<typename T>
T&& maybe_handle_forward(typename std::remove_reference<T>::type& t ) noexcept {
return std::forward<T>(t);
}
template<typename T>
T& maybe_handle_forward(Handle<T> h) noexcept {
return *handle_ca... |
73,765,330 | 73,765,346 | Is it a race condition? | Two threads are executing a function named job, inside which they are incrementing a global variable. Will there be a race condition here?
int i = 0;
void *job(void *args)
{
i += 1;
}
| Yes, this might result in parallel access to the variable, which is a problem. To avoid that, it's recommended to declare i as std::atomic<int>.
|
73,765,487 | 73,767,916 | sfml gravity clipping shapes through floor | I tried to make a cube that moves side to side and bounces off the floor.
It bounced a couple times and then fell through the floor.
I tried making the floor higher.
I tried adding extra vertical velocity.
I have tried everything i can think of.
I would like to get the cube to not fall through the floor.
how do I do th... | In your implementation, once the bottom of the rectangle goes below the ground, you just reverse the velocity but never update the position of the rectangle. This causes the rectangle to sink below the ground.
You should make sure that the bottom of the rectangle never goes below the ground. This can be done by adding ... |
73,765,835 | 73,765,880 | How to call a function with the same name within another class? | I have two classes, a Card class and Deck class. Both have display() functions, and I cannot change the name of the function. I am unsure of how I can call Card::display() inside of Deck::display().
Card.cpp
void Card::display( ) const
{
cout << rank << suit;
}
Deck.cpp //in Deck.h I did #include "Card.h", I did no... | If deck is an array of Cards(as you mentioned), than when you write:
deck[i].display()
This display function will be implicit the display function of your Card class, so your code should be fine
|
73,765,945 | 73,765,986 | C++ - Can a vector's size become more than the system RAM? | If I keep on inserting elements in a vector until I get an out of memory exception.
What is the limit to the final vector's size?
Size of RAM
Size of secondary memory because virtual memory is being used.
| This is entirely system dependent.
However, on typical desktop and server systems, allocations via new in a C++ application are allocations of virtual memory. If the system has swap space, then it is entirely possible to allocate more virtual memory than the size of physical RAM, so your #2 is closer to the truth.
Of ... |
73,766,300 | 73,766,664 | UTF-8 constexpr std::string_view from static constexpr std::array not valid on MSVC | The title is a bit wordy, the code demonstrates the problem better:
// Equivalent to क़
constexpr auto arr = std::array<char, 3>{static_cast<char>(0340),
static_cast<char>(0245),
static_cast<char>(0230)};
int main()
{
constexpr auto a... | This is a compiler bug which Microsoft devs seem to already be aware of, see this bug report against the standard library.
It seems that comparing narrow string literals with bytes outside the [0,127] range against non string literals currently fails at compile-time, because the built-in __builtin_memcmp has a bug.
The... |
73,766,477 | 73,766,772 | Is there a way to print base address (hex) not as characters but as readable 0x00000 format in a messagebox | void PrintBaseAddr() {
while (true) {
if (GetAsyncKeyState(VK_F6) & 0x80000) {
HMODULE BaseAddr = GetModuleHandleA(NULL);
BaseAddr += 0x351333;
MessageBoxA(NULL, (LPCSTR)BaseAddr, "Base Address", MB_OK);
}
}
}
so this is my code and the problem is, that Bas... | MessageBox expects to receive a string. Since you want to pass an address and render it as a hexadecimal number, you need to create a string holding the hexadecimal number first.
void PrintBaseAddr() {
while (true) {
if (GetAsyncKeyState(VK_F6) & 0x80000) {
HMODULE BaseAddr = GetModuleHandleA(NU... |
73,766,767 | 73,767,172 | How C++ expands multiple parameters packs simultaneously, | Having following functions f0, f1, f2 in C++14 code, which accepts arbitrary number of fixed-length arrays:
#include <functional>
template<typename... TS, size_t N> void f0( TS(&& ... args)[N] ) {}
template<typename T, size_t... NS> void f1( T(&& ... args)[NS] ) {}
template<typename... TS, size_t... NS> void f2( TS(&&... | This is specified in C++ Standard section [temp.variadic]. Basically, it's what you described: when a pack expansion expands more than one pack, all those packs must have the same number of elements. And the expansion in most cases forms a list where the nth element in the resulting list uses the nth element of each ex... |
73,767,539 | 73,767,638 | when can xvalues become lvalues? | or, to phrase it another way; when can we assign to a temporary?
cppreference.com says:
"an rvalue expression is either prvalue or xvalue" and "an rvalue can't be used as the left-hand operand of the built-in assignment or compound assignment operators"
with that context in mind, I would like to understand what is happ... | Assuming C++17 or later:
int * p1 = &get_int();// fail "cannot take the address of an rvalue"
A function call expression to a function returning by-value is a prvalue expression. The built-in & does not accept prvalues as operand.
type * p2 = &get_type();// fail "taking the address of a temporary object"
Same as abov... |
73,767,655 | 73,768,355 | Non-type template argument, from constant function argument? | I'm experimenting with C++ templates, and a kind of heterogenous type-safe map. Keys go with specific types. An example use would be something like a CSS stylesheet. I've got it to where I can things write:
styles.set<StyleKey::fontFamily>("Helvetica");
styles.set<StyleKey::fontSize>(23.0);
That type checks as desired... | You can't do SFINAE or specialization on function parameters, only template parameters. That means this can't work using your current approach.
What you could do is change your StyleKeys from being enum values to being empty tag structs with different types. Then you could specialize KeyValueType on each of those typ... |
73,767,924 | 73,772,059 | C++ std::make_unique usage | This is the first time I am trying to use std::unique_ptr but I am getting an access violation
when using std::make_unique with large size .
what is the difference in this case and is it possible to catch this type of exceptions in c++ ?
void SmartPointerfunction(std::unique_ptr<int>&Mem, int Size)
{
try
{
... | When you invoke std::make_unique<int>(Size), what you actually did is allocate a memory of size sizeof(int) (commonly 4bytes), and initialize it as a int variable with the number of Size. So the size of the memory you allocated is only a single int, Mem.get()[k] will touch the address which out of boundary.
But out of ... |
73,768,316 | 73,768,954 | Qt zombies: Calling functions containing new with QTimer | I'm trying to display a dynamically updating table using QTimer with a refresh rate of 1s. I'm calling the function create_table which in turn calles create_title. The code runs without complaints but tracking memory usage one finds that it keeps creeping up steadily till the program becomes unresponsive, or crashes.
v... | For the question itself: Your createTable method could call QTimer::singleShot to schedule an update one second later.
auto create_table(QWidget * tab,
const std::vector<std::string> &v,
const std::string &title) {
...
QTimer::singleShot(1000 /*ms*/, this /*context*/, [this, ... |
73,768,399 | 73,776,367 | Why does C++23 ranges::to not constrain the container type C to be a range? | C++23 introduced the very powerful ranges::to for constructing an object (usually a container) from a range, with the following definition ([range.utility.conv.to]):
template<class C, input_range R, class... Args> requires (!view<C>)
constexpr C to(R&& r, Args&&... args);
Note that it only constrains the template p... | This is a problem with the wording that we'll need to address, I'll open an issue later today. This is LWG 3785.
So, what are the considerations for removing the constraint that C must be input_range?
The goal of ranges::to is to collect a range into... something. But it need not be an actual range. Just something w... |
73,768,552 | 73,771,523 | Why does RegOpenKeyEx return "0" value? | I use CodeBlocks version 20.03 (x86) as IDE.
Here are my codes:
#include "iostream"
#include "windows.h"
using namespace std;
int main()
{
HKEY hkRegedit;
long longHataKodu;
longHataKodu = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Chkdsk", 0, KEY_ALL_ACCESS | KEY_WOW64_64KEY, &hkRegedit);
... | Registry virtualization is a compatibility shim for old applications that redirects writes to HKEY_USERS\<User SID>_Classes\VirtualStore instead of causing access denied errors.
To turn it off, add a manifest to your application with a requestedExecutionLevel node to mark yourself Vista/UAC compatible.
|
73,769,115 | 73,769,435 | GCC C++ GTK ENTRY SET TEXT with GLADE | I have a small problem, I have used GTK with other languages but with C ++ being new I cannot find tutorials that allow me to use interfaces created with Glade and the ones I have found explain everything else.
I tried to write a code in C ++ where I have to insert a text in a GTK_ENTRY but nothing appears even followi... | Change the following line
//doesnt appar nothing
void gtk_entry_set_text (GtkEntry* MyEntry, const gchar *TextVar);
with
gtk_entry_set_text(GTK_ENTRY(MyEntry), TextVar);
And make sure you are compiling with -rdynamic flag.
|
73,770,170 | 73,770,709 | Is std::istream_iterator<int> trivially copy constuctible? | Why does this program compile on MSVC but not on GCC and Clang? godbolt
#include <iterator>
#include <type_traits>
static_assert(std::is_trivially_copy_constructible_v<std::istream_iterator<int>>);
According to [istream.iterator.cons]/6, the constructor must be trivial. Does it relate to P0738 which moves the wording... | Seems like there is a difference in implementation. The gcc library has a copy constructor
istream_iterator(const istream_iterator& __obj)
: _M_stream(__obj._M_stream), _M_value(__obj._M_value),
_M_ok(__obj._M_ok)
{ }
which is non-trivial.
MSVC does not, and apparently relies on a compiler generated one.
|
73,770,185 | 73,770,357 | Is std::vector::end()[-1] a undefined behavior? | std::vector v { 1, 2, 3, 4, };
The v.end()[-1] is able to access element 4.
For a longabout 2 years time, I use *(v.rbegin() + 0)...
Will it cause any problems if I only use indexes ranged on [-static_cast<int>(v.size()), -1]?
| You are allowed to use the subscript operator on a LegacyRandomAccessIterator.
i[n] convertible to reference *(i + n)
where n is of type std::iterator_traits<It>::difference_type (which is signed).
So, as long as you stay within the valid bounds, it's fine.
int main() {
std::vector v { 1, 2, 3, 4, };
fo... |
73,770,870 | 73,771,320 | Why do compilers now accept to call str() member on a returned std::ostream& from std::stringstream::operator<<()? | Consider the following line:
std::string s = (std::stringstream() << "foo").str();
This should not compile because std::stringstream::operator<<() is inherited by std::ostream and returns a std::ostream& which does not have an str() member.
It seems the main compilers are now accepting this code where they didn't in t... | They all added the rvalue overload (see here) at around the same time.
The rvalue overload was introduced in added to C++11 and returns the same type of stream as its left-hand operand.
As has been noted in the comments, the reason for it being added to the compilers seemingly after a whole decade is that it was added ... |
73,771,368 | 73,774,169 | Why doesn't boost::asio::ip::udp::socket::receive_from throw interruption exception in Windows? | volatile std::sig_atomic_t running = true;
int main()
{
boost::asio::thread_pool tpool;
boost::asio::signal_set signals(tpool, SIGINT, SIGTERM);
signals.async_wait([](auto && err, int) { if (!err) running = false; });
while(running)
{
std::array<std::uint8_t, 1024> data;
socket.recieve_from(boost::a... | Regardless of the question how you "raise the signal" on Windows there's the basic problem that you're relying on OS specifics to cancel a synchronous operation.
Cancellation is an ASIO feature, but only for asynchronous operations. So, consider:
signals.async_wait([&socket](auto&& err, int) {
if (!err) {
s... |
73,771,983 | 73,772,519 | circular dependent incomplete templated types | I am trying to create a graph data-structure in an adjacency-map style, however I am running into some problems with circularly dependent structs. I have tried doing a forward declaration, but it doesn't seem to work. I keep getting invalid use of incomplete type node_collection<int>, which makes sense since I am forwa... | The program is not guaranteed to compile, although the specification of the language is somewhat lacking in this area.
Your variable in main requires instantiation of graph<int>, which in turn requires instantiation of std::unordered_map<std::string, node<T>>.
std::unordered_map does not promise that it can be instanti... |
73,772,122 | 73,772,342 | An efficient algorithm to sample non-duplicate random elements from an array | I'm looking for an algorithm to pick M random elements from a given array. The prerequisites are:
the sampled elements must be unique,
the array to sample from may contain duplicates,
the array to sample from is not necessarily sorted.
This is what I've managed to come up with. Here I'm also making an assumption that... | The comments already note the use of std::set. The additional request to check for M unique elements in the input make that a bit more complicated. Here's an alternative implementation:
Put all inputs in a std::set or std::unordered_set. This removes duplicates.
Copy all elements to the return vector
If that has more ... |
73,772,424 | 73,774,817 | Refreshing QTableView based on data refreshed periodically via QTimer | I'm trying to refresh a QTableView based on data from a method get_data which is called periodically by QTimer as below.
Once I get the data, I update it in my model (via a member function refresh) and then call refresh_table to hopefully update the tableView with the current data. However, the call to tableView->updat... | The canonical way is for your model to emit a dataChanged() signal. Any associated QTableViews will receive that signal and respond by re-querying the model for new values and updating the associated cells of their table.
|
73,774,029 | 73,774,135 | Convert if with init-statement (c++17) to c++14 | This works only for c++17. Is there a way to convert this to c++14?
if (auto user = static_cast<CUser*>(pMover); user && !user->UserState())
return;
| You have to split the if into 2 statements.
In order to limit the scope of user to the if statement, you can enclose it with {...}:
{
auto user = static_cast<CUser*>(pMover);
if (user && !user->UserState())
return;
}
|
73,774,540 | 73,774,958 | Need to call some code in an arbitrary Windows process (externally) at some time interval. Is there any OS API call for it? | I want to test my idea, wherein I execute some code in the context of another process at some interval. What API call or kernel functionality or l technique should I look into to execute code in another process at some interval?
Seems like I need to halt the process and modify the instruction pointer value before cont... | The wording of the question tells me you're fairly new to programming. A remote process doesn't have AN instruction pointer, it typically has many - one per executing thread. That's why the normal approach would be to not mess with any of those instruction pointers. Instead, you create a new thread in the remote proces... |
73,776,372 | 73,781,421 | how to solve cpp library confliction within anaconda? | I tried to install lightgbm with gpu in anaconda. I used pip in anaconda directly with --install-option='--gpu'. it's built successfully and lib_lightgbm.so links to libstdc++.so under /lib64.
as anaconda has it's own libstdc++.so under anaconda3/lib and it's different from the one under /lib64, when I try to import li... | As described in microsoft/LightGBM#5106, when building lightgbm from source in a conda environment on Linux, the most reliable way to avoid linking to a libstdc++ that is using a new GLIBCXX version than the one found by conda is to use conda's C/C++ compilers.
Like the following.
# create conda env with lightgbm's dep... |
73,776,523 | 73,776,849 | Setting a test-wide tolerance with BOOST_DATA_TEST_CASE_F | Within a BOOST_FIXTURE_TEST_CASE, you can set a tolerance for all BOOST_TEST calls like so:
BOOST_FIXTURE_TEST_CASE(Testname, SomeFixture, *utf::tolerance(.01))
However, I cannot find a way to make this work with BOOST_DATA_TEST_CASE_F.
From Boost:
BOOST_DATA_TEST_CASE_F(my_fixture, test_case_name, dataset, var1, var2... | I don't see a way to do that, but you can set the tolerance in a BOOST_AUTO_TEST_SUITE(), and you can have as many of those suites as you want. So:
BOOST_AUTO_TEST_SUITE(suite1, *utf::tolerance(.01))
BOOST_DATA_TEST_CASE_F(my_fixture, test_case_name, dataset, var1, var2..., varN)
BOOST_AUTO_TEST_SUITE_END()
Repea... |
73,777,055 | 73,785,383 | Failing to read from std::cin after pipe() with dup2() | I was trying to read output from a child process using a pipe(). I used dup2() to get the pipe's output through stdin, and cin.get(c) in a loop to get the child's output. The first time I do this, everything works fine. After that, however, every time I try to do this again, cin.get() returns EOF.
I thought that perhap... | As William Pursell mentioned, using both clear() and clearerr() will solve your problem.
After reading around for a bit, I came to the conclusion that this is due to the fact that std::cin and stdin are two different things, and therefore you need to reset their error flags separately:
std::cin is an object of class i... |
73,777,190 | 73,778,335 | How to join two vector<vector<string>> in c++ based on a common column | So what I want to do is essentially do an inner join of two tables in c++. However, the only guide I could is this one from geeksforgeeks: https://www.geeksforgeeks.org/joining-tables-using-multimaps/
An example below is as follows:
// First Column Name: Numbers
// Second Column Name: Alphabets
vector<vector<string>> v... | In your code, you are actually computing for the column header names two times. First you are pushing them manually, then in the main loop you have for (vector<string> v : v1) which actually will start from the first row, which is again those column names.
Instead you can use a normal for loop and start from the second... |
73,777,244 | 73,777,617 | Why does the bit-width of the mantissa of a floating point represent twice as many numbers compared to an int? | I am told that a double in C++ has a mantissa that is capable of safely and accurately representing [-(253 − 1), 253 − 1] integers.
How is this possible when the mantissa is only 52 bits? Why is it that an int16 is only capable of having a range of [-32,768, +32,767], or [-215, 215-1], when the same thing could be used... | The format of the double (64 bits) is as follows:
1 bit: sign
11 bits: exponent
52 bits: mantissa
We only need to look at the positive integers we can represent with the mantissa, since the sign bit takes care of the negative integers for us.
Naively, with 52 bits, we can store unsigned integers from 0 to 2^52 - 1. Wi... |
73,778,605 | 73,779,512 | How to restrict access to the most direct base class, while still exposing the base-base classes? | I have a class hierarchy similar to this:
class Widget {
// a lot of virtual members
};
class Button : public Widget {
// new stuff + overrides
};
class MySuperButton : public Button {
// ...
};
And I would like to hide the fact that MySuperButton inherit from Button, but not from Widget. Basically makin... | What you are asking is not really possible.
A possible Qt-specific solution is the following:
class MySuperButton : public Widget {
public:
MySuperButton () {
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(button = new Button());
setLayout(layout);
}
private:
Button *butto... |
73,778,815 | 73,779,325 | Understanding what typedef HRESULT(__stdcall* endScene)(IDirect3DDevice9* pDevice) does | I found this piece of code and i cant understand what it means and what it does:
typedef HRESULT(__stdcall* endScene)(IDirect3DDevice9* pDevice);
endScene pEndScene;
I would appreciate any clues
| It is declaring an alias for a function pointer type, and then declaring a variable of that type.
It is declaring a type named endScene, which is a pointer to a function that takes in an IDirect3DDevice9* as input, uses the __stdcall calling convention, and returns an HRESULT as output.
And then it is declaring a varia... |
73,778,901 | 73,779,109 | Type deduction in C++ for positional information | Let's assume I have a collection of functions following the following pattern:
template <typename T, typename ... Args>
T example(Args ... args, T* defaultValue);
Furthermore I have another function that operates on these collections:
template <auto Function, typename T, typename ... Args>
auto transform(Args ... args... | You can get the parameters from function.
for example you can do something like this
#include <tuple>
template<typename F>
struct last_arg{};
template<typename ret, typename ...args>
struct last_arg<ret(*)(args...)>{
using type = std::tuple_element_t<sizeof...(args)-1,std::tuple<args...>>;
};
template <auto F, t... |
73,779,251 | 73,779,907 | Calculating the position of an orbiting object with a pivot point based on angle or vector | I'm trying to get an object to orbit around a point at a fixed distance. I've tried some methods such as setting the position of the object to the normalized vector multiplied by how far away I want the object to be from the pivot, but the input vector is sometimes (0, 0), which when multiplied results in 0 causing the... | If your pivot point has coordinates (x, y), then you only need to set the position of your object (ideally its center of mass) to
(x + r*cos(t), y + r*sin(t))
where r is the distance from the pivot and t is an angle, presumably a function of time (or something you periodically increase).
In C++, you have std::sin and s... |
73,779,453 | 73,780,198 | How to avoid console flickering/opening when executing a system() command in QT? | I'm working on an implementation to force the exit of a process by PID in QT. The only way I found to solve this problem is using the following lines of code:
QString processToKill = "taskkill /F /PID " + QString(getAppPid());
system(processToKill.toStdString().c_str());
These lines do their job and works well, th... | If you are using system() you cannot avoid the occasional flash of the console window. Were you to use any other program you might even see its window flash.
I won’t go into any detail about the security flaws inherent to using system().
The correct way to do this with the Windows API.
Even so, you are taking a sledgeh... |
73,779,721 | 73,779,785 | Why does the clang sanitizer think this left shift of an unsigned number is undefined? | I know there are many similar questions on SO. Please read carefully before calling this a dup. If it is, I would be happy to get a reference to the relevant question.
It seems to me that the clang sanitizer is complaining about a perfectly valid left shift of an unsigned number.
int main()
{
unsigned int x = 0x123... | -fsanitize=address,integer
The integer sanitizer turns on checking for "suspicious" overflows of unsigned integers too, which do not have undefined behavior.
See "-fsanitize=unsigned-integer-overflow: Unsigned integer overflow, where the result of an unsigned integer computation cannot be represented in its type. Unli... |
73,780,089 | 73,830,489 | How to download a file from a private repository using curl? | I'm trying to download a file from a private GitHub repository, current code:
#include <curl/curl.h>
static size_t WriteMemoryCallback(void* contents, size_t size, size_t nmemb, void* userp) {
size_t realsize = size * nmemb;
auto& mem = *static_cast<std::string*>(userp);
mem.append(stati... | Add Authorization and Accept headers like this:
slist = curl_slist_append(slist, "Authorization: token <Your Token>");
slist = curl_slist_append(slist, "Accept: application/vnd.github.v3+raw");
then call
curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, slist);
and provide the link to the file in this form:
https://a... |
73,780,645 | 73,780,762 | Segmentation Fault in Stack, Printing Weird Numbers | I keep getting a segmentation fault and the printsum() areas of my code print crazy numbers. I've tried running it through an online GDB debugger but couldn't find the error. Essentially the first input contains the number of queries and then it prompts the user to type a "type" of query for each query that determines ... | For type 5:
Type 5: You have to simply print the sum of all the elements of the stack.
Since there is no way to iterate a stack, you get the sum by poping and getting stack top. To get the sum of a stack, you can copy the stack and on the sum calculation is complete, copy it back to stack s.
So update printsum like t... |
73,781,105 | 73,781,168 | How to debug c++ file in vscode on macOS? | I've been trying to debug .cpp file in vscode and following files have been installed perfectly. (I've ran .cpp file via code-runner extension but now I'd like to debug c++ files.)
$ clang --version // or g++ --version (both same result)
Apple clang version 13.1.6 (clang-1316.0.21.2.5)
Target: arm64-apple-darwin21.5.0... | the launch.json "preLaunchTask": "C/C++: clang build active file"
use task.json "label": "C/C++: clang++ build active file"
as it's execute task
so you launch.json should be modified
notice change clang to clang++ to match task label
{
"configurations": [
{
"name": "C/C++: clang build and deb... |
73,781,772 | 73,781,954 | Result of string in conditional statement in C++ | if( condition && "Text in double quotes")
{
do this;
}
else
{
do that;
}
Saw this code in a program, in which case would the conditional expression in the IF-statement return true and in which case would it return false?
| false && "Literally anything" is always false.
The primary expression is false, operator && is a logical operator (unless it was overloaded), so it will short-circuit.
This is because false && E (where E is an expression) is known to always evaluate to false. Therefore E doesn't need to be evaluated at all.
So if E was... |
73,781,815 | 73,781,941 | Image blurring with different approaches | I am learning how to write down c++ program using open cv for Gaussian filtering for image blurring.
After browsing lot of websites I found two different types of coding but both claim that those code can be used from image blurring and they applied Gauusian filter method for blurring.
Code 1: Source
int main(int argc,... | pyrDown() not only blurs the image by applying a Guassian filter, it also downsamples the resulting image to produce a smaller sized image. It is producing an image pyramid by applying Gaussian blurring and downsampling. The reason for applying Gaussian blurring is that if you downsample directly, the resulting image w... |
73,782,191 | 73,784,077 | Mocking a class instance created in other class constructor C++ Google Mock | To give you a bit of an insight into my system - I've got a hardware device that can be communicated with using USB, SPI or UART bus from a host like Raspberry PI or regular PC (USB only). It's a communication dongle and the library should be available to users so the ease of use is a crucial thing for me.
Now I'd like... | You might have extra constructor:
class Dongle
{
private:
std::unique_ptr<Bus> bus;
public:
// also used for testing to pass a MockBus
// Can be made protected, and make friend a test factory.
explicit Dongle(std::unique_ptr<Bus> bus) : bus(std::move(bus)) { reset(); }
explicit Dongle(busType_... |
73,782,267 | 73,782,728 | construction and destruction of parameterized constructor argument? | Here, i am getting different out on different compiler, why is that ?
On msvc compiler, there i'm getting extra destructor statement ?
Why i'm getting this behaviour ?
Am i missing something ?
i had looked many question on stackoverflow, but i can't find anything related to my problem ?
i also tried to look for duplica... | Since you're using C++17 and there is mandatory copy elision from C++17(&onwards), the extra destructor call must not be there.
A msvc bug has been reported as:
MSVC produces extra destructor call even with mandatory copy elision in C++17
Note that if you were to use C++11 or C++14, then it was possible to get an extr... |
73,782,471 | 74,617,118 | How Did the GNU libstdc++ Library Find Its Way into Our App? | The Question
This is not about legal advice. We are asking why/how the GNU libstdc++ library seemingly found its way into our app, when to the best of our knowledge it should not be part of our app, according to our IDE setup.
Context
We recently used Android's documentation to include open source notices in our app. A... | I found it for example in the com.google.android.gms:play-services-oss-licenses dependency itself.
I did it by running the <variant>OssLicensesTask multiple times, and using divide and conquer to comment out half of the dependencies that can potentially include that license and check the generated third_party_license_m... |
73,782,520 | 73,790,154 | How can I wait in reading from file between letters C++ qt | I wrote this code:
void StartToSendCommand(QString fileName, QPlainTextEdit *textEdit)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTimer * inputTimer=new QTimer(textEdit);
QTextStream in(&file);
QString line;
while (!in.atEnd()) {
... | If you want to wait for individual letters, you can also do this with a QTimer interval. Once the condition is met, you can submit the file.
Here would be a small example, oriented towards a typewriter but has the same effect:
.h
....
private slots:
void typeWriter();
private:
QString line;
QTimer *timer;
... |
73,783,547 | 73,787,512 | GDAL read several pictures from wmts server using same opened connection | I use C++ code to read pictures from WMTS server using DGAL.
First I initialize GDAL once:
...
OGRRegisterAll();
etc.
But new connection is opened every time I want to read new image (different urls):
gdalDataset = GDALOpen(my_url, GA_ReadOnly);
URL example: https://sampleserver6.arcgisonline.com/arcgis/rest/services/... | While GDAL can read PNG files, it doesn't add much since those lack any geographical metadata.
You probably want to interact with the WMS server instead, not the images directly. You can for example run gdalinfo on the main url to see the subdatasets:
gdalinfo https://sampleserver6.arcgisonline.com/arcgis/services/Toro... |
73,783,695 | 73,784,365 | C++: Template binding object and method using lambda expression | Due to the fact that std::functional uses heap memory when combining it with an std::bind I wanted to replace the std::bind with a lambda expression but I do not quite know how to do this. Is this even possible?
#include <iostream>
#include <functional>
#include <utility>
template<typename Signature>
class Callback;
... | If you really want to pass a member function pointer then you need to use syntax for calling the method via a member function pointer:
mFunc = [&,method](Args...x){ return (obj.*method)(x...);};
However, it would be simpler if you'd accept free callables and let the caller bind the object to a member function if nece... |
73,784,163 | 73,784,796 | CreateWindowW always returns null | I'm new to C++ coding, and I'm trying to create a window using the Win32 API, but CreateWindowW() always return a NULL value. I tried to use CreateWindowEx() and CreateWindow(), but the same results.
Here is the code I used:
#include<windows.h>
LRESULT CALLBACK WindowProcedure(HWND, UINT, WPARAM, LPARAM);
INT WINAPI ... | The window procedure always returns 0, which ultimately cancels window creation. As outlined in the documentation for CreateWindowExW:
The CreateWindowEx function sends WM_NCCREATE, WM_NCCALCSIZE, and WM_CREATE messages to the window being created.
The first message, WM_NCCREATE, has the following in the documentatio... |
73,784,199 | 73,786,884 | Insert JSON object into an existing JSON object as a key-value-pair in Boost | I have a class hierarchy that looks like this: class A is composed of classes B and C.
B and C each have a function that returns boost::json::object, which looks like this in case of B: {"B": "someValue"}
A is supposed to compose each of these objects into a structure like this:
{
"A": {
"B": "someValue",
"C"... | makeObject returns single objects. You pass them as the initializer list to a json::value, so you should expect {makeObject(...), makeObject(...)} to create an array: docs
If the initializer list consists of key/value pairs, an object is created. Otherwise an array is created.
Instead, you want to make an initializer... |
73,784,496 | 73,785,522 | Why does static_assert on a 'reference to const int' fail? | I'm now learning how to use static_assert. What I learned so far is that the argument of the static_assert has to be constant expression. For the following code, I don't know why the argument reference is not a constant expression: It is declared as const and initialized by integral constant 0:
int main()
{
const i... | First of all, because you use static_assert(reference); instead of static_assert(!reference); the program is ill-formed whether or not the operand of static_assert is a constant expression, as the assertion will fail. The standard only requires some diagnostic for an ill-formed program. It doesn't need to describe the ... |
73,784,828 | 73,796,366 | C++ Builder 10.4 community edition => scoped_lock are missing (at least seems to be a path mess) | Just installed C++Builder 10.4 Community Edition. My app is a console multi-threaded app, and uses std::scoped_lock (C++17).
It seems that C++Builder chooses a <mutex> header file that does not define scoped_lock in C:\Program Files (x86)\Embarcadero\Studio\21.0\include\dinkumware64, where the <mutex> header file that ... | The standard library is located in dinkumware64 for 32-bit programs as well, so you should be looking there.
Problem is that scoped_lock is missing from the standard library.
You can easily implement this class by yourself by using std::lock, or just use std::lock_guard if you only have one mutex.
|
73,784,862 | 73,784,928 | How to specify which function I want to use in a C++ class when a C function has the same name as my C++ function? | I am trying to write an i2c driver class. The class contains read() and write() methods.
The problem is that I use write function of unistd.h in my Drv_i2c class write() function (see below) and Qtcreator compiler chooses my class write function instead of unistd.h write function.
I know that I could just rename my cla... | You can use the scope operator "::" maybe
|
73,785,102 | 73,785,468 | After compiling a simple C++ code in eclipse, it doesn't show the problems as described in my instruction | I am learning C++ along with a script. Eclipse is my IDE and I'm using MinGW64 as a compiler.
In the script there is following code written, which I am just supposed to copy and compile first:
Supposed code from script
My script says that as soon as I compile it, in the lower window under "Problems" there should be sho... | You've got two problems.
The easy one. On line 12 you have a typo. It should say std::endl; rather than std:endl; You are missing a colon, it's just that.
The harder one. When I load the following code into Visual Studio on Windows, it compiles and runs correctly.
#include <iostream>
int main()
{
std::cout << "Hel... |
73,785,198 | 73,824,775 | Range_Image of PCL crashes Application | I am using the precompiled/All-in-One PCL (PointCloudLibrary) in release-version 1.12.1 for Windows.
IDE: Visual Studio 2019
With that, I am already able to use the visualizer, so parts of the library are already working fine.
When I want to create a RangeImage-object however my program either runs into an infinite l... | What fixed this problem was to build the pcl 1.12.1 new with instructions from this tutorial*1 (scroll down until you find the right version): https://gist.github.com/UnaNancyOwen/59319050d53c137ca8f3
Also in Visual Studio the project setting under "C/C++ > Codegeneration > Activate advanced Instructionset" had to be s... |
73,786,289 | 73,786,419 | class math operation overload for types which are also have cast operator overloaded | as a part of my uni task I need to write class for rational numbers, override math operator, compare operators, etc. But I also need to overload cast to short, int and long types. Here is simplified code for my class:
class RationalNumber {
long long numerator, divider;
public:
RationalNumber() : numerator(0), divi... | Implicit conversions can cause problems and can have a negative effect on readability. If possible make the conversions explicit and keep implicit conversions for exceptional cases, when you are sure that an implicit conversion is appropriate. The call is no longer ambiguous if you make the conversion explicit:
explici... |
73,787,458 | 73,787,521 | Do you know what happend when i invoke copy constructor on self? | I do not know what happend when i invoke copy constructor on self. In my opinion, The copy constructor will allocate new memory space for the object, and then copy the data of the old object to the new memory space. So the address will change when i call A(a), but it not.
class A {
public:
A(const A& t) {
s... | a = A(a); does create a new A by invoke copy constructor.
But you then copy(assign) the value back to a. and drop the temporary.
the a address is never changed. (there is no way to change it btw)
|
73,787,588 | 73,787,688 | Constexpr class function definition linking error | Function is declared in hpp file like this:
class StringProcessor
{
static constexpr const char* string_process(const char* initial_string, std::size_t string_length, const char* key, std::size_t key_length);
};
And defined in cpp like this:
constexpr const char* StringProcessor:: string_process(const char* initia... | constexpr functions are implicitly inline and therefore need to be defined in every translation unit where they are used. That usually means that the definition should go into a header shared between the translation units using the function.
Also, in order for constexpr to be of any use, the function needs to be define... |
73,788,875 | 73,884,165 | How to get proper stack trace despite catch and throw; in std library | I use C++17, GCC, Qt Creator with its integrated GDB debugger.
I have code that simplifies down to this:
#include <iostream>
#include <iomanip>
// Example-implementation
#define assert(Condition) { if (!(Condition)) { std::cerr << "Assert failed, condition is false: " #Condition << std::endl; } }
#include <execinfo.h... | What @n.1.8e9-where's-my-sharem. suggested in the comments ended up working. When you throw an exception in C++, behind the scenes the function __cxa_throw is called. You can replace that function, look at the stack trace, then call the replaced function.
Here is a simple proof-of-concept:
#include <dlfcn.h>
#include <... |
73,789,293 | 74,022,551 | CLION detecting UNIX operating system on WINDOWS computer | I am trying to write a program that opens up a com port to communicate but works on both LINUX and WINDOWS. To do this, I am using the method outlined in many other sources:
#ifdef __unix__
#linux code
#else
#windows code
#endif
If I copy the code into VSCode, it functions correctly. However, when I do this in C... | I figured out the issue. My CLION toolchain was default set to WSL and I had to change it to MinGW.
|
73,789,689 | 73,789,730 | Can G++ coexist side by side with Visual Studio? | I have Visual Studio 2013 Community installed. Now want to learn more about compiling, as well as being more Windows independent/portable, with Notepad/G++11/MinGW-64 (all within same Windows 10 Home 64bit platform for c++ audio applications). Can GCC and VS coexist side by side?
| Yes. You can, of course, have both installed side-by-side. But you cannot expect to be able to link object files / libraries compiled by different compilers (or even different compiler versions) in most cases.
|
73,789,722 | 73,793,278 | even using error_handler got uncaught x3::expectation_failure | As I try to rewrite my Spirit X3 grammar, I put some rules (e.g. char_ > ':' > int_ > '#') into a parser class like this one shown here:
struct item_parser : x3::parser<item_parser> {
using attribute_type = ast::item_type;
template <typename IteratorT, typename ContextT>
bool parse(Iterator... | First off, you need to make up your mind. You're duplicating the error handling code (inconsistently), using a function object as the rule tag (error_handler), (but operator() is completely ignored there), complicating things because you are using the same tag on different rules.
Then you're also using the undocumented... |
73,790,277 | 73,801,820 | Calling a GNU ar script in Makefile | I'm having some trouble using GNU ar script from a Makefile. Specifically, I'm trying to follow an answer to How can I combine several C/C++ libraries into one?, but ar scripting isn't well supported by make, as most Makefiles use the ar command-line interface and not a script. ar needs each line to be terminated by a ... | You don't need to use the shell function and you don't need to write it to a file. ar is taking from stdin anyway so why not just use a pipe?
Either:
final_lib.c: foo.a the_cmake_library.a
printf "EOM\nCREATE $@\nADDLIB foo.a\nADDLIB the_cmake_library.a\nSAVE\nEND\nEOM\n" | $(AR) -M
ranlib $@
Or somet... |
73,790,603 | 73,791,486 | How to insert an element at some specific position in the list using classes? | #include<iostream>
using namespace std;
template<typename T>
class List
{
public:
T *values;
int capacity;
int counter;
public:
List()
{
values = NULL;
capacity = 0;
counter = 0;
}
List(int cap)
{
capacity = cap;
values = new T[cap];
counte... | bool insertAt(T item, int index)
{
if (!isFull() && index < counter)
{
for (int i = counter; i > index; i--) {
values[i] = values[i - 1];
}
values[index] = item;
counter++;
return true;
}
return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.