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 |
|---|---|---|---|---|
65,681,765 | 65,682,123 | Use an array declared inside an if condition elsewhere | I declared an array depending upon a randomly generated number. Now i know we can't use an array generated inside an if block anywhere else but i heared there are ways like dynamic memory allocation & vectors etc?
any help on that?
srand(time(0));
int num=rand() % 6 + 1;
if(num==1)
char word[6] = {'b','a','t','m',... | From what you show, you might use:
srand(time(0)); // Called only once, probably in main
char words[3][6] { // Possibly const // Possibly std::vector<std::string>
{'b','a','t','m','a','n'},
{'k','i','l','l','e','r'},
{'b','e','a','u','t','y'}
};
int num = rand() % 3;
auto& word = words[num]; // char (&wor... |
65,682,253 | 65,682,352 | Put a non-numeric input into an integer variable | I’m having a bit of a problem in C++. When I wrote this:
int a = ‘:‘;
cout << a;
This printed out 58. It checks out with the ASCII table.
But if I write this:
int a;
cin >> a;
//i type in “:”
cout << a;
This will print out 0. It seems like if I put in any non-numeric input, a will be 0. I expected it to print out the... | You're declaring a as an int, then the operator>> expects digits, but you give a punctuation, which makes extraction fails. As the result, since C++11, a is set to 0; before C++11 a won't be modified.
If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is ... |
65,683,044 | 65,684,194 | Why does libc++ allow recursive locking of std::mutex? | std::mutex is nonrecursive, and violation of that is UB. So anything is possible in theory(including works as std::recursive_mutex)), but libc++ seems to work fine , this program outputs
bye
#include <iostream>
#include <mutex>
std::mutex m;
int main() {
std::scoped_lock l1(m);
std::scoped_lock l2(m);
st... | I get the opposite results: libc++ hangs and libstdc++ doesn't
The reason is that if the file is not compiled with -pthread, threading support is disabled and std::mutex::lock/unlock become noops. Adding -pthread makes both of them deadlock as expected.
libc++ is built with threading support by default and doesn't requ... |
65,683,121 | 65,683,337 | I'm intrested in finding the time complexity of a map with two keys | I am trying to convert the entire elements of a matrix in to a hashmap. for that what i tried is using map<pair<int,int>,int>mp;
where pair<int,int> are the array indices and the value is the value in the element of a matrix.
so i tried this way
mp[{i,j}]=value;
It works fine but what i am interested in is finding the... | Just to clarify, map container in C++ is a tree-based structure. You mentioned using a hashmap. unordered_map is a hash-based container in C++.
As for the unordered_map (https://en.cppreference.com/w/cpp/container/unordered_map):
Unordered map is an associative container that contains key-value
pairs with unique keys.... |
65,683,135 | 65,699,793 | MPI_Scatterv (c) will give segmentation fault | I've built a fairly simple c code that reads a pgm image, splits it in different sections and sends it to various cores to elaborate it.
In order to account for some elaboration margins (each core has to access a larger area of the image than the it needs to write on), I can't simply split the image but I first have to... | In the code shown here, start and end are used uninitialised in the computations of first and last:
int flo, start, end, i;
~~~~~~~~~~
flo = floor(ysize/ranks);
int first, last;
first = start - (m - 1)/2; // <---- start has a random value here
last = end + (m - 1)/2; // <---- end has a random value here
... |
65,683,297 | 65,683,775 | Is there a standard way to swap arguments for a binary predicate? | I want to find last value in a container that is less-than-or equal using std::lower_bound (that finds greater-than-or-equal), and have a comparison predicate for my type , f.e.
bool valComp(MyType lhs MyType rhs){ return lhs.value_ < rhs.value_; }
Can I somehow concisely call reverse std::lower_bound with reversed arg... | A lambda is quite short:
// std::lower_bound(myVec.rbegin(), myVec.rend(), myVal,
[&valComp](const auto& l, const auto& r) { return valComp(r, l); }
// );
The standard built-in solution would be std::bind
// std::lower_bound(myVec.rbegin(), myVec.rend(), myVal,
std::bind(valComp, std::placeholders::_2, std::pl... |
65,683,336 | 65,712,880 | How can I run the application written in Golang as a Windows service | I cannot use the screenshot application that I developed with the Win32 api as a Windows Background service.
I install and run it as a Windows background service, I have no problem so far.
My problem: The service doesn't give me a printout. Doesn't take a screenshot.
I tried making another simple app. I tried sending a... |
If a service is running in the security context of the LocalSystem
account but does not include the SERVICE_INTERACTIVE_PROCESS
attribute, it uses the following window station and desktop:
Service-0x0-3e7$\default. This window station is not interactive, so
the service cannot display a user interface. In addition, pro... |
65,683,926 | 65,683,941 | error declaring function C++ - Expected ';' at end of declaration list & Expected ')' | I am attempting to define a function and running into several errors.
I am able to define one function successfully like this:
void simulatedFixture(int fixAddress);
however when I attempt to define the next function like this:
void addFixture(bool simShow; int x; int y; int w; int h; int universe; int address; int ch... | Parameters should be separated by comma ,, not by semicolon ;.
See e.g. here for more details in layman terms:
https://www.geeksforgeeks.org/functions-in-c/
https://www.cs.auckland.ac.nz/references/unix/digital/AQTLTBTE/DOCU_056.HTM
Or here for precise technical reference:
https://en.cppreference.com/w/cpp/language/fun... |
65,684,259 | 65,685,302 | Using boost::format with std::vector | It is possible to use boost::format with std::vector<std::string> like below.
std::vector<std::string> name = {"some", "name"};
boost::format("%s, %s") % name[0] % name[1];
Since I have a large vector, I would like to use them together without manually writing indices:
std::vector<std::string> name = {"som... | Check out this sample:
#include <vector>
#include <string>
#include <iostream>
#include <boost/format.hpp>
auto format_vector(boost::format fmt, const std::vector<std::string> &v) {
for(const auto &s : v) {
fmt = fmt % s;
}
return fmt;
}
int main() {
std::vector<std::string> name = {"some", "... |
65,684,293 | 65,829,359 | Visual Studio 2019 - how to manually edit .props/solution file to force c++17/c++latest standard? | We decided to upgrade our solution, that we are able to use c++17 standard.
The solution itself has a lot of projects and I am aware how to setup this manually through the properties of each of them (Project properties -> Configuration Properties -> C++ Language Standard e.g.), but this is something I want to avoid. I ... | Just in case somebody will search for it you need to add:
<ItemDefinitionGroup Condition="'$(VisualStudioVersion)' >= '15.0'">
<ClCompile>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
</ItemDefinitionGroup>
to the .props file you are using (condition check is not necessary).
In case of ... |
65,684,630 | 65,685,810 | compact form of many for loop in C++ | I have a piece of code as follows, and the number of for loops is determined by n which is known at compile time. Each for loop iterates over the values 0 and 1. Currently, my code looks something like this
for(int in=0;in<2;in++){
for(int in_1=0;in_1<2;in_1++){
for(int in_2=0;in_2<2;in_2++){
// .... | The n bits in_k can be interpreted as the representation of one integer less than 2^n.
This allows easily to work with a 1-D array (vector) d[.].
In practice, an interger j corresponds to
j = in[0] + 2*in[1] + ... + 2^n-1*in[n-1]
Moreover, a direct implementation is O(NlogN). (N = 2^n)
A recursive solution is possible... |
65,685,036 | 65,685,108 | How can I initialize an array of its length equal to the return of a const int method? | What I'm trying to accomplish is this:
inline const int size() { return 256; }
int main()
{
int arr[size()];
return 0;
}
But Visual Studio gives me an error when initializing arr[size()]:
expression must have a constant value
Is there a way to accomplish what I want without using global variables, Macros, ... | Drop the inline and const and add constexpr specifier instead, to solve the issue:
constexpr int size() { return 256; }
now you can use it as array size like:
int arr[size()];
In C++ (not C) length of arrays must be known at compile time. const qualifier only indicates that a value must not change during running time... |
65,685,138 | 65,685,265 | Replacing a range between two iterators in C++ | Assume I have two non-constant iterators begin and end. I want to completely replace the range between begin and end with values, that are between two other iterators. I know with non-constant iterators I can use the following syntax.
*begin = *result.begin();
*end = *result.end();
But this will only change the values... | Using std::copy(), it can be done like this:
#include <iostream>
#include <vector>
#include <algorithm>
void printVector(const std::vector<int>& v) {
bool first = true;
std::cout << '{';
for (int i : v) {
if (!first) std::cout << ", ";
std::cout << i;
first = false;
}
std::c... |
65,685,157 | 65,685,727 | C++ : Alternative to constructor initializer lists without assignment? | I'm facing the following problem:
I want to pass the _partHandlePtr to the constructor of _currUnmanaged and _extUnmanaged but getting errors like "memory access violation occurred at address 0x00000010, while attempting to read inaccessible data". I also tried to initialize both instances after 2) but the problem is ... | I suspect that what you're aiming for is to have one vector of "handles" that is shared (initially) with the two "unmanaged" members.
That would look something like this:
class DerivedCollect
{
DerivedCollect(
const IGCollect& inputCollect,
Handle handle) :
_partHandles(std::make_shared<st... |
65,685,879 | 65,687,316 | Is it possible to reference a C++ project from a C# project? | I'm trying to call some C++ I've written from some C# (also my code) and having troubles with Interop/PInvoke getting a populated int[] back. Is there a way I could just add a compile-time reference to the C++ project from the C# project and call the functions within it as though it were just another C# class library?... | your code doesn't write to the content of accumulationsPointer but overwrite the pointer itself with address of accumulation
it should be something like this
for (auto index = 0; index < numberOfAccumulations; index++, accumulationsPointer++)
{
auto accumulation = input * ((index + 1) * accumulationFactor);
*acc... |
65,686,537 | 65,688,638 | Fails to load Python module with Python 3 | #include <Python.h>
#include <fstream>
#include <iostream>
#include <string>
#include <filesystem>
#include <sys/types.h>
#include <dirent.h>
static const char * sPythonCode =
"class Test :\n"
" def __init__(self) : \n"
" self.Disc_ = 0. \n"
" def getset(self) : \n"
" self.Disc_ = 7. \n"
" return sel... | You should call __import__('importlib').invalidate_caches() each time you modify modules folders to let C Python knows it must read directories again.
|
65,686,665 | 65,686,996 | How to detect wrong subtractions of signed and unsigned integer in C++? | I have legacy code performing a subtraction of signed int with an unsigned int and a cast of the result to a float. It was giving expected result with Visual Studio 6 to 2013. With Visual Studio 2017 (15.6.3) the result is not the expected one.
I have simplified the code to this:
unsigned int uint = 10;
signed ... | MSVC is not able to detect this even with /W4 /c or /Wall and additional linter is required, e.g. clang-tidy is detecting this (courtesy to Stephen Newell).
When using g++ compiler, you are looking for -Wsign-conversion compiler option.
|
65,686,806 | 65,687,324 | filling 2D array with dummy data and input form txt file not working | hi so i need to fill an 2D array of dummy values like x with values form txt file, the "x" are there to fill in empty cols if file.txt has little or no data my file.txt looks like this
1 23 3 42 5 63 4 . 5
-2 1 43 95 55 5 43 2 -6
. 2 3 -4 5 43 -4 4 35
82 61 3 5 -5 65 . 2 6
my c++ looks like this
#include <iostream>
#... | Problem:
When you use std::getline you take the whole line instead of taking one number.
"." is not a valid argument for std::stod so it will throw an std::invalid_argument exception.
Solution:
Use the std::ifstream::operator>> instead.
Reformat the file and change the "." to the value it should represent (I guess i... |
65,686,833 | 65,736,168 | Finding zoom center coordinates on a zoomed-in image | I'm attempting to implement mouse cursor centered zoom in/out on an image. For simplicity, assume I only need to zoom in/out in the horizontal axis. I am using Qt with QPainter to draw my scene and QWidget:: mouseWheelEvent override to calculate a zoom factor and a zoom position.
To put it into words before showing the... | Well I got it working. I use inverse matrix to compute the new zoom center, but once zoomed in, it will not match the mouse position, so the entire image must be translated additionally by the inverted_position - mouse_position. Here's the final code for any future wanderers. m_extraTranslation is obviously initialised... |
65,688,740 | 65,688,841 | Can alias templates have default template parameters? | The following code is very short, but causes different compilers to behave disagree:
#include <tuple>
template <typename T = int, typename... Ts>
using tpl = std::tuple<T, Ts...>;
tpl x; // I would assume this should be std::tuple<int>
Clang and MSVC say that template argument deduction doesn't work for alias templa... | C++20 introduces CTAD for alias templates
An alias template may indeed have default template arguments, and it is legal to have default template arguments to template parameters that are followed by a template parameter pack, as per [temp.param]/14:
If a template-parameter of a class template, variable template, or al... |
65,689,253 | 65,689,409 | How to erase or change element while iterating over vector in C++? | I was in the middle of creating a simple sieve of Erathostenes function when I stumbled upon one obstacle. In to order to accomplish the highest efficiency in this task I wanted to use only a vector. Here is the current code:
vector<int> sieveOfErathostenes(int N) {
vector <int> result(N, 1);
for(int ... | Instead of erasing elements in the middle of the vector, you should write the results from the beginning of the vector and eliminate the unused elements in the end of vector.
int finalSize = 0;
for(int i = 0; i < N; i++)
{
if(result[i] != 0) {
result[finalSize++] = i;
}
}
result.resize(f... |
65,689,330 | 65,689,484 | Write an algorithm that compute the Euler's number until | My professor from Algorithms course gave me the following homework:
Write a C/C++ program that calculates the value of the Euler's number (e) with a given accuracy of eps > 0.
Hint: The number e = 1 + 1/1! +1/2! + ... + 1 / n! + ... = 2.7172 ... can be calculated as the
sum of elements of the sequence x_0, x_1, x_2, .... | |x_(i+1) - x_i| > = eps means "the distance between the next value of x (x_(i+1)) and the current value of x (x_i) is greater or equal to epsilon".
Your code is adding one to x and checking a very different condition:
(euler+1) - euler >= epsilon
This means: "iterate until euler + 1 (not the next value of euler!) minu... |
65,689,680 | 65,689,879 | C++ why is my pointer taking me to some weird location as soon as I call a->val? | I'm working through a LeetCode problem with two linked lists that need to be added up.
It looks like my code is correctly generating a new list, with the expected nodes 7, and 9, followed by null, yet when I try to print out the results I'm running into an issue. I can see that the value of a->val is 7, but as soon as ... | ans is allocated on the stack, locally. As soon as you return from addTwoNumbers, there is no guarantee the data is still there, i.e. it's undefined behavior. GCC warns about it:
<source>: In function 'ListNode* addTwoNumbers(ListNode*, ListNode*)':
<source>:45:12: warning: address of local variable 'ans' returned [-Wr... |
65,690,012 | 65,690,124 | c++ std::vector: sum in a vector position its previous value | I need to accomplish a simple task, which seems to be forbidden in c++ language.
I have a simple std::vector<double> a{1.,2.,3}and I want to do this simple thing:
for(int i=0; i<a.size();i++)
a[i]=a[i]+0.1; //or a[i]+=0.1;
or, likely, with pointers:
for (auto it = a.cbegin(); it != a.cend(); ++it)
*it=*it+0.1;
... | I do not see an error in this for loop
for(int i=0; i<a.size();i++)
a[i]=a[i]+0.1;
except that the compiler can issue a warning that there is a comparison of a signed integer with an unsigned integer in the condition of the loop.
You could write the loop like
for( std::vectpr<double>::size_type i=0; i < a.size(); i... |
65,690,027 | 65,690,176 | Using "extern" keyword without #include "file.h" | Right now i read Stephen Prata's book about C++, and learning about extern keyword and its usage. So i have a question. Can i type "extern int var a;" without including a file that defines and initializes this 'a' variable?
#include <iostream>
//#include "vars.h" Not including the file with 'a' variable
using namespac... | The extern keyword will denote that the variable has external linkage.
When a name has external linkage, the entity it denotes can be
referred to by names from scopes of other translation units or from
other scopes of the same translation unit.
From https://eel.is/c++draft/basic.link
If you attempt to run the above c... |
65,690,187 | 65,690,717 | Why does using two getline function together, second one doesn't take the \n character? | #include <bits/stdc++.h>
using namespace std;
int main(){
string str1, str2;
getline(cin, str1); // aaa
getline(cin, str2); // bbb
cout << str1 << " " << str2; // aaa bbb
return 0;
}
Why does the 2nd getline() not take \n, when I input str1 as "aaa\n"?
cout should print "aaa" not "aaa bbb".
| From the description of std::getline at cppreference (bolding mine):
...until one of the following occurs... b) the next
available input character is delim, as tested by Traits::eq(c, delim),
in which case the delimiter character is extracted from input, but is
not appended to str.
So, in your case, the newline char... |
65,690,490 | 65,690,758 | Why my C++ code is not taking all inputs before execution? It just take a input and print all cout content | this is my code and result
I just create a structure first and then set up a for loop to use that elements and take input from user and display at last of the code part.
please help me
#include <iostream>
using namespace std;
struct person
{
char name[30];
int age;
int phone_no;
}p[5];
int main()
{
... | The problems are:
The phone number is too large to fit into int in this environment. It should be stored as strings.
>> operator for cin leaves newline characters at the stream, so the next cin.get() will read that and stop there. You can read until newline character and drop what are read via cin.ignore(). Note that ... |
65,690,570 | 65,699,092 | How to set tab based cookies in WebView2? | How can I set a cookie which would be applicable for just a specific tab in the browser ? Chrome keeps cookies separated for normal mode and incognito mode. What i'm trying to achieve is similar to this but i want to do that for every tab in normal mode.
| If I understand correctly, you have a tab based application with a WebView2 on each tab and you want a separate environment for each WebView2 so they have their own cookies.
There's an example of setting up an environment here: Getting started with WebView2
Go to Step 3.
The second argument to CreateCoreWebView2Environ... |
65,690,691 | 65,690,777 | How to emulate class template argument deduction pre-C++17? | I am working on removing sscanf() calls from a C++ codebase and replacing them with the std::stringstream implementation described here: https://www.quora.com/Is-there-a-C-alternative-to-sscanf . The relevant code is:
template<class Char>
class imatch
{
const Char* s;
public:
imatch(const Char* x) :s(x) ... | A common workaround was to provide a make_xx function that can rely on traditional template argument deduction:
template <typename T>
imatch<T> make_imatch(const T* t) {
return imatch<T>(t);
}
|
65,690,897 | 65,691,095 | Error during recursive class template instantiation for overloaded multiplication operator in C++ | I am trying to implement a template class for a very special box, called H Box.
It holds a vector of numbers with the size being always a power of 2. That is essentially it, when it comes to the structure - it only contains an array and has the [] operator overloaded to access its elements. The thing is - it has a very... | When using template recursion you can't provide the base case as a simple if. The reason for this is that the whole function needs to be able to compile even if some code is unreachable. A simple if (false) is not enough.
To fix this you can either use C++17's if constexpr or partial template specialization:
// using... |
65,691,101 | 65,706,319 | Why is Windows's SetCursorPos ineffective when certain programs are in foreground? | The win32 API's SetCursorPos moves the mouse to a location on the screen. However, sometimes it does nothing.
See the following C++ code (Visual Studio 16.8.1, Windows 10)
#include <iostream>
#include <windows.h>
int main()
{
while (true)
{
std::cout << "Hello World!\n";
SetCursorPos(100, 200);... | The answer is admin privileges.
As explained by @chris in the comments, some programs have elevated privileges, and when they are in the foreground (and thus, accepting user input), Windows doesn't let programs without elevated privileges control the mouse or keyboard. Otherwise, untrusted programs would be able to uti... |
65,691,779 | 65,692,423 | How to make the height coordinates start from the top? | I am trying to make an overlay for one game. I need to make it so that I can use normal coordinates to draw objects instead of -1 and 1. That is, the left must start at zero, and the right must equal the window width. So it is with height. The top should start at zero and the bottom should be equal to the height of the... | See OpenGL 2.1 API Specification - 2.10 Rectangles:
Rect (x1, y1, x2, y2);
is exactly the same as the following sequence of commands:
Begin(POLYGON);
Vertex2(x1, y1);
Vertex2(x2, y1);
Vertex2(x2, y2);
Vertex2(x1, y2);
End();
Therefore, the geometry can be discarded when Face Culling is enabled. Disable face cullin... |
65,691,843 | 65,691,997 | C++ primer 5th edition: A bitset to represent a sequence of integers | I am asked on C++ primer 5th edition this exercise:
Exercise 17.10: Using the sequence 1, 2, 3, 5, 8, 13, 21, initialize a bitset that has a 1 bit in each position corresponding to a number in this
sequence. Default initialize another bitset and write a small program to turn on each of the appropriate bits.
In fact I... |
How can 1000000010000100101110 represent the sequence 1, 2, 3, 5, 8, 13, 21?
Numbers in base 2 are typically written MSB first - most significant bit first - and typically numbered or indexed from right to left, from the least significant bit, starting from 0 (or 1).
1000000010000100101110
^ ^ ^-- bi... |
65,691,999 | 65,694,529 | How does this compile in Arduino IDE? | I have noticed the following code, which is obviously invalid C++, compiles in Arduino IDE (using AVR-GCC):
// The program compiles even when the following
// line is commented.
// void someRandomFunction();
void setup() {
// put your setup code here, to run once:
someRandomFunction();
}
void loop() {
// put y... | This is what we call Forward declaration and in C++ it only requires you to declare the prototype of the function before attempting to use it, instead of defining the whole function.:
Taking as example the following two pieces of code:
CODE A:
#include <Arduino.h>
void setup(){}
void AA(){
// any code here
}
void loo... |
65,692,233 | 65,692,421 | Boolean Function Always Return False | It must be true but function returns false. I can't understand. How it is possible?
#include <iostream>
using namespace std;
bool Testing() {
static int Variable = 0;
if (Variable == 1) return true;
else {
Variable = 1;
Testing();
}
return false;
}
int main()
{
if (Testing())... | When main() calls Testing() for the 1st time, the static variable is created and initialized to 0. So the if evaluates to false, the variable gets updated to 1, and Testing() is called a 2nd time. And like any other function, that call will return to the place where it was called from.
Inside the 2nd Testing() run, t... |
65,692,611 | 65,695,253 | Boost spirit x3: compound attribute compile time error (enum class) | I was recently writing a simplest possible parser using boost spirit x3. It contains 2 rules: identifier and a single character operator. Naturally, I implemented the operator using a symbol table, which produces an operator type enum class. Identifiers are parsed as std::strings. However, the code refuses to compile w... | std::variant is not yet supported for attribute compatibility.
Changing to boost::variant makes it compile: Compiler Explorer
Alternatively, here are ways to make it actually work if you require std::variant: Transitioning Boost Spirit parser from boost::variant to std::variant
#include <boost/spirit/home/x3.hpp>
#in... |
65,693,178 | 65,693,253 | Combining two QTransform maps | Combining two QTransform map operators gives me a result that is not what I expected. Could anyone possibly point out the problem? Thanks.
#include <QApplication>
#include <QtGui>
#include <QtCore>
#include <QDebug>
int main(int argc, char *argv[])
{
(void)argc; (void)argv;
QPointF pnt(20, 20); // normal coor... | The transformations are not commutative (Tx * Ty is differente to Ty * Tx) so the order of interest in your case must be:
QTransform flipy_then_shift = flip_y * shift;
Output:
flipped QPointF(20,-20) shifted QPointF(20,80)
combined QPointF(20,80)
|
65,693,318 | 65,693,430 | is the pointerdiff between members of different objects in containers the same? | The c++ macro offsetof is just defined behaviour when used on standard layout types. As I understood this is because the compiler can change the memory layout of the data depending on the context of the code it runs. (For example when a variable is never used)
However, what I wondered is whether all elements stored in ... |
what I wondered is whether all elements stored in a range share the same layout
Of course they do, otherwise traversing through multiple elements of the same type and accessing the same member of each element would be impossible. The offset of a given member is relative to the element's type. That offset is the sam... |
65,693,742 | 65,694,144 | C++ How to implement callbacks? | I'm trying to implement a Button class in C++. Here's how it's going so far:
button.h:
class Button {
private:
unsigned short x;
unsigned short y;
std::string text;
std::function<void()> onClickFunction;
public:
Button(unsigned short x, unsigned short y, std::string ... | You probably want:
this->toggleGridButton = Button(x, y, "Toggle Grid", [this]() { this->toggleGrid(););
|
65,694,043 | 65,703,695 | vertex buffer renders later vertexes in front of earlier ones | While trying to render a cube with OpenGL I noticed that the vertexes I defined later in my positions array rendered on top of the ones defined earlier:
It is hard to see in the image but if you look closely, you can see the back faces of the cube are rendering on top of the faces closest to the camera. When I move th... | At first I tried enabling the depth test (I wasn't aware it was off by default) But then nothing rendered. The problem was not clearing the depth buffer every frame with glClear(GL_DEPTH_BUFFER_BIT).
Problem Solved!
|
65,694,307 | 65,694,792 | Is it possible to group structs for use with std::variant | I'm designing a class to represent data from 10+ sources using std::variant. Each source may have 10 different messages, so the variant will represent 100 different underlying structs.
Understandably I'd like to declare the std::variant without listing 100 types in the declaration:
std::variant<Type1, Type2, Type3........ | You might do:
using Source0Types = std::variant<Type0, Type1, Type2, Type3, .., Type9>;
using Source1Types = std::variant<Type10, Type11, Type12, Type13, .., Type19>;
// ..
using SourceTypeVariant = std::variant<Source0Types, Source1Types, .., Source9Types>;
The caveat here is that you have two levels of variant (for... |
65,694,728 | 65,694,729 | Why can I not compare chrono::weekday's with operator<()? | In the new C++20 <chrono> header there is a std::chrono::weekday type. Why can I not compare weekdays with operator< and thus sort them?
auto wd1 = Wednesday;
auto wd2 = Thursday;
if (wd1 < wd2) // compile-time error
{
// do something
}
test.cpp:14:13: error: invalid operands to binary expression (std::chrono::w... | In the view of <chrono>, no Wednesday is not less than Thursday.
Thursday - Wednesday does indeed equal days{1}. However Wednesday - Thursday equals days{6}, not days{-1}.
In modern culture, there is disagreement about which day is the first day of the week. The <chrono> library takes the view that we do not have to ... |
65,694,993 | 65,695,045 | What kind of grammar is int& b = (&a)[15] | int a = 30;
int& b = (&a)[15];
std::cout << b << std::endl;
I print it , find that this is a random value that doesn't make any sense
|
What kind of grammar is int& b = (&a)[15]
int& b is a variable. Its name is b and its type is reference to int. type variable_name = expression is syntax for defining and initialising a variable.
& is a unary operator. For fundamental types, it is the addressof operator. Thus &a gives the address of the object referr... |
65,695,052 | 65,706,745 | Can a project be build even missing a lib? | There is a Visual Studio project which refers to opencv_world440.lib but it does not seem to be available on vcpkg.
I understand vcpkg has opencv 4.3. In order to proceed I tried to remove opencv_world440.lib from
VS, project, properties, linker, input, additional dependencies and the project build successfully then. B... | Try to use dependency walker to see if it's something related to libraries. Anyway that error code stands for STATUS_NO_MEMORY as described here which indicates a problem with memory (can also be something OS level!?), sorry but I cannot be more specific.
EDIT
"opencv_world" appears to be just one DLL holding all the O... |
65,695,371 | 65,695,734 | Reading arguments from a text file using < | I have a txt file called test.txt that looks like this,
hi this is a test
and I have a c++ file called selection_sort.cpp that looks like this,
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
cout << argc << endl;
for (int i = 0; i < argc; i++) {
cout << argv[i] << en... |
What am I missing or doing wrong? I need to use the <.
This is a shell operator that sends the content of the file to the standard input of the application.
./app < text.file
Will read the file text.file and send the conent to the standard input of the application app. In C++ you can read the standard input via std:... |
65,695,613 | 65,697,389 | Where is there an understandable documentation for the wdm.h c header | I was wondering if there was a possible way to embed regular c/c++ inside a windows kernel mode driver. I've been doing some research and it seems pretty impossible, considering that the print function already looks like
KdPrintEx((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "KmdfHelloWorld: KmdfHelloWorldEvtDeviceAdd\n"))... | So You want a Pretty Good Documentation for learning about Drivers? Here are few I Suggest
Microsoft KMDF : https://learn.microsoft.com/en-us/windows-hardware/drivers/gettingstarted/writing-a-very-small-kmdf--driver
So If you are a starter learn with User mode Drivers as they are easier to use
Microsoft UMDF : https://... |
65,695,879 | 65,696,790 | Converting string literal to JSON Array and sending using HTTP Post Request | I'm trying to send a post request over an ESP32 WiFi module using an Arduino IDE. Although the response received is 200, I receive a formatting error with the JSON body object. How should I format the JSON object?
Here is what the original JSON object looks like that I need to send:
{
"method":"passthrough",
"params"... | The value of requestData needs to escape the quotes within the string. Otherwise the payload that is sent is malformed JSON with the value of requestData terminated too early.
This can be done with:
http.POST("{\"method\":\"passthrough\",\"params\":{\"deviceId\":\"9006765C87CD29BC37447E490C4C91F819143376\",\"requestDat... |
65,696,266 | 65,699,542 | How to Declar Member Function with both `requires` and `-> return_type` | I want to write a class template, which:
A<float> have just a member variable val;
A<int> have a member variable val and a member function make_unsigned (return unsigned).
I want to explicitly state the return value of make_unsigned. Here is my code.
#include <concepts>
template<typename T> struct A
{
T val;
... | std::make_unsigned is not SFINAE friendly, so you have to
don't be explicit on return type, use auto/decltype(auto):
auto make_unsigned() requires std::signed_integral<T>
{
return static_cast<std::make_unsigned<T>::type>(val);
}
add a "friendly" trait (a trait which doesn't make the program ill-formed with inval... |
65,697,034 | 65,697,215 | std::enable_if to conditionally disable a template constructor | I am trying to get a simple example to work to understand how to use std::enable_if, here is the problem:
I am reading the textbook C++ Templates The Complete Guide by David Vandevoorde, Nicolai M.Josuttis, Chapter 6, Section 5.
This chapter mentions: "std::enable_if to prevent being able to copy objects of a class tem... | That class, as it is defined, is somewhat useless.
a) You can't default-initialize it, default constructor is removed. C<int> c_int; is ill-formed.
b) You can't create it from value, e.g. C<std::string> c_string1(some_str);, because that constructor does not exist.
Essentially you can copy it, but you cannot create it,... |
65,697,453 | 65,697,538 | Why does defining an empty copy ctor beside a deleted default ctor make a value initialization with empty list fail? | In short, why the code below behaves like described in the comments?
struct A
{
A() = delete;
//A(const A&) {} // uncommenting this...
};
int main()
{
A a{}; // ... breaks this
//A(); // this fails in either case because of `A() = delete;` only
}
What part of the standard (or at least a page on cppref... | Without the user-provided copy constructor, A is an aggregate. Yes, even though we deleted the default constructor. It's something that was addressed in C++20.
So, prior to C++20, A a{}; is aggregate initialization, and so doesn't use the deleted constructor. When you uncomment the copy constructor, A stops being an ag... |
65,697,614 | 65,698,061 | How to remove certain specified value from vectors? | mySongs is a vector that store a collection of songs input by the user. In the if statement, the program will check the elements in the vector with user input. If match, it will delete that specified value from the vector. When I look for the solution, I see someone recommend to use remove/erase idiom:. But when I impl... | This error is due to the fact that the class Song does not have an == operator. This can be solved in one of the two following ways
If you have access to the source code of Song then
add the following function to it. please note that const is necessary
bool operator == ( const Song& song)
{
//Do the comparison c... |
65,697,655 | 65,800,340 | populate combobox items from c++ file in Qt quick | I am a novice in QT QML.
I have a list of strings in a c++ file(audioinput.cpp) and one combo-box in a QML file(voiceCall.qml).
I need to populate items of this combo-box with strings of that list .
my list definition is ->
List<Qstring> lst .
my combobox defintion is :
ComboBox {
id: comboBox
x: 200... | C++:
QQuickView view;
QStringList comboBoxModel = { "one", "two", "three" };
view.rootContext()->setContextProperty("comboBoxModel", &comboBoxModel);
view.setSource("main.qml");
view.show();
QML:
Combobox {
model: comboBoxModel
}
QStringList inherits from QList<QString>.
|
65,697,697 | 65,698,631 | Euler's number with stop condition | original outdated code:
Write an algorithm that compute the Euler's number until
My professor from Algorithms course gave me the following homework:
Write a C/C++ program that calculates the value of the Euler's number (e) with a given accuracy of eps > 0.
Hint: The number e = 1 + 1/1! +1/2! + ... + 1 / n! + ... = 2.7... | One problem with computing Euler's constant this way is pretty simple: you're starting with some fairly large numbers, but since the denominator in each term is N!, the amount added by each successive term shrinks very quickly. Using naive summation, you quickly reach a point where the value you're adding is small enou... |
65,697,833 | 65,697,994 | Why is parameterized constructor called, when we assign an integer value to an object of a class? | The code is:
#include<iostream>
using namespace std;
class Integer
{
int num;
public:
Integer()
{
num = 0;
cout<<"1";
}
Integer(int arg)
{
cout<<"2";
num = arg;
}
int getValue()
{
... | Your parameterized constructor is a converting constructor. C++ is all too happy to make an expression valid, so long as it can find a reasonable conversion sequence to make things work. So as already noted, 10 is converted to an Integer temporary, which then gets assigned by the compiler generated operator= (Integer c... |
65,698,013 | 65,698,434 | How to build and run Vivek's Virtual Camera on Windows 10? | https://github.com/roman380/tmhare.mvps.org-vcam
I gave look on Vivek's Virtual Camera. I could not understand how to compile and run this project.
In the project I am seeing two directories
alok@LAPTOP-DG8ME7Q5:/mnt/c/Users/alokm/tmp/vcam/vcam$ tree .
.
├── Bin
│ ├── VCam.ax
│ └── VCamD.ax
└── Filters
├── Dll.... | Filters folder contains source code for the project. .DSP is the project file for old Visual Studio (or was it Visual C++ 6.0 yet?). If current Visual Studio cannot convert the project file you should still be able to create a new DLL project file and add the source code files.
You need DirectShow BaseClasses to build ... |
65,699,514 | 65,699,684 | Use of "#define FOO" with no value assigned - other than as include guard? | I'm trying to understand Steinberg's VST SDK.
What's the use of this:
#define PLUGIN_API
without assiging any value in a header file and then PLUGIN_API occurring in many member functions' declarations/definitions for example like this:
Steinberg::tresult PLUGIN_API initialize (Steinberg::FUnknown* context) SMTG_OVER... |
What's the use of this:
#define PLUGIN_API
Of this particular line, none really. Basically to allow compilation of other parts of code, of functions declarations, where this macro is used. Without defining it to empty, other parts of code could error when compiling.
like this:
Steinberg::tresult PLUGIN_API initial... |
65,699,988 | 65,700,374 | standard library not raising error for duplicate definition | Why does this not return an error for duplicate function definition since the c++ standard library does external linkage.
This shouldn't be function overloading since its is type double(double,double) which is the exact same as the pow defined in math.h
#include <iostream>
#include <math.h>
double pow(double base, dou... | The function signature pow(double, double) is reserved to the language implementation in the global namespace. By defining a reserved name, the behaviour of the program is undefined.
Then the behaviour of the program is undefined, you are not guaranteed to be "raised an error for duplicate definition".
Related standard... |
65,700,121 | 65,702,449 | how a cpp function should return "-1" as char*? | For a problem statement, there is a case in which a cpp function returning char* needs to return value as -1. How to return char* with negative integer value?
Sample pseudo-code where the function is decrypting the mystring and returning a character at given index and if not found should return -1:
char * decrypt(char ... |
if not found should return -1:
This is a bad design. Pointers have a conventional way to represent a value that doesn't point to anything: The null pointer. A more conventional design is to return nullptr when result is not found.
If you use an arbitrary value such as -1, it would be quite difficult for the caller to... |
65,700,159 | 65,705,168 | Delay/latency in synchronous boost asio with unix socket | I write a client-server app which uses asynchronous boost asio networking (boost::asio::async_write and boost::asio::async_read) on server side and synchronous calls (boost::asio::write and boost::asio::read) on the client end. Because underneath I use protocol buffers, if I want to send a buffer from the client, first... |
On the other hand glueing size at the beginning of the data isn’t an option, because then I would do a copy.
Scatter-gather to the rescue: https://www.boost.org/doc/libs/1_75_0/doc/html/boost_asio/reference/buffer.html#boost_asio.reference.buffer.buffers_and_scatter_gather_i_o
So, this could help:
void WriteProtobuf(... |
65,700,593 | 65,701,425 | std::jthread runs a member function from another member function | Here is my code:
#include <iostream>
#include <zconf.h>
#include <thread>
class JT {
public:
std::jthread j1;
JT() {
j1 = std::jthread(&JT::init, this, std::stop_token());
}
void init(std::stop_token st={}) {
while (!st.stop_requested()) {
std::cout << "Hello" << std::end... | According to the useful comments, I have rewritten the class code as below:
class JT {
public:
std::jthread j1;
JT() {
j1 = std::jthread(&JT::init, this);
}
void init() {
auto st = j1.get_stop_token();
while (!st.stop_requested()) {
std::cout << "Hello" << std::endl... |
65,702,336 | 65,703,003 | C++20 Concepts: out-of-line-definition fails with MSVC but not in GCC or clang | Consider this little code snippet
namespace nsp
{
template<typename T>
concept Addable= requires(const T& a,const T& b)
{
{a + b} -> std::convertible_to<T>;
};
template<Addable T>
struct C
{
C();
};
}
template<nsp::Addable T>
nsp::C<T>::C() {};
As shown here GCC (10.2)... | This behavior is an observable deviation in MSVC that has been seen usually in the context of templates and SFINAE. MSVC tends to have difficulty with out-of-line definitions of templates that have qualifications when the declarations are not qualified (from being in the same namespace). I've often encountered this whe... |
65,702,923 | 65,703,058 | partial specialised template as template argument | let's say for example I have a function foo() taking a parameter pack Ts. The function however should only accept the parameter pack Ts if there is exactly one type meeting the requirements of std::is_integral. The following code I've written does exactly that as expected.
#include <type_traits>
template <template <ty... | It seems to me you're looking for
template <template <typename, typename> typename predicate, typename T, typename... Ts>
inline constexpr std::size_t count_if = ((predicate<T, Ts>::value ? 1 : 0) + ...);
template <typename T, typename... Ts>
void foo(T) requires (count_if<std::is_same, T, Ts...> == 1) {}
But, this w... |
65,703,206 | 65,723,049 | Why does GCC's ifstream >> double allocate so much memory? | I need to read a series of numbers from a space-separated human-readable file and do some math, but I've run into some truly bizarre memory behavior just reading the file.
If I read the numbers and immediately discard them...
#include <fstream>
int main(int, char**) {
std::ifstream ww15mgh("ww15mgh.grd");
doub... | It really doesn't. The number 59,302,487 shown by valgrind is the sum of all allocations, and does not represent the actual memory consumption of the program.
It turns out that the libstdc++ implementation of the relevant operator>> creates a temporary std::string for scratch space, and reserves 32 bytes for it. Thi... |
65,703,217 | 65,727,005 | Call function from other file - identifier not found on Unreal Engine? | I have class named HealthComponent and GamemodeBase with .cpp and .h files. In GamemodeBase header file i had declared void funtion HealthBar(float fHealth). I want to call it in HealtComponent implementation file but i getting indentifier not found error. I include GamemodeBase.h so IMO this should work.
GameModeBase.... | You need a reference to the GameMode in order to call non static functions on it.
If the HealthComponent is attached to the GameMode, you can simply cast the owner of the HealthComponent to the GameMode.
AMyGameModeBase* GameMode = Cast<AMyGameModeBase>(GetOwner());
GameMode->HealthBar(fHealth);
Alternatively you can ... |
65,703,501 | 65,705,129 | Cpp in VSCode - How to compile to other folder | I'm using VSCode to program in C++.
When I run the code (using the "Code Runner" extension), the .exe file stored in the same folder.
I've seen in many projects that they stored it in a /bin folder.
Is it posibble to automatically store it in there? (Also create the /bin folder if it doesn't exists).
Thank you!
| I figured out 2 ways how to do your task:
In this scenario you have to create bin folder manually
So let's configure your VScode extension
From extension page follow this step to open settings
From extension page follow this step to open settings
In settings tab open "Edit in settings.json"
In your Json find "code-r... |
65,703,593 | 65,703,854 | Stack around the variable 'product' was corrupted | I'm trying to multiply two matrices of different column lengths together, and the product matrix is correct, but it's been corrupted somehow.
// main.cpp
#include <iostream>
#include "Matrix.h"
using std::cout, std::cin;
int main() {
Matrix<> a({
4, 5, 7, 3,
2, 1, 2, 1,
6, 2, 8, 9,
... | The runtime error Stack around the variable '*' is corrupted pops up when you try to access memory which isn't allocated. This line matrix[i][i] = identity; poses the issue in the default constructor.
Explanation:
In this matrix,
Matrix<> a({
4, 5, 7, 3,
2, 1, 2, 1,
6, 2, 8, 9,
9, 3, 6,... |
65,704,649 | 65,704,706 | Why my regex doesn't work in c++ but it works with Python? | I am using RegEx to extract substrings in a RPN formula. For example with this formula:
10 2 / 3 + 7 4
I use this RegEx to extract substring (I hope it could return {"10", "2", "/", "3", "+", "7", "4"}
[0-9]+|[\/*+-])\s?
Firstly, I try it with Python:
s = r"([0-9]+|[\/*+-])\s?"
text = "10 2 / 3 + 7 4"
x = re.findall(... | \ is used as a escape sequence in C++. You have to write \ as \\ to pass it to regex engine.
regex rgx("([0-9]+|[\\/*+-])\\s+");
Another option is using raw string literal (since C++11):
regex rgx(R"(([0-9]+|[\/*+-])\s+)");
|
65,704,700 | 65,704,772 | QByteArray indexOf deprecated? | I'm using Qt 5.15.2, I have the following code:
QByteArray arybytData = mpsckIncoming->readAll();
bool blnHTTP = false;
if ( arybytData.startsWith("GET / HTTP/") == true ) {
//HTTP Request, probably from browser, jump to end of header
const QString cstrHeaderTerminator("\r\n\r\n");
... | Only QByteArray::indexOf(const QString& str, int from) is deprecated. The other overloads are still available.
What you're meant to do is to use QString::toUtf8(), QString::toLatin1() or QString::toLocal8Bit() to retrieve a QByteArray representing the QString which can then be passed to the non-deprecated overloads of ... |
65,705,448 | 65,705,579 | C++ : pointer on member function |
namespace Borg
{
class BorgQueen
{
public:
BorgQueen();
bool move(Borg::Ship *ship, Destination dest) {return ship->move(dest);}
void fire(Borg::Ship *ship, Federation::Starfleet::Ship *target) {ship->fire(target);}
void destroy(Borg::Ship *ship, Federation::Ship *target) {ship->fire(target);}
void... | The right-hand side of .* is not resolved in the context of the left-hand side, but in the current scope.
Like this:
int main()
{
bool (Borg::BorgQueen::*go)(Borg::Ship *ship, Destination dest) = &Borg::BorgQueen::move;
Borg::BorgQueen queen;
//...
(queen.*go)(something something...);
}
Q is your objec... |
65,705,708 | 65,706,008 | Is there a way to make sure inherited member is not accessible in derived classes, while still keeping the benefits of public inheritance? | If I have a class that holds a protected member that derived classes will inherit:
class Base1
{
protected:
int baseMember_;
};
class Base2 : public Base1
{
public:
void printBaseMember
{
std::cout << baseMember_ << std::endl;
}
};
How can I make sure that baseMember_ will be inaccessable in c... |
Is there a way to make sure that derived classes will not have access to a protected member, while still using public inheritance?
You can change the access mode of an inherited member by a using declaration:
class Base1
{
protected:
int baseMember_;
};
class Base2 : public Base1
{
public:
void printBaseMemb... |
65,706,205 | 65,707,492 | Numerically stable way to compute sqrt((b²*c²) / (1-c²)) for c in [-1, 1] | For some real value b and c in [-1, 1], I need to compute
sqrt( (b²*c²) / (1-c²) ) = (|b|*|c|) / sqrt((1-c)*(1+c))
Catastrophic cancellation appears in the denominator when c approaches 1 or -1. The square root probably also does not help.
I was wondering if there is a clever trick I can apply here to avoid the difficu... | The most interesting part of this stability-wise is the denominator, sqrt(1 - c*c). For that, all you need to do is expand it as sqrt(1 - c) * sqrt(1 + c). I don't think this really qualifies as a "clever trick", but it's all that's needed.
For a typical binary floating-point format (for example IEEE 754 binary64, but ... |
65,706,618 | 65,706,760 | Function does not return a value, while using a vector in c++ | The below function works fine when using an integer array(minNumCoins) but does not return anything while using a vector instead of an array. Can anyone tell me why?
int dp_change(const vector<int> &coins, int money, int n){
//vector<int> minNumCoins(n);
int minNumCoins[n];
int numCoins = 0;
minNum... | In this piece of code:
for( int m =1 ; m<=money; m++){
minNumCoins[m] = 100000;
m can become out of bounds if money >= n, which it is in your example input (money=20, n=2). As a result, your program crashes before it gets to output anything.
|
65,707,161 | 65,707,699 | MysteryLinkedList Tracing code using pen and paper | So, I stumbled upon this problem recently. I can't figure out what is happening in this code. I used a compiler to create and linked list and inserted the values in it to get the answer
check this code first the question is as follows what will happen to the linklist after it is passed in this function.
front -> 25 -> ... |
When curr has smaller data than its next, it just moves the point to the next node.
When curr has bigger data than curr->next, it moves the node curr->next to the first of the link.
When curr is same with curr->next, it deletes the next node.
It would work like this.
curr25 -> 40 -> 50 -> 20 -> 50 -> 10 -> 8 -> 60 -... |
65,707,236 | 65,707,413 | Why does filtering out ASCII value 32 (' ') from a stringstream with the following function also filter out '\n' and '\t'? | I have been practicing different ways to filter out undesired garbage characters from a nlohmann::json object to an std::string, and I just finished the following function giving me a pretty good result (ignoring that I'm writing beginner sloppy code of course):
//This string is what I'm testing with as input.
std::str... | In this code:
while (ss >> c) {
if (c == ' ') {
The if will NEVER evaluate as true, because operator>> skips leading whitespace by default, which includes spaces, tabs, and line breaks. So c will never be a whitespace character like ' '.
Either:
use std::noskipws, like @WhozCraig suggested in comments:
while (s... |
65,707,394 | 65,708,009 | How to make a function in C++ to delete a node from the linked list (node can be any except the first node) which matches the searched key | I have this function named DeleteData which I use to delete any node from my linked list.
void DeleteData(Node *node, int key)
{
Node temp;
//If key is in the first node itself
if (node != NULL && node->read_data() == key)
{
temp = *node->next;
node->next = NULL;
delete node;
cout <<... | For starters the parameter that specifies the head node shall have a referenced type.
The function can be declared and defined the following way
bool DeleteData( Node * &head, int key )
{
Node **current = &head;
while ( *current && ( *current )->read_data() != key )
{
current = &( *current )->next;... |
65,707,661 | 65,710,601 | access the unique pointer across the class without using reference or shared pointer | Posting Again,
Unique pointer stored in class A, need to access in class B without using shared ptr or reference?. (ie)The owner of that pointer should remain only in class A and the semantic ownership of the pointer should not be shared.
func1, func2, func3 all the places unique pointer is accessed many times.
code sn... |
the semantic ownership of the pointer should not be shared
Don't don't pass around access to the unique_ptr at all. Pass around a raw pointer to the ABC that the unique_ptr owns, eg:
class A
{
public:
static A* Get();
A();
ABC* Getter();
private:
std::unique_ptr<ABC> uniquePointer;
};
A::A()
{
u... |
65,708,047 | 65,708,453 | Refactoring to enum to enum class shadows namespace | In previous codebase I have :
namespace E {
enum { a, b }
void foo();
}
I want to refactor to using enum class:
enum class E : int { a, b }
namespace E {
void foo();
}
However this fails to compile because now namespace E can't be used as it has same name as enum.
Is there a way around this ?
Basically I still want t... | Other way to do that is define an enum class and then map its values to respective constants:
namespace E {
enum class MyEnum { a, b };
constexpr auto a = MyEnum::a;
constexpr auto b = MyEnum::b;
void foo() {}
}
https://godbolt.org/z/zY5v3G
This way strong type checking will be introduced and dependin... |
65,708,899 | 65,713,157 | How to initialize a constexpr std::array with templated constexpr member functions? | This is a follow up of my question given here. In the end I want to create a constexpr std::array containing text with an appended running index.
I wanted to try a different approach than in the previous question.
Nearly everything, what I do in the below code is constexpr. But maybe, it is simply the old problem of re... | Your code generating compile time dangling pointers (which should be impossible) on MSVC.
To fix:
template <const size_t numberToConvert, const char* Text>
class Converter {
// blah
std::array<char, ArrayLength> buf{};
constexpr operator std::array<char, ArrayLength>() const { return buf; }
constexpr std::array... |
65,709,037 | 65,709,809 | How to use std future and async with threading in a for loop with a shared resource as param? | I got stuck with an implementation problem in my threading practice project. I know what I want to achieve but I dont know how. I am new in the topic of std::future and std::async so I am not even sure if the implementation is even possible in the way I imagined.
I have a NuclearPP class which has this function(It shou... | First - define what information each thread shall provide.
In this case - it is probably something like this:
struct Result
{
error_codes::NPPCoreErrorCode error;
float produced_energy;
};
So your future type is std::future<Result>.
Then start your work in many threads:
std::vector<std::future<Result>> resu... |
65,709,771 | 65,720,600 | Receiving Unicast and Multicast on the Same Socket in C++ | I need to receive both unicast and multicast UDP on the same socket and port at a specific IP. Based on other questions asked here, this should be possible. I can set all the options and bind successfully, but I cannot receive any traffic. It just stays blocked at read() call.
I have tried many different options, such ... | Assuming you're using Linux, when receiving both unicast and multicast traffic on the same socket you must bind to INADDR_ANY, i.e. 0.0.0.0. If you bind to a specific interface you won't get multicast traffic, and if you bind to a multicast address you won't get unicast traffic.
So set up your bind address like this:
... |
65,710,351 | 65,710,671 | Operator overloading for nested struct only working as member or friend function | This C++ code compiles and runs perfectly, as I expect:
template <typename T> struct S { T *p; };
template <typename T>
bool operator == (S<T> &a, S<T> &b) { return a.p == b.p; }
int main () { int i; S<int> a = {&i}, b = {&i}; return a == b; }
However, if I try to do the same with the inner struct of an outer str... | First, the compiler gets confused by missing typename. The error message really is confusing and can be silenced via:
template <typename T>
bool operator == (typename O<T>::I &a, typename O<T>::I &b) {
return a.p == b.p;
}
Now the actual problem gets more apparent:
int main () {
int i;
O<int>::I a = {... |
65,710,667 | 65,723,312 | OpenGL Textures: how do I create an image path? | I'm stuck trying to upload textures here:
// The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path.
unsigned char *data = stbi_load(FileSystem::getPath("resources/textures/container.jpg").c_str(), &width, &height, &nrChannels, 0);... | I found the fix: It was indeed as Joshua said, "move the file into the correct project directory so the relative path will work". So in my project I created a folder called 'Textures' and added the textures there, and I called the texture using:
unsigned char* data = stbi_load("Textures/container.jpg", &width, &height,... |
65,710,668 | 65,710,976 | How do I construct a struct in a union? | t2 below causes the following compile error
test.cpp:14:15: error: cannot initialize a member subobject of type 'E' with an rvalue of type 'int'
Test t2{2, {{2, 3}}};
^
test.cpp:14:18: error: cannot initialize a member subobject of type 'void *' with an rvalue of type 'int'
Test t2{2... | It's pretty simple, only the first (non-static) member of the union can be initialized in this way. Read more:
http://www.hellenico.gr/cpp/w/cpp/language/aggregate_initialization.html
|
65,711,459 | 65,712,951 | Why can't I use listS for the VertexList template parameter for boost graph's isomorphism test? | The following program is based on an example provided by the boost website https://www.boost.org/doc/libs/master/libs/graph/example/vf2_sub_graph_iso_multi_example.cpp
#include <boost/graph/vf2_sub_graph_iso.hpp>
using namespace boost;
int main() {
typedef property<edge_name_t, char> edge_property;
typedef propert... | vecS has an implicit vertex index.
listS doesn't. Therefore it uses the internal property vertex_index_t but you didn't initialize it.
Here's modernized version that tests all combinations of vecS/listS possible for graph1/graph2:
Live On Compiler Explorer
#include <boost/graph/vf2_sub_graph_iso.hpp>
#include <boost/pr... |
65,712,091 | 66,050,521 | In C++20, how do I write a contiguous iterator? | C++20 has explicit library support for std::contiguous_iterator_tag. Some STL algorithms (e.g. std::copy) can perform much better on contiguous iterators. However, I'm unclear on exactly how the programmer is supposed to get access to this new functionality.
Let's suppose for the sake of argument that we have a complet... | The last version in my question seems to be the most correct. There is just one subtlety to watch out for:
MyIterator::value_type should be the cv-unqualified type of the pointee, such that someone could write value_type x; x = *it;
MyIterator::element_type should be the cv-qualified type of the pointee, such that som... |
65,712,210 | 65,713,736 | Upgrading gcc to 8/9 trigger "Error: unsupported instruction `vmovdqu'" while gcc-7 runs fine | I compile Apache Arrow (https://arrow.apache.org/) with CMake 3.15 and gcc/g++-7 (7.5.0) and it goes well. However, when I upgrade gcc/g++ to 8(8.4.0) and 9(9.3.0) with the same CMake version, I got the following errors:
/tmp/ccrlCxYO.s: Assembler messages:
/tmp/ccrlCxYO.s:5651: Error: unsupported instruction `vmovdqu'... | TLDR: I found the solution is to add "-mavx512bw" to target_compile_options
Please continue reading if you want to hear more detail about the root cause, and how I found it.
After googling a bit I found this webpage talking about a bug of GNU AS. https://www.mail-archive.com/bug-binutils@gnu.org/msg30524.html
That webp... |
65,712,793 | 65,713,067 | Is assignment of bit field with different Endianness implementation specific | As we know, we have two types of Endianness: big endian and little endian.
Let's say that an integer takes 4 bytes, so the layout of the integer 1 should be 0x01 0x00 0x00 0x00 for little endian and 0x00 0x00 0x00 0x01 for big endian.
To check if a machine is little endian or big endian, we can code as below:
int main(... | Let's say we have a struct:
typedef struct {
unsigned char a1 : 1;
unsigned char a2 : 1;
unsigned char a6 : 3;
}Bbit;
and a definition:
Bbit byte;
Suppose byte is stored in a single byte and is currently zeroed out: 0000 0000.
byte.a1 = 1;
This sets the bit called a1 to 1. If a1 is the first bit, then by... |
65,712,971 | 65,713,002 | How to initialize and return vector of vectors more compactly? | How to initialize and return vector of vectors more compactly ? The code below seems bloated and repetitious for the two cases when K==1 and K==N.
std::vector< std::vector<unsigned int> > Foobar(const unsigned int K, const unsigned int N)
{
std::vector< std::vector<unsigned int> > res;
if (K == 1)
{
... | if (K == 1)
{
return {{N}};
}
if (K == N)
{
return {std::vector<unsigned int>(N,1)};
}
|
65,713,221 | 65,713,371 | Splitting A String List Into Components | I am trying to figure out a way to split the following string:
"2.000000, ["Me", [13, 11], "You"], [12.000000, 15.000000]"
such that I have a string vector with the following contents:
2.000000
["Me", [13, 11], "You"]
[12.000000, 15.000000]
I started with using , as the regex, however this splits the sublists ([...])... | Straight-forward solution is to store balance of [] brackets on current prefix. [ gives +1, ] gives -1. Also don't update balance, ignore [ and ] inside "strings"
int balance = 0;
// If balance is 0, you're outside your list:
// [ ... ]
// ^ here ^ or here
// If balance is >= 1, you're inside list:
// [ ... ]
// ... |
65,713,466 | 65,713,606 | How can I read as string and then make it int vector; | Lets say I have txt.file as
7 8 9
10 11 1
14 15 1
I want to keep the line and then put them in a nested vector. I have done this:
#include <sstream>
#include <fstream>
using namespace std;
int main()
{
vector<vector<int> > data;
vector<int> temp;
string file;
cout << "Enter a file: ";
cin >> f... | Among the multitude of things wrong.
You use std::cin and std::cout, but never #include <iostream>
You use std::vector, but never #include <vector>
You use std::string, but never #include <string>
You append your populated line vector, but never reset the vector.
Note that you don't have to do (4) if you simply ensur... |
65,713,719 | 65,713,760 | C++ Priority queue with custom type and comparator not working | I'm trying to use the C++ STL priority queue with a custom type and comparator, but no matter how I put it, I keep getting an error.
Does anyone know what the issue might be? I'm trying to copy the syntax from documentation but nothing has been working...
The custom type is a pointer to the ListNode class used in LeetC... | You should specify a function pointer type, but not a function type as the template argument for priority_queue.
Change
priority_queue<ListNode*, vector<ListNode*>, decltype(compare)> pq(compare);
to
priority_queue<ListNode*, vector<ListNode*>, decltype(compare)*> pq(compare);
// ... |
65,713,957 | 65,714,544 | Standard input to C++20 range adaptors w/o temporary variables | I can read ints from standard input, transforming them into odd or even, writing the results to standard output:
std::vector<int> v;
std::ranges::copy(
std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(v)
);
std::ranges::copy(
v | std::views::transform([](int a_i... | You can always turn an iterator based algorithm into a view based one with std::ranges::subrange:
std::ranges::copy(
std::ranges::subrange(std::istream_iterator<int>(std::cin), std::istream_iterator<int>())
| std::views::transform([](int a_int){return a_int%2 ? "odd":"even";}),
std::ostream_iterator<const c... |
65,714,054 | 65,714,107 | Function does not stop executing after return statement | I am working in C++ and have written a function but it does not stop the execution after the return statement.
BSTNode* search(BSTNode* root, int data)
{
BSTNode* newroot=root;
int count = 1;
if (root->data == data)
{
newroot=root;
count = 0;
}
else
{
search(root->lef... | Your count variable is useless and should be removed. The recursive calls to search() do not update it, so if (count != 0) is always evaluated as true.
You are also ignoring the return value of the recursive search() calls to stop the search once a matching node is found.
And you are ignoring the possibility of null p... |
65,714,286 | 65,714,311 | Const pointer pointing to non-const data | Consider the following case 1:
const int n = 5;
int* p = &n;
This is invalid, because &n is of type cont int* and p is of type int * (type mismatch error).
Now, consider this case 2:
int k = 4;
int *const p = &k;
This case compiles successfully, without any error. Clearly, p is of type int * const and &k is of type... |
In this case, there is a type mismatch
No; there is no type mismatch in this case. It is a pointer to non-cost and you initialise it with a pointer to non-const.
Alternatively, if you insist on there being a "mismatch", then it is analogous to the following "mismatch":
const int b = 42;
Why is the second case valid... |
65,715,294 | 65,753,497 | How to connect QT and MariaDB. driver not loaded |
Same "QMYSQL driver not loaded" error.
But others people see the QMYSQL in the "QSqlDatabase: available drivers" message.
Why I don't even have it?
| The first thing is to download the connector installer, depending on the version of the compiler you are using, 64 or 32 bits, for c from here:
https://downloads.mysql.com/archives/c-c/
locate the connector installation folder and run these commands.
cd% QTDIR% \ qtbase \ src \ plugins \ sqldrivers
qmake - MYSQL_INCDIR... |
65,715,675 | 65,715,739 | A proper way to disable a class constructor based on a trait of that class | I would like to SFINAE-disable a class template constructor - but the catch is that an enable-disable condition is a trait of that class. Particularly, I would like to enable that constructor only if a specific class method, matching constructor's template arguments, exists in that class.
A simplified example:
struct S... | You can introduce another template parameter with default value S, and use it for SFINAE. E.g.
template <class T, class X = S, class = decltype(std::declval<X>().set_value(std::declval<T>()))>
S(T && x)
{
set_value(std::forward<T>(x));
}
LIVE
|
65,715,998 | 66,372,348 | xerces: how to take xml node with a particular tag? | with Qt library I can take a node with a particular tag name with:
QDomElement tmp = root.firstChildElement("A");
QDomElement tt = tmp.firstChildElement("C");
with a xml file with this structure:
<A>
<B></B>
<C></C>
</A>
With xerces, how can I do this?
| xercesc_3_2::XMLPlatformUtils::Initialize();
// create the DOM parser
xercesc_3_2::XercesDOMParser* parser = new xercesc_3_2::XercesDOMParser;
parser->setValidationScheme(xercesc_3_2::XercesDOMParser::Val_Never);
parser->parse(fileName.c_str());
// get the DOM representation
xercesc_3_2::DOMDocument* doc = parser->getD... |
65,716,368 | 65,716,748 | Is the volatile qualifier deprecated in c++20? | I just downloaded GCC 10 with c++20 on my embedded project.
However in embedded applications it's quite common to use volatile for Register Struct Mappers.
Since the compiler does not know if the Register value was changed externally by a DMA, it makes sense to "force" a reload of this register.
To increase performance... | You can't use |= anymore, but you can use =, so change this:
(*(volatile uint32_t *)regAddr) |= (1UL << CLK_GATE_ABSTRACT_BITS_SHIFT((uint32_t)name));
To this:
*(volatile uint32_t *)regAddr = *(volatile uint32_t *)regAddr | (1UL << CLK_GATE_ABSTRACT_BITS_SHIFT((uint32_t)name));
|
65,716,519 | 65,716,619 | When is the storage location of static variables in C++ determined? | I have the following simple program:
int main()
{
int x = 5;
static int y = x;
return (0);
}
Compiling it with gcc, it produces error for the line static int y = x; since "initializer element is not constant". I assume this is due to y being a static variable, whose storage location (data/bss) and initial ... | Your program is well-formed in C++ as local variables with static storage duration are initialized not during startup (with some exceptions for constant expressions; not applicable in this example) but at the first time control passes through their declaration, at which point the initializer expression, containing the ... |
65,716,760 | 65,717,400 | Gurobi quicksum syntax in c++ | I need the Syntax to create a sum in a Gurobi-constraint in c++:
EXAMPLE:
I have the variables:
x[i][j]
and the constraint:
sum over all i's from x[i][j] <= 1 for all j's
in Gurobi Python it is:
for i in [list of i's]:
model.addConstr(x[i,j] <= 0 for j in [list of j's])
How is the Syntax for this in c++?
Thanks i... | I found it out:
for (j = 0; j < n; j++)
{
GRBLinExpr expr = 0;
for (i = 0; i < n; i++)
expr += vars[i][j];
model.addConstr(expr <= 1, [name of constrain]);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.