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 |
|---|---|---|---|---|
72,185,378 | 72,185,501 | Does "new CLASS" return CLASS or CLASS* | This may seem really simple, but I don't know how to actually make a program that tells me this.
| As stated in comments, new will always give you a pointer.
But as new implies delete, I strongly advise you to take a look at a concept call RAII, especially why it's so popular.
|
72,185,932 | 72,191,079 | Sorting a list with indexes of another | I am trying to sort a list of indexes based on a list of string, and I receive bellow error - Segmentation fault. I cannot understand why I receive this error and how to solve it?
#include <iostream>
#include <string.h>
using namespace std;
int main() {
int size = 5;
char* mass[size];
int num[size];
f... | In the inner loop you start with j = size and then num[j] is an out-of-bounds array access.
In modern C++ you would solve this like this:
#include <iostream>
#include <array>
#include <algorithm>
int main() {
const int size = 5;
std::array<std::string, size> mass;
std::array<int, size> num;
for (int i... |
72,186,129 | 72,190,159 | C++ method not calling member method but compiles fine | I'm building a Vulkan Project with CMake and C++. My project compiles fine under MSVC 2019. However, when calling this line:
printf("Before\n"); // The below line is where the program hangs.
const char** e = this->validationLayers->getRequiredExtensions();
this->createInfo.ppEnabledLayerNames = e;
this->createInfo.ena... | enabledLayerCount is the number of elements in the ppEnabledLayerNames array, not the length of the first string. The value you should be assigning is this->validationLayers.size().
Here archive are the spec valid usage requirements for ppEnabledLayerNames and enabledLayerCount.
If enabledLayerCount is not 0, ppEnable... |
72,186,638 | 72,187,438 | Merge similar objects together based on object elements is O(n²). How to make it simpler? | Problem Description
We have a vector<A> v containing for 4 objects. Each object has the following members x, y, z and w. Two objects are considered equal if the have the same x and y. In that case we merge the objects: we merge the vector w and we change the value of z if and only if the value of object that we want to... | You can do it in O(NlogN * MlogM) if you sort the input, and then do a linear pass to merge.
N is the length of v, and M is the length of the A::ws.
bool compare(const A & lhs, const A & rhs) {
return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
}
std::sort(v.begin(), v.end(), compare);
for (auto first = v.beg... |
72,186,671 | 72,186,924 | Is there some way to define a variable as a function such that calling the variable at some given time will return the function's output at that time? | Essentially, I'm trying to do something like
#define foobar foo.bar()
But without the use of #define, so I can write something along the lines of
double foobar = foo.bar();
Obviously, compiling the code above will just define foobar as whatever foo.bar() returns at the time of definition. What I want to do is the abo... |
Obviously, compiling the code above will just define foobar as whatever foo.bar() returns at the time of definition. What I want to do is the above in such a way that using foobar at some time in the code will just use whatever foo.bar() returns at that time, and not whatever it was at definition of foobar.
You want ... |
72,187,143 | 72,187,689 | Need Help Understanding OpenMP Matrix Multiplication C++ code | Here is my Matrix Multiplication C++ OpenMP code that I have written. I am trying to use OpenMP to optimize the program. The sequential code speed was 7 seconds but when I added openMP statements but it only got faster by 3 seconds. I thought it was going to get much faster and don't understand if I'm doing it right.
T... | Matrix size of 1000x1000 with double(64 bit) element type requires 8MB data. When you multiply two matrices, you read 16MB data. When you write to a third matrix, you also access 24MB data total.
If L3 cache is smaller than 24MB then RAM is bottleneck. Maybe single thread did not fully use its bandwidth but when OpenMP... |
72,187,706 | 72,188,107 | makefile, error compiling files from different paths | I have 2 folders, the first folder contains the files I've built, and the second folder contains files I should be using without changing, all the files synchronize and work, already tested by manually compiling them while combined in 1 folder,
CC:=g++
COURSE_DIR:=/home/mtm/public/2122b/
HW_DIR:=$(COURSE_DI... | Your problem appears to be:
HW_FLAG=-I -I$(HW_DIR)
This sets the include path to -I/home/mtm/public/2122b/ex2/ which (as a relative path, since it begins with -) would be a (presumably nonexistent) directory under the current directory.
it should be:
HW_FLAG=-I $(HW_DIR)
GCC's command line documentation shows that -I... |
72,187,797 | 72,189,169 | How to generate CRC7 based on lookup table? | I am trying to implement CRC-7/MMC checksum with pregenerated lookup table. This is the code so far:
#include <iostream>
#include <string>
#include <cstdint>
using namespace std;
/* CRC-7/MMC
Poly: 0x09
Xorout: NO
Init: 0x00
Check value: 0x75 for "123456789"
*/
uint16_t CRC7_table[256];
void generate_crc7_table() {... | Note that the CRC definition you pointed to includes refin=false refout=false. That CRC is not reflected, so it is computed with left shifts, not right shifts.
Given that, and the fact that the CRC is less than eight bits in length, you will also want to keep the seven bits at the top of the byte being used for calcula... |
72,187,895 | 72,188,038 | Is passing literal string as template parameter not good | I'm working on a c++ project and I just defined a function as below:
template<typename... Args>
void func(Args&&... args) {}
Then, call it like this:
func("abc"); // char[4]?
func("de"); // char[3]?
My question is if the compiler will deduce two independent functions, one is for char[4] and the other is for char[3]?... |
My question is if the compiler will deduce two independent functions, one is for char[4] and the other is for char[3]?
It will.
If I call many func with const char* as above, the compiler will generate many independent functions?
You don't call func with const char*. If you did call func with only const char* then... |
72,188,061 | 72,188,786 | Why does new int() work like an array in C++? | As far as I understand
int* p = new int();
Is something like creating an int with a constructor. If so why does the following code work like an array?
int* p = new int();
*p = 5;
p[1] = 15;
for (int i = 0; i < 2; i++)
cout << p[i] << endl;
5
15
|
Why does new int() work like an array in C++?
p[1] is equivalent to *(p + 1), it simply dereferences the pointer to access the value stored in the memory location where it points to, the notation is similar to array notation, it's allowed and is preferred to pointer notation because it's more readable.
As far as I ... |
72,188,255 | 72,271,889 | How can I make sure `iostream` is available to the linker? | I have the following C++ code in a file called helloworld.cpp:
#include<iostream>
int main()
{
std::cout << "Hello, World!\n";
}
I would like to compile this manually so I can really understand how the compilation steps work with gcc, namely:
Preprocessing
Compilation
Assembly
Linking
This article gives some us... | Based on the comments and posted answer I realized that the blog from which I was copying those commands makes things more complicated than they really need to be for my purposes. It's definitely possible to isolate every step of the compilation process using solely the g++ command. Here's a Makefile I came up with:
al... |
72,188,334 | 72,334,146 | What is a "container detachement" in the C++11 ranged based loop over QList? Is it a performance only problem? | This question contains some proposals for working around the problem, I would like to understand more in depth that exactly the problem is:
QList<QString> q;
for (QString &x: q) { .. }
Is it so that unless the container is declared const, Qt makes a
copy of the list and then iterates over that copy? This is not amo... | Copy-on-write (=Implicit sharing) concept
It is important to understand that copy-on-write (= implicit shared) classes externally behaves like "normal" classes that perform a deep copy of their data. They only postpone this (potentially) expensive copy operation as long as possible. A deep copy is made (=detaching), on... |
72,188,544 | 72,188,571 | error: expected unqualified-id before ‘friend’ | In my .cpp file I got
Student:: friend istream& operator>>(istream &input,Student &a){
input>>a.AM>>a.name>>a.semester>>;
return input;
}
And in my .h file I got
friend istream &operator>>(istream &input,Student &a);
I keep getting that error and I don't know what to do.Any help?
| Rewrite the definition like
istream& operator>>(istream &input,Student &a){
input>>a.AM>>a.name>>a.semester>>;
return input;
}
The specifier friend is used only in a declaration of a friend function within a class.
And a friend function is not a member of the class granting friendship.
|
72,188,762 | 72,189,678 | Can I replace an if-statement with AND? | My prof once said, that if-statements are rather slow and should be avoided as much as possible. I'm making a game in OpenGL, where I need a lot of them.
In my tests replacing an if-statement with AND via short-circuiting worked, but is it faster?
bool doSomething();
int main()
{
int randomNumber = std::rand() % 10... | I agree with the comments above that in almost all practical cases, it's OK to use ifs as much as you need without hesitation.
I also agree that it is not an issue important for a beginner to waste energy on optimizing, and that using logical operators will likely to emit code similar to ifs.
However - there is a vali... |
72,188,924 | 72,189,239 | C++ Segmentation fault when changing value of pointer within method call | I'm programming a server - client application with a shared utils.cpp.
So the server and client use the (in utils.h) predefined methods:
int listening_socket(int port);
int connect_socket(const char *hostname, const int port);
int accept_connection(int sockfd);
int recv_msg(int sockfd, int32_t *operation_type, int64_t ... | Pointers are variables that should be use to point to some allocated memory.
In your initialization, you made your pointers point to NULL, i.e, no memory.
And after that you are trying to change the value of nothing. That's why you are getting a segmentation fault.
You should either:
Declare some local variables and m... |
72,189,469 | 72,189,929 | Embedding Python to C++ Receiving Error Segmentation fault (core dumped) | This is my first go at Embedding Python in C++.
I am just trying to create a simple program so I understand how it works.
The following is my code.
main.cpp
#define PY_SSIZE_T_CLEAN
#include </usr/include/python3.8/Python.h>
#include <iostream>
int main(int argc, char *argv[]){
PyObject *pName, *pModule, *pF... | After each and every one of those statements, you will need to check for errors, using something of the form:
if (varname == NULL) {
cout << “An error occured” << endl;
PyErr_Print();
return EXIT_FAILURE;
}
This will check if the python layer through an error; and if so will ask it to print the Python tra... |
72,189,626 | 72,189,823 | simplest way to prevent accesing array beyond range in C | I'm wondering if there is any easier way to prevent accessing array beyond range than using if() statement.
I have switch case code for arduino like this with many cases:
switch(a){
case 3:
case 27:
for (int i = 0; i < 8; i++){
leds[ledMapArray[x][i]] = CRGB(0,255,0);
leds[ledMapArr... | The Answer was written when the question used the tag c, not c++ and edited later. The FastLED library is clearly implemented in C++.
You could wrap the array access in a function that implements the checks.
The following function assumes that the array leds and ledMapArray are file scope variables. Otherwise the funct... |
72,190,379 | 72,249,840 | lld runs LTO even if -fno-lto is passed | I have a CMake project with several subprojects that create static libraries built with -flto=thin.
The project has a lot of tests that are linked against the aforementioned libraries. With LTO it takes a lot of time to build tests, therefore I have disabled LTO for tests using -fno-lto.
What I noticed though, is that ... | If you compile the libraries with -flto then, at least for gcc, the object files will only contain the intermediate language and no binary code.
That means when you link them into your test cases compiled with -fno-lto there is no binary code to link to. The linker has no choice but to first compile the intermediate la... |
72,190,405 | 72,191,099 | Switching between threads with C++20 coroutines | There is an example of switching to a different thread with C++20 coroutines:
#include <coroutine>
#include <iostream>
#include <stdexcept>
#include <thread>
auto switch_to_new_thread(std::jthread& out) {
struct awaitable {
std::jthread* p_out;
bool await_ready() { return false; }
void awai... | switch_to_new_thread actually creates a new thread, it doesn't switch to a new thread. It then injects code that resumes the coroutine in it.
To run code on a specific thread, you have to actually run code on that thread. To resume a coroutine, that specific thread has to run code that resume that coroutine.
Here you... |
72,190,700 | 72,190,753 | "explicit template argument list not allowed" with g++, but compiles with clang++? | I have test code as below.
#include <iostream>
#include <vector>
using namespace std;
template<typename Cont>
class Test
{
template<typename T, typename = void> static constexpr bool check = false;
template<typename T>
static constexpr bool check<T, std::void_t<typename T::iterator>> = true;
public:
... | It should be ok to write a partial specialization in any context
It is listed as a gcc bug but it is not fixed yet: gcc bug
As a workaround you can place the specialization outside class context like:
template<typename Cont>
class Test
{
template<typename T, typename = void> static constexpr bool check = false;
p... |
72,190,768 | 72,190,943 | Error: 'else' without a previous "if' even though there is not a semicolon | I made a very simple program but even though there is not a semicolon, I still get this error. Please ignore the weird intention of this program, it's for comedy purposes.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int john, jeff, philip, joe, dave;
cout << "Hello and welcome to th... | For starters in this expression statement
cin >> john, jeff, philip, joe, dave;
there is used the comma operator. It is equivalent to
( cin >> john ), ( jeff ), ( philip ), ( joe ), ( dave );
So all the operands after the first operand
( jeff ), ( philip ), ( joe ), ( dave )
do not produce any effect.
It seems you ... |
72,191,489 | 72,192,351 | Serving HTML as C array from Arduino code - String size limit problem | I've been working on a HTML / websocket server on a Wiznet W5100S-EVB-Pico, programmed in the Arduino IDE. It all worked fine up until now but I'm running into, I think, a string size limit. I guess it is in the way the code handles the const char but I don't know how to do it properly.
I hope someone is willing to hel... | Edit: There is a bug in the ethernet library shown in this post.
I don't know if it affects you; you should look at your library implementation.
I'm assuming that web_client is an instance of EthernetClient from the Arduino libraries.
EthernetClient::println is inherited from Print via Stream and is defined in terms o... |
72,192,073 | 72,192,161 | Strange C++ output with boolean pointer | I have the following code:
#include <iostream>
using namespace std;
int main() {
int n = 2;
string s = "AB";
bool* xd = nullptr;
for (int i = 0; i < n; i += 100) {
if (xd == nullptr) {
bool tmp = false;
xd = &tmp;
}
cout << "wtf: " << " " << (*xd) << " " ... |
if (xd == nullptr) {
bool tmp = false;
xd = &tmp;
}
tmp is an automatic variable. It is destroyed automatically at the end of the scope where the variable is declared. In this case, the lifetime of the object ends when the if-statement ends. At that point, the pointer xd which pointed to the variable becomes... |
72,192,352 | 72,192,527 | Template argument dependent using/typedef declaration | How can I write a using (or typedef) declaration that is dependent on a template argument?
I would like to achieve something like this:
template<typename T>
class Class
{
// T can be an enum or an integral type
if constexpr (std::is_enum<T>::value) {
using Some_type = std::underlying_type_t<T>;
} else {
... | This is exactly what std::conditional is for:
template <class T>
class Class
{
using Some_type = typename std::conditional_t<std::is_enum<T>::value, std::underlying_type<T>, std::type_identity<T>>::type;
};
std::type_identity is from C++20, which if you don't have is easy to replicate yourself:
template< class T >... |
72,193,031 | 72,193,077 | No match for ‘boost::shared_ptr::operator=’ | This is the code I have that causes the error below:
class CAlternateMerchantList
{
public:
CAlternateMerchant::SP m_pAlternateMerchantList[MAX_PLAYER_LIST];
int m_nMax;
int m_nCur;
CAlternateMerchantList()
{
int i;
for (i = 0; i < MAX_PLAYER_LIST; i++)
m_pAlternateMerch... | You don't need to set boost::shared_ptrs to null. They have a default constructor which does it automatically. You can simply delete the entire for loop.
I suggest also using an initialization list for m_nMax and m_nCur.
CAlternateMerchantList()
: m_nMax(0), m_nCur(0)
{
}
|
72,193,320 | 72,193,543 | Why no std::as_const overload for pointer types | I just came across std::as_const and I was surprised by the output of the last line in the following snippet:
#include <cstdio>
#include <utility>
struct S {
void foo() { std::puts("foo: non const"); }
void foo() const { std::puts("foo: const"); }
};
int main() {
S s;
s.foo(); // foo: non const
st... | The purpose of std::as_const is to be able to reference a non-const lvalue as a const lvalue so that it isn't modifiable in the context in which it is used. In other words std::as_const(x) should be a shorthand for writing
const auto& y = x;
and then using y.
It already does that well, so there is no need for special ... |
72,193,329 | 72,193,561 | Why are integer return values (such as -1 or 0) used in C and C++? | When I read C or C++ code, I often notice that functions return integer values such as -1 or 0. My question is: why are these integer return values used?
It appears that -1 is returned by functions when they are unable to do what they were intended to do. So are these values like HTTP response status codes? If so, how ... | I assume that you refer to the return value of main. This is what the C++ standard says about it:
[basic.start.main]
A return statement ([stmt.return]) in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argum... |
72,193,426 | 72,216,043 | Native WebRTC crashes in webrtc::PeerConnectionInterface::RTCConfiguration destructor | I'm writing a WebRTC client in C++. It needs to work cross platform. I'm starting with a POC on Windows. I can connect and disconnect to/from the example peerconnection_server.exe.
Per the Microsoft "getting started" tutorial (https://learn.microsoft.com/en-us/winrtc/getting-started), I'm using the WebRTC "M84" rele... | Turns out this is specific to not only Windows/MSVC, but to DEBUG mode. In release mode, this doesn't happen for me. Apparently, it's caused by some linkage mismatch. If you compile with a given /MDd or /MT switch, etc. you'll run into such issues if you link to other libs or dlls which don't agree on that detail. (... |
72,193,730 | 72,235,510 | Generating a call graph with clang's -dot-callgraph with multiple cpp files, and a sed command | I tried Doxygen, but it was a bit slow, and it generated a lot of irrelevant individual dot files, so I'm pursuing the clang way to generate a call graph.
This answer https://stackoverflow.com/a/5373814/414063 posted this command:
$ clang++ -S -emit-llvm main1.cpp -o - | opt -analyze -dot-callgraph
$ dot -Tpng -ocallgr... | I managed to do it, but it was not really trivial, and clang doesn't really provide options to filter "noisy" symbols.
It is important to know that graphviz cannot magically optimize the layout of a graph, so it's better to generate one graph per object file.
Here is the python filter I came up with to remove a lot of ... |
72,193,865 | 72,193,922 | boolean function returning false even though condition is satisfied to return true in c++. Why? | My function is a simple palindrome algorithm that is supposed to take an input integer (test), turn it into a string (test_s), then reverse that string in a new variable (test_s_reverse) then return true if test_s is equal to test_s_reverse.
bool is_palindrome(int test){
test_s = to_string(test);
test_length = ... | You should use test_length - 1 instead of test_lenght + 1, because in the new reversed string you have some extra characters which you can't see if you print them.
The .length() function returns you exactly the number of characters in the string. So you either go with test_length, but you do i>0, or if you go in the lo... |
72,194,076 | 72,194,243 | Pointer-Interconvertible Types and Arrays of Unions | If I have a union.
struct None {};
template<typename T>
union Storage {
/* Ctors and Methods */
T obj;
None none;
};
pointer-interconvertible types means it is legal to perform the following conversion:
Storage<T> value(/* ctor args */);
T* obj = static_cast<T*>(static_cast<void*>(&value));
It is legal ... | No, it is not legal. The only thing that may be treated as an array with regards to pointer-arithmetic is an array (and the hypothetical single-element array formed by an object that is not element of an array). So the "array" relevant to the pointer arithmetic in objs[i] here is the hypothetical single-element array f... |
72,194,964 | 72,250,620 | Spurious wakeup with atomics and condition_variables | std::atomic<T> and std::condition_variable both have member wait and notify_one functions. In some applications, programmers may have a choice between using either for synchronization purposes. One goal with these wait functions is that they should coordinate with the operating system to minimize spurious wakeups. That... |
My question: should I expect different behavior between std::condition_variable's and std::atomic<T>'s wait functions? For example, should std::condition_variable have fewer spurious wakeups?
std::atomic::wait does not have spurious wake ups. The standard guarantees that a changed value was observed, it says in [atom... |
72,195,181 | 72,195,348 | Using Templates to set function types in a class gives error | So I have this class:
template <typename callBackOne,
typename callBackTwo>
class MyClass { // The class
public:
callBackOne cbo;
callBackTwo cbt;
MyClass(callBackOne cbop, callBackTwo cbtp){
cbop();
cbtp();
}
};
All it does is call the functions you give in ... | The problem is that the explicit template arguments that you're passing are of type void but the function arguments voidFuncOne and voidFuncTwo will be implicitly converted to void (*)() and passed but since there is no conversion from a void(*)() to void you get the mentioned error.
C++17
With C++17, you can make use ... |
72,195,327 | 72,195,437 | indexing an element from a volatile struct doesn't work in C++ | I have this code:
typedef struct {
int test;
} SensorData_t;
volatile SensorData_t sensorData[10];
SensorData_t getNextSensorData(int i)
{
SensorData_t data = sensorData[i];
return data;
}
int main(int argc, char** argv) {
}
It compiles with gcc version 8.3, but not with g++. Error message:
main.c: In ... | Your program is trying to copy a SensorData_t object. The compiler supplies a copy constructor with the following signature:
SensorData_t(const SensorData_t &)
This copy constructor will not work with volatile arguments, hence the compilation error.
You can write your own copy constructor which works with volatile Sen... |
72,195,354 | 72,195,484 | I had try to run a car game through c++ only | As mentioned in the title I try to run a car game developed using only CPP but faced problems in line 20 of my code...
#include<conio.h>
#include<dos.h>
#include <windows.h>
#include <time.h>
#define SCREEN_WIDTH 90
#define SCREEN_HEIGHT 26
#define WIN_WIDTH 70
using namespace std;
HANDLE console = GetStdHandle(S... | You're defining your 'car' array as a 2d (1x1) array, which would need to be initialized like:
char car[1][1] = {{' '}}; // probably not useful (it only holds 1 char)
You probably need to change the size of your array. Something like:
char car[2][3] = { // here car is 2x3, an array of size 2
{ ' ', ' ', ' ' }... |
72,196,298 | 72,197,081 | C++ startup once, listen node input design issue | I’ve build a cpp program that performs the following workflow sequentially:
Read serialized data (0.3 ms)
Receive search metadata (0.00.. ms)
Search data (0.01 ms)
Return search data(0.00.. ms)
Right now, I run the program with nodejs shell exec and serve it with an express api. The api is not used by many users, so r... | You may call C++ directly from nodejs which should save you from overhead either executing the shell or building the socket server.
Eg:
int Feed(const char* searchMetadata) which returns a key of data if you want multiple metadata being saved in C++part.
Then call const char* search(int dataKey, const char* searchingKe... |
72,197,030 | 72,197,264 | How to pass a template function to another function and apply it | // I can't change this function!
template<typename Function, typename... Args>
void RpcWriteKafka(Function func, Args&&... args) {
func(std::forward<Args>(args)...);
}
// I can change this one if necessary.
template<typename FUNC, typename... Args, typename CALLBACK, typename... CArgs>
void doJob(std::tuple<CALLBA... | First, the first parameter type of doJob should be std::tuple<CALLBACK, CArgs...> instead of std::tuple<CALLBACK, CArgs&&...> since CArgs&&
cannot be deduced in such context.
Second, since RpcWriteKafka is a function template, you can't pass it to doJob like this, instead, you need to wrap it with lambda, so this shoul... |
72,197,093 | 72,197,700 | What is the need for having two different syntaxes for specializing data member of a class template | I was writing an example involving specialization of class template where I noticed that the standard allows two different syntax for specialization of a data member as shown below:
template<typename T >
struct C {
static int x;
};
template<>
struct C<bool> {
static int x;
};
//here we cannot write prefix temp... | Explicit specialization declaration of a class template is not a template declaration. [Source]. This means that when we provide an explicit specialization for a class template, it behaves like an ordinary class.
Now we can apply this to the examples given in question.
Example 1
template<typename T >
struct C {
sta... |
72,197,242 | 72,197,410 | What is wrong with my application of SFINAE when trying to implement a type trait? | I needed a type trait that decays enums to their underlying type, and works the same as decay_t for all other types. I've written the following code, and apparently this is not how SFINAE works. But it is how I thought it should work, so what exactly is the problem with this code and what's the gap in my understanding ... | SFINAE applied to class templates is primarily about choosing between partial specialisations of the template. The problem in your snippet is that there are no partial specialisations in sight. You define two primary class templates, with the same template name. That's a redefinition error.
To make it work, we should r... |
72,197,420 | 72,199,804 | std::time() and its dependence on daylight saving | I have a requirement to lock a user, if 3 consecutive login attempts are failed within 15 minutes. I am going to check with the following formula, if third login attempt fails.
if (first_login_attemp_time + 900 <= std::time(nullptr))
{
lockuser();
}
If the first login attempt fails, I set first_log... | The std::time returns UTC time that does not follow daylight saving policies of local authorities. So about daylight savings there are no worries.
Like the cited reference article says most systems implement std::time_t (that std::time returns) as in POSIX standard. In my experience it is all systems that I know of. S... |
72,197,597 | 72,197,782 | c++ constexpr concatenate char* | Context:
In my company we generate a lot of types based on IDL files. Some of the types require special logic so they are handcoded but follow the same pattern as the generated ones. We have a function which all types must implement which is a name function. This will return the type name as a char* string and the func... | From constexpr you cannot return char* which is constructed there... You must return some compile time known(also its size) constant thingy.
A possible solution could be something like:
#include <cstring>
// Buffer to hold the result
struct NameBuffer
{
// Hardcoded 128 bytes!!!!! Carefully choose the size!
ch... |
72,197,716 | 72,197,825 | Why the std::is_array in template function is not distinguishing between int and array type? | In the following code, I am using a template function and type traits to distinguish between an integer type (else case) and array type. I would expect the output to be int and array respectively, instead I get int int with the two calls that instantiates the template functions respectively with an int type and an arra... | The std::is_array does not include the case of std::array; Rather, it only checks if the type is just a normal array type(i.e T[], T[N]). Hence, your if statement lands in the false branch.
You have to provide a custom traits for the std::array for this to happen:
#include <type_traits> // std::true_type, std::false_t... |
72,198,057 | 72,199,333 | use a signal between 2 classes Qt | I have a MainWindow class which contain a QComboBox and a widget which is from another class. This second class contain a QCheckBox and a QComboBox. I want to use a signal to change the checkState of my QCheckBox and the string displayed in my QComboBox from my widget class when the string displayed in my QComboBox fro... | Let's call your widget's name container. We want to connect QComboBox's currentTextChanged(const QString &text) signal to the widget, so we create a slot that corresponds to the signal, let it be chosenTextChanged(const QString& text). We connect them inside MainWindow constructor:
connect(ui->comboBox, SIGNAL(curr... |
72,198,503 | 72,201,908 | Why is a FILE* pointer zero-initialized in C++'s default initialization? | Consider
#include <iostream>
#include <cstdio>
using namespace std;
struct Foo {
FILE* fp;
Foo* mp;
};
int main()
{
Foo f1; // default initialization
cout << f1.fp << '\t' << f1.mp << '\n';
Foo f2{}; // zero initialization / direct-list-initialization
//Foo f2 = {}; // zero initialization ... | You didn't initialize the pointers. They get random (undefined) values (specifically, whatever the runtime happened to leave on the stack during initialization before main was called). Sometimes those values happen to be NULL. C++ didn't initialize them, you just got "lucky". As noted in the comments on your question, ... |
72,198,985 | 72,199,278 | How does this way of computing array-length work? | i am new to c++ and stumbled upon this way of computing the length of an array with pointers which i don't exactly understand. I looked everywhere but nowhere seems to be an explanation on how it works, i just heard that it's supposed to be a bad way of computing array length but why is that and how does it even work?
... |
&array
This is a pointer to the object array. It is a singular object of an array type.
&array + 1
Adding a number to a pointer produces a pointer to a successive sibling of the object in an array of objects. Adding 1 produces the next sibling. For purposes of this pointer arithmetic, singular objects are treated... |
72,199,097 | 72,199,508 | Why does this boolean function return true (74) and the program display 74? | I am just messing around with the function and somehow palindromes returns 74. I am using Visual studio 2022. Was it supposed to not return anything and catch compiler error since false is never returned in the case below?
bool palindromes(string str) {
if (str.length() == 0 || str.length() == 1) return true;
... | Seems that you ignored the warning:
warning C4715: 'palindromes': not all control paths return a value
This is a sin.
|
72,199,799 | 72,228,324 | Are accents and special characters broken in Qt6? | I've got a Qt program that reads from csv files and saves the info into a database.
There was no problem until i tried to update from Qt 5.15.2 to Qt 6.3. Now, when I read from the files, all accents are converted to a question mark.
I've tried using pretty much every way to explicitly interpret a QTextStream or conver... | Okay so after a couple more days of research and trying things it now works. I cannot reproduce the issue but something must have had happened when I used LibreOffice Calc to save the csv encoded as UTF-8 or when I sent that file by email.
I suppose the encoding might have gotten in some way changed or corrupted into s... |
72,200,625 | 72,200,841 | Compiler macro to compare byte size of types | Can this if-statement be replaced with a #if .... macro?
Possibly without having to include (too many) extra headers.
#include <cstdint>
#include <string>
///Parse a string to obtain a fixed width type
inline uint64_t stou64(const std::string& in) {
if (sizeof(unsigned long) == sizeof(uint64_t)) {
return st... | You don't need pre-processor macro for this. The function is well-defined regardless of the size, and the compiler is smart enough to optimise the unused branch away completely.
If you want to be sure that the unused branch is removed even with optimisation disabled, you can use if constexpr. Simply add constexpr after... |
72,201,109 | 72,201,617 | C++ multiple nested template types inside outer template class referring to each other | I am quite new to C++ and I am trying to code a simple version of a list (doubly linked as in STL). The list has a template parameter. Inside the list I define two nested classes, also with different template parameters. Now, I agree, in this case defining the inner classes as templates is completely useless because th... | Two things wrong with that code:
1 You can't use Node before it is declared. So move that private block up top.
2 NodeList<E>::Node<E> must be NodeList<T>::Node<E>, or simply Node<E> as you are already in the Nodelist<T> class.
template <typename T>
class NodeList
{
typedef T value_type;
template <typename E = ... |
72,201,421 | 72,201,606 | How to do is >> std::skipws >> through multiple indices of an array? | Let's say you have std::array<int, SIZE> a, and you have saved each element of a into a file in one line separated by a space. Then you want to read them with a std:istream& is via:
is >> std::skipws >> a[0] >> a[1] >> a[2] >> ... >> a[SIZE-1];
How to write this generically for any value of SIZE. Even though there a... |
How to write this generically for any value of SIZE.
There are control structures for repeating an operation a variable number of times: loops.
For example:
is >> std::skipws;
for(auto& el : a) {
is >> el;
}
|
72,201,447 | 72,201,505 | Template template argument mismatch | The following code
#include <cstdint>
template<typename T>
struct allo{};
template <typename T, std::size_t a = alignof(T)>
struct AA{
constexpr std::size_t align() { return a; }
};
template<template <typename> typename AT>
struct SAR{
};
using UHR = SAR<allo>;
using AHR = SAR<AA>;
int main()
{
UHR u;... | Before C++17, template template parameters must use class instead of typename. In C++17, this restriction got lifted and the keywords are equivalent in this context.
Your issue is actually that AA has two template parameters and you try to bind it to AT which as one. C++17 allowed templates with N non-defaulted paramet... |
72,201,979 | 72,203,340 | Combining regex and ranges causes memory issues | I wanted to construct a view over all the sub-matches of regex in text. Here are two ways to define such a view:
char const text[] = "The IP addresses are: 192.168.0.25 and 127.0.0.1";
std::regex regex{R"((\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}))"};
auto sub_matches_view =
std::ranges::subrange(... | The problem is std::regex_iterator and the fact that it stashes.
That type basically looks like this:
class regex_iterator {
vector<match> matches;
public:
auto operator*() const -> vector<match> const& { return matches; }
};
What this means, for instance, is that even though this iterator's reference type i... |
72,202,639 | 72,202,932 | GPS Coordinates in 4 bytes | I am trying to find a method to store the standard Latitude and Longitude (double---both of 8 bytes) in 4 bytes, and viceversa (i.e. convert these data in the standard 8 byte latitude/longitude). Honestly, it is not clear how to do that. I am programming in C++, so if there is an existing function or library to do that... | Fixed point rational representation is a potential solution for this purpose.
There is no fundamental type for fixed point rational numbers, nor does the standard library provide types implementing them. The idea is fairly simple however: Scale the value of an underying integer such that the range of the underlying int... |
72,204,397 | 72,209,557 | Visual C++ 6.0 - Possible Conversion Loss of Data (Warning C4244) | I am using quite an old compiler, and I believe the compiler has made a bit of a mistake in its warning diagnosis.
typedef unsigned char uint8_t; // 8-bit byte
typedef unsigned int uint32_t; // 32-bit word (change to "long" for 16-bit machines)
typedef struct _sha256_ctx_t
{
... | There's nothing wrong with the compiler in this case
ctx->data[63] = ctx->bit_len; // LINE 156 IS HERE!
ctx->data[62] = ctx->bit_len >> 8;
ctx->data[61] = ctx->bit_len >> 16;
ctx->data[60] = ctx->bit_len >> 24;
ctx->data[59] = ctx->bit_len >> 32;
ctx->data[58] = ctx->bit_len >> 40;
ctx->data[57] = ctx->bit_len >> 48;
c... |
72,204,426 | 72,204,493 | Destroying/removing a static text in c++ win32 | I am using win32 API in c++ and I have a static piece of text. How would I delete the static text when the user presses a button? I can't figure out to do that.
| Assuming you have the window handle hwnd of the STATIC control, you can delete it via DestroyWindow(hwnd) or simply make it not be visible with ShowWindow(hwnd, SW_HIDE).
|
72,204,846 | 72,204,914 | How to Fix MISRA C++ Rule 0-1-4 | The following code violates the MISRA C++ rule 0-1-4:
for (auto &a : b) {
... // The variable a is used only in the for condition.
}
Rule: A project shall not contain non-volatile POD variables having only one use. Variable 'a' is used only once, that is, during initialization.
What I tried:
for (const auto &a : b... | Alas the current C++ grammar requires you to declare a variable when using the range-for form of the for loop:
for (auto& : b) {
is not allowed, despite it having potential applications (such as computing the number of elements in a container).
Writing
a;
or
(void)a;
in the loop body might work depending on the type.... |
72,204,862 | 72,204,942 | What is this std::string constructor doing? | I am trying to write a native host client for a WebExtension browser addon in C++.
I looked for examples and unfortunately only found a couple ones.
There's this simple good looking one I'm following but I don't understand the part where a string is constructed as follows:
json get_message() {
char raw_length[4];
... |
What does string m( message, message + sizeof message / sizeof message[0] ); do?
message decays to pointer to first element, sizeof message / sizeof message[0] is the number of elements in the array, and message + sizeof message / sizeof message[0] is a pointer to the past the end of the array. Note that this is unne... |
72,204,957 | 72,205,281 | Changing a macro in C (or C++) | In other words, how can I redefine a macro based on it's previous definition? Specifically, I want to add a string to the end of a string macro in C++. This is what I've tried so far:
#define FOO "bla"
// code here will read FOO as "bla"
#define FOO FOO ## "dder"
// code here will read FOO as "bladder"
In C++, this re... | This is not possible.
From the gcc documentation (emphasis is mine):
However, if an identifier which is currently a macro is redefined, then the new definition must be effectively the same as the old one. Two macro definitions are effectively the same if:
Both are the same type of macro (object- or function-like).
Al... |
72,205,026 | 72,205,171 | Why do I get an error when I overload the << on the object returned by the + operator overloaded function | class String
{
char* array;
public:
String(const char* s)
{
array = new char[strlen(s) + 1]{ '\0' };
strcpy(array, s);
}
~String()
{
if (array)
{
delete[]array;
}
}
String operator+ (const char* p) //返回对象
{
String temp(p);... | The problem is that the second parameter to overloaded operator<< cannot be bound to an String rvalue since the second parameter is an lvalue reference to a non-const String.
how should I rewrite the overloaded function?
You need to make the second parameter to overloaded operator<< a const String& so that it can wor... |
72,205,459 | 72,205,676 | How can I access public constructor of private nested class C++ | I have a nested private classes Nested and Key and I want that I could using my add_new_object(Key, Nested) function add objects to my my_mmap multimap. But when I try to call that those classes constructors, obviously that it's inaccessible. How can I solve the problem.
class Enclosing
{
private:
class Nested {
... | You seem to misunderstand what it means to declare a type in the private section. Or at least you are not aware of the implications of those types appearing as arguments of a public member function.
Here is your code with definitions added (without a definition for Key and Nested you cannot call their constructor at al... |
72,205,522 | 72,205,873 | GLIBCXX_3.4.29 not found | I am trying to install mujuco onto my linux laptop and everything works until I try to import it into a python file. When I try to import it/run a python script that already has mujuco in it I get the following errors:
Import error. Trying to rebuild mujoco_py.
running build_ext
building 'mujoco_py.cymj' extension
g... | Where does /home/daniel/miniconda3/envs/mujoco_py/lib/libstdc++.so.6 come from? Something bundles a version of libstdc++.so.6 which is older than your system version, and other system libraries depend on the newer version. You should be able to fix this issue by just deleting the file in your home directory.
|
72,205,650 | 72,207,035 | How to create constructor for braced-init-list in c++ without standard library? | I would like to be able to initialize my objects with a brace-init-list:
#include <initializer_list>
template <class T>
struct S {
T v[5];
S(std::initializer_list<T> l) {
int ind = 0;
for (auto &&i: l){
v[ind] = i;
ind++;
}
}
};
int main()
{
S<int> s = {1, 2, 3,... | As a work around one could do something like
#include <iostream>
template <class T>
struct S {
T v[5];
template<typename... Args>
requires (std::same_as<T, Args> && ...)
S(Args... args) {
static_assert(sizeof...(args) <= 5);
int ind = 0;
((v[ind++] = args), ...);
}
};
int... |
72,206,078 | 72,206,168 | What will happen if I pass a mutable lambda to a function as const reference? | What does the code actually do when I pass a mutable lambda as const reference?
Why does not the compiler raise error, is this an undefined operation?
Why f1 and f2 are differnt which f1 uses std::function<void()> and f2 uses auto?
I found a similar question but I still don't fully understand
A const std::function wrap... | In first case both calls of call(f1) are using same instance of std::function<void()>.
In second case call(f2); implicit conversion form lambda to std::function<void()> kicks in and respective temporary object is created. So second call uses new copy of temporary object.
Try transform this code in cppinsights to see th... |
72,206,115 | 72,206,319 | Does C++ let a program compiled by itself to return pointer to an array to be used directly? | For example, if I have some code string like this:
std::string code = R"(
#include<thread>
#include<iostream>
int main()
{
int array[@@size@@];
std::cout<<(size_t)&array[0]<<std::endl;
std::this_thread::sleep(1000000000);
return 0;
}
)";
boost::replace_all(code, "@@size... | As far as C++ is concerned, there may not even be a concept of processes. They are mentioned in the standard, as far as I can tell, only twice.
Once in a recommendation about lock-free atomics, suggesting that they should also work when shared between processes, and once with regards to possible causes of file system r... |
72,207,077 | 72,207,226 | finding max value of a struct construction inside vector c++ | enum class comp {
age,
weight
};
struct person {
int age;
int weight;
static auto max(std::vector<person> x, comp(y)) {
if (comp(y) == comp::age) {
for (person e : x) {
auto max = 0;
for (card e : x) {
if (max < e)
... | here is a corrected version of your code. As cory post shows you can do this with standard algorithms in a much cleaner way
struct person {
int age;
int weight;
static int max(std::vector<person> x, comp y) {
if (y == comp::age) {
for (person e : x) {
auto max = 0;
... |
72,207,152 | 72,207,345 | How can change the value of a member of a base class? | I have three classes:
class Operation{
public:
virtual bool execute(const Solution& sol, Solution& newSol) = 0;
pair<int, int> pair_routes;
};
class OperationR : public Operation{
public:
OperationR(){};
bool execute(const Solution& sol, Solution& newSol);
pair<int, int> pair_routes;
};
class Oper... | Your derived classes are declaring their own pair_routes members that shadow (ie, hide) the pair_routes member of the base Operation class.
When you execute op->execute(), op is pointing at an OperationR object, so it is calling OperationR::execute(), which is then modifying the OperationR::pair_routes data member. Bu... |
72,207,562 | 72,207,761 | Where is the library for GUID in win32 | I was trying the example code on "How to Play Media Files with Media Foundation", and I tried to compile the code with the following makefile:
LDFLAGS = -LC:\\pathToWindowsSDK\\Lib\\10.0.22000.0\\um\\x64 -lMfplat -lMfuuid -lUser32 -lOle32 -lShlwapi -lMf
default: winmain.o player.o
g++ winmain.o player.o -o a.exe
w... | Try adding -luuid (Visual C++ projects created through Visual Studio link to uuid.lib by default).
|
72,207,645 | 72,355,575 | Is there a way to teach Android Studio how to display a C++ struct when hovering over the variable? | As a practical example, say I have a struct that looks like this:
struct MyFoo {
std::string mValue;
bool hasValue;
MyFoo() : hasValue(false) {}
MyFoo(std::string value) : mValue(value), hasValue(true) {}
};
If I hover over an instance of this struct, Android Studio displays + ☰ {MyFoo}. I can expand t... | As far as I know, Android Studio uses LLDB for debugging native code.
You can use LLDB commands to add custom formatting for showing these variables.
See: https://lldb.llvm.org/use/variable.html
The easiest way to do fancy pretty-printing is a Python script inside LLDB (see the LLDB docs link for more info, I based thi... |
72,207,931 | 72,215,406 | Why is my OpenGL texture black (in Dear ImGUI)? | In OpenGL 4.6, I (attempt to) create and initialize a solid color texture as follows:
glCreateTextures(GL_TEXTURE_2D, 1, &_textureHandle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FIL... | You created the texture by OpenGL 4.5 DSA, but didn't use DSA to set the texture parameters and image.
You have to use glTextureParameter, glTextureStorage2D and glTextureSubImage2D instead of glTexParameter and glTexImage2D.
glCreateTextures(GL_TEXTURE_2D, 1, &_textureHandle);
glTextureParameteri(_textureHandle, GL_TE... |
72,208,195 | 72,208,560 | Dump a binary exe to hexadecimal and embed it into c++ file leads to execution error | I am dumping a sample of relec malware to hexadecimal using xxd to embed it in a c++ file and execute it with createprocess. When I get the hexadecimal relec file I copy it to an array and write it to disk. I call createprocess to execute the relec executable but I get the following error message: "The program can´t be... | I changed the fopen writing mode. Instead I used the write binary mode as @TedLyngmo suggested. Thank u all for your answers.
|
72,208,471 | 72,219,101 | Set wallpaper from resource image file | I would like to set the background wallpaper from a resource image. I found and tried this code, but FindResource() can't find anything. Can anybody help me please?
HINSTANCE hInstance = GetModuleHandle(NULL);
std::cout << hInstance << std::endl;
HRSRC hResInfo = FindResource(hInstance, MAKEINTRESOURCE(IDB_PNG1), RT_... | There are two mistakes in your code:
You are creating the IDB_PNG1 resource as type PNG, but you are asking FindResource() to find a resource whose type is BITMAP instead. The types need to match, so replace RT_BITMAP with TEXT("PNG") in the call to FindResource(). Alternatively, use RCDATA instead of PNG in the .rc... |
72,208,512 | 72,255,890 | How to stop long operation on QThread? | I've made some research but I couldn't find the answer to why my solution is not working. But to the point.
I've got QWidget as a separate dialog in my app. I'm using this QWidget class to gather paths to files and zip them into one file with ZipLib. To give users some feedback about the progress of the zipping I've ad... | You cannot interrupt the execution of
ZipFile::AddFile(mZip, file);
itself. It is a single call to a function, and no one checks isInterruptionRequested() inside that function.
A simplified example
#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include <QTimer>
class MyThread : public QThread
{
pub... |
72,208,838 | 72,209,648 | Pass matrix of unknown dimensions to C++ function | The following code compiles with gcc but not g++. Is it possible to write a function with a matrix argument of arbitrary dimensions in C++?
void print_mat(const int nr, const int nc, const float x[nr][nc]);
#include <stdio.h>
void print_mat(const int nr, const int nc, const float x[nr][nc])
{
for (int ir=0; ir<nr;... | To build on Peter’s answer, you can use the single-dimension variant with proper indexing to do the work. But you can make invoking the function much nicer in C++:
void print_mat(const int nr, const int nc, const float *x)
{
...
}
template <std::size_t NumRows, std::size_t NumColumns>
void print_mat(const float (*x)... |
72,209,091 | 72,214,594 | How to, given UV on a triangle, find XYZ? | I have a triangle, each point of which is defined by a position (X,Y,Z) and a UV coordinate (U,V):
struct Vertex
{
Vector mPos;
Point mUV;
inline Vector& ToVector() {return mPos;}
inline Vector& ToUV() {return mUV;}
};
With this function, I am able to get the UV coordinate at a specific XYZ position:
P... | I haven't tested your implementation, but you only need to compute two parametric coordinates - the third being redundant since they should sum to 1.
Vector Math3D::TriangleUVToXYZ(Point theUV, Vertex* theTriangle)
{
// T2-T1, T3-T1, P-T1
Point aTr12 = theTriangle[1].ToUV() - theTriangle[0].ToUV();
Point aT... |
72,210,101 | 72,210,510 | Copy constructor is called although I have provided the move constructor | I have implemented both copy constructor and move constructor and what i learned was the program must use Move constructor instead of copy constructor .
class Move
{
private:
int *data; // raw pointer
public:
Move(int); // constructor
Move(const Move &source); // copy constructor
Move(... | Because std::vector moves while resizing only if you have a noexcept move constructor.
Or you can call vec.reserve(7) to avoid resizing.
|
72,210,210 | 72,261,716 | Microsoft Key Storage Provider get keys | I am trying to get the details of keys in Microsoft Key Storage Provider.
For this I open the storage provider using the below API call:
NCryptOpenStorageProvider(&prov, MS_KEY_STORAGE_PROVIDER, 0);
Then I call NCryptEnumKeys in a while loop to get the key details.
However I am only able to get one key from the KSP.
Du... | After days of analysis and discussions, finally I was able to identify the root cause. It is related to privileges. If I run with Admin privilege, I can extract keys for ECDSA certificate as well from the Local Machine certificate store.
If you do not intend to use Admin privilege, just take the certificate manager or ... |
72,210,455 | 72,212,742 | Why are the results of the optimization on aliasing different for char* and std::string&? | void f1(int* count, char* str) {
for (int i = 0; i < *count; ++i) str[i] = 0;
}
void f2(int* count, char8_t* str) {
for (int i = 0; i < *count; ++i) str[i] = 0;
}
void f3(int* count, char* str) {
int n = *count;
for (int i = 0; i < n; ++i) str[i] = 0;
}
void f4(int* __restrict__ count, char* str) { // GCC ex... | I created a simplified demo for the string case:
class String {
char* data_;
public:
char& operator[](size_t i) { return data_[i]; }
};
void f(int n, String& s) {
for (int i = 0; i < n; i++) s[i] = 0;
}
The problem here is that the compiler cannot know whether writing to data_[i] does not change the value... |
72,210,655 | 72,211,816 | visual C++ and u8 prefix | I was writting a HTTP server in visual studio preview, and I add <meta charset="utf-8"> to use UTF-8 as content encoding.
The problem is when I use u8 prefix on string literal, the browser looks like has encoding error.
when I remove u8 prefix, the browser show correctly.
Why?
and my document was save with utf-8 (code... | thanks to @AlanBirtles, use \u literal solve my problem.
u8 and no u8 both works in \U0001f4dd
update code
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment (lib, "ws2_32.lib")
#define U8
#ifdef U8
typedef const char8_t c;
c str[] = u8"HTTP... |
72,211,047 | 72,217,459 | How to include library from sibling directory in CMakeLists.txt for compilation | I am working on a C project as of recently and want to learn how to use CMake properly.
The project consists of the following directory structure (as of now):
.
└── system
├── collections
│ ├── bin
│ ├── build
│ ├── includes
│ └── src
└── private
└── corelib
├── bin
... | Binary directory has to be a subdirectory of current dir, it can't be above ../bin. Use:
add_subdirectory(../private/corelib some_unique_name)
Overall, let's fix some issues. A more advanced CMake might look like this:
# system/CmakeLists.txt
add_subdirectory(private EXCLUDE_FROM_ALL)
add_subdirectory(collections)
#... |
72,211,074 | 72,211,197 | Having trouble including header files | I can only use header files that I add to C:\SDL2-w64\include, but I Can't get it to link to the include folder inside my project folder.
for example: I have a folder called "MyProject" and its located at C:\Users\User\Desktop\MyProject, inside the project folder there is an "Include" folder located at \MyProject\Inclu... | Assuming the file doing the including is located at C:\Users\User\Desktop\MyProject, try using #include "Include/head.h". This is because there is a difference between using quotations ("") and angle brackets (<>) in your includes.
The reason is explained in this answer: https://stackoverflow.com/a/3162067/19099501
But... |
72,211,174 | 72,212,255 | declare a template vector member in a class without template the class? | I have some class that should be populated with values,
but I don't know the type of values.
To clarify, each vector in a class instance is populated with the same value types,
But one instance of SomeClass can have vector<int> and another vector<string> and so on.
How can I declare the vector as template, but not temp... | There are a few different ways to shear this beast. It mostly depends on how you want to access this vector and how you determine its exact type at runtime.
std::variant
A variant can store a set of predetermined types. It's effective but also cumbersome if you have many different types because you have to funnel every... |
72,211,630 | 72,405,147 | Forward Declaration of Constrained Template Specializations | I've been doing constrained partial class template specializations using C++20 concepts for a while now and they work great, but I and ran into a problem when attempting to forward declare them: godbolt example
#include <concepts>
template <class T>
concept Integer = std::is_same_v<T,int> || std::is_same_v<T,unsigned ... | Was a bug; is now fixed. No idea which version this fix will make it into.
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96363
|
72,212,385 | 72,212,633 | why is copy constructor called twice in this code? | When I execute the below code, a copy constructor of AAA is called twice between boo and foo.
I just wonder when each of them is called exactly.
Code:
#include <iostream>
#include <vector>
class AAA
{
public:
AAA(void)
{
std::cout<<"AAA ctor"<<std::endl;
}
AAA(const AAA... | The copy constructor is invoked twice here:
foo({a});
First to construct the elements of the initializer list, and second to copy the values from the initializer list to the std::vector.
|
72,212,408 | 72,212,479 | How to initialise and return an std::array within a template function? | I'd like a template function that returns some initialisation.
I did the following:
#include<iostream>
#include<array>
template <typename T>
inline static constexpr T SetValues()
{
if(std::is_integral<T>::value)
{
std::cout<<"int\n";
return T{1};
}
else
{
std::cout<<"array\n";
... | The problem is that, when T = int, you're trying to trying to initialize int arr with initializer list {1, 2, 3, 4} in the else branch. Even if you don't execute the else branch, the compiler still has to compile it and int arr = {1, 2, 3, 4} is invalid syntax.
On C++17 (and higher), you can get away with if constexpr:... |
72,212,409 | 72,227,863 | Neatly linking dependency tuple references specified by variadic class args | Given the following class structure in which we possess a number of different classes C#, each with unique data that is passed into a number of ledgers L<C#>, as well as possessing a number of classes S#, each depending on some subset of the classes under the C#, I have established a tuple containing all ledgers in the... | So focusing on the reference initialization, you might do something like:
template <typename T> struct Tag{};
template <typename... Ts, typename Tuple>
std::tuple<L<Ts>&...> make_ref_tuple(Tag<std::tuple<L<Ts>&...>>, Tuple& tuple)
{
return {std::get<L<Ts>>(tuple)...};
}
template <class... Cs, class... Ss>
class E... |
72,212,536 | 72,213,799 | how to iterate through several vectors with DIFFERENT types? | Here, I have a custom collection of entities (vectors of different types: Type1, Type2, Type3 , Type4, for simplicity I reduced to two types) with different sizes:
#include <stdio.h>
#include <vector>
template<typename DataType>
struct AbstractEntity
{
public:
virtual std::vector<DataType>& getParticlesCPU() = 0;
... | Make your run_function member function take a functor instead of a function pointer:
template<typename Entity, typename F, typename... Ts>
static void fun_per_entity(std::vector<Entity*>& entities, F&& f, Ts&&... args) {
for (auto& entity : entities) {
f(entity, args...);
}
}
pub... |
72,212,891 | 72,213,542 | What's the difference between using an mt19937_64 instance with or without the function call operator ()? | I created an mt19937_64 instance with a seed like so;
std::mt19937_64 mt_engine{9156}
What's the difference between using the instance like:
mt_engine()
or just
mt_engine
in code. And when should I use either?
I can't seem to find any material that explains this precisely. All I find on this stuff is either filled with... | mt_engine is an expression of type std::mt19937_64. You use it to refer to the generator.
mt_engine() is an expression of type std::uint_fast64_t. You use it when you want a random number from the generator.
What's the difference between the two use cases?
std::cout << mt_engine() generates a random number, and outpu... |
72,213,072 | 72,220,727 | Unable to refer to typedef struct definitions done in Win32 Header files (.h files in External dependencies) from WinRT C++ Library | Unable to refer to typedef struct definitions done in Win32 Header files (.h files in External dependencies) when consumed from WinRT C++ Library
#include <mfplay.h>
#pragma comment(lib,"Mfplay.lib")
class MediaPlayerCallback //: public IMFPMediaPlayerCallback
{
long m_cRef; // Reference count
MFP_EVENT_HEADER H;
};
... | As noted in the comments, the issue is that the MFP_EVENT_HEADER type is in the WINAPI_FAMILY_DESKTOP_APP API partition but is not in the WINAPI_FAMILY_APP API partition supported for UWP applications. Per Microsoft Docs this type is marked " [desktop apps only]".
IMFPMediaPlayerCallback is also "desktop apps only". Th... |
72,213,782 | 72,213,858 | Append to String a Signed Int (Converted to Bytes) in Big Endian | I have a 4 byte integer (signed), and (i) I want to reverse the byte order, (ii) I want to store the bytes (i.e. the 4 bytes) as bytes of the string. I am working in C++. In order to reverse the byte order in Big Endian, I was using the ntohl, but I cannot use that due the fact that my numbers can be also negative.
Exa... |
I was using the ntohl, but I cannot use that due the fact that my numbers can be also negative.
It's unclear why you think that negative number would be a problem. It's fine to convert negative numbers with ntohl.
s.append(reinterpret_cast<char*>(reinterpret_cast<void*>(&a)));
std::string::append(char*) requires t... |
72,213,987 | 72,214,145 | How to use C++ std::barrier arrival_token? | I keep getting a compiler error when using the std::barrier arrive and wait functions separately.
I've been trying to find examples of using these functions but I can't find them so I'm just shooting wild at this point.
It complaines that my arrival token is not an rvalue, so I changed the declaration to use &&, but I'... | A variable with an rvalue reference type is an lvalue (arrival is an lvalue).
std::barrier<>::wait takes an arrival_token&&, so you need to move from the lvalue:
sync_point.wait(std::move(arrival));
|
72,214,059 | 72,214,759 | Run time error assigning cv::Mat element value using cv::Mat::at | In the following code I would like to assign a values to elements of a Mat variable in a loop. I get the runtime error below.
pair<Mat, Mat> meshgrid(vector<int> x, vector<int> y) {
int sx = (int)x.size();
int sy = (int)y.size();
Mat xmat = Mat::ones(sy, sx, CV_16U);
Mat ymat = Mat::ones(sy, sy, C... | I assume you meant to generate output similar to numpy.meshgrid, and Matlab meshgrid.
There are several errors in your code:
The cv::Mat is initialized with type CV_16U (i.e. 16 bit unsigned value), but when you access the elements with at you use int (which is 32bit signed).
You should change it to at<unsigned short>... |
72,214,285 | 72,225,294 | QT Creator and OpenCV455: 'arm_neon.h' file not found | I'm building a project using qt6 and opencv455. I'm doing this on the new MacBook with a silicon chip (arm64). I can compile the whole project without errors, but I always get the 'arm_neon.h' file not found error message in the editor and therefore the syntax highlighting and warning display doesn't work correctly for... | Okay, I found a solution after three days of re-installing and re-compiling everything in every possible configuration (like opencv with unix makefiles, xcode, forced target architecture of arm64 etc). What finally worked was to disable the ClangCodeModel flag in the plugin section of QtCreator (Menu: About/Plugins/ ->... |
72,215,492 | 72,217,501 | How to link shared library on linux using cmake? | How to link shared library on linux platform? I downloaded sfml library using apt cmd and I tried to run simple example:
main.cpp
#include <SFML/Graphics.hpp>
int main()
{
// Make a window that is 800 by 200 pixels
// And has the title "Hello from SFML"
sf::RenderWindow window(sf::VideoMode(800, 200), "Hel... | here is an example of cmake file for sfml on linux
cmake_minimum_required(VERSION 3.22)
project(sfml-program LANGUAGES CXX)
add_executable(${PROJECT_NAME} main.cpp)
find_package (SFML 2.5 COMPONENTS graphics audio network REQUIRED)
target_link_libraries (${PROJECT_NAME} PUBLIC sfml-system sfml-graphics sfml-audio s... |
72,216,482 | 72,376,069 | Running into problem with benders decomposition from scip | I'm running into a strange error when solving a problem with SCIP. This does not happen for all instances, but for a few. I just wanted to ask if someone knows, what the error message means exactly and if I would need to turn off something specifically when solving the Problem with the Bender's Default from SCIP.
The e... | I was able to find the mistake myself. There were some problems with the parameters you can specify within SCIP. For Benders Decomposition you need to turn off the restarts in the solving process, but due to a mistake in the order of putting these parameters it was not turned off.
|
72,217,399 | 72,217,637 | How do I declare the root as global and set it to null to indicate an empty tree in a structure in c++? | As a beginner in c++, I have encountered a problem trying to implement a structure for binary search tree. Shown below is part of my code but c++ kept reminding me that the "data member initializer is not allowed".
#include<iostream>
using namespace std;
struct BstNode{int key; BstNode*Left; BstNode*Right; BstNode*roo... | You simply write
BstNode *root = nullptr;
outside of the struct.
|
72,218,366 | 72,220,447 | Stack Infix to Prefix not working correctly | I have an assignment to make a program that converts Infix to Prefix in C++. I have written a code to do so but the problem is I am only getting the operands and not the operators in the final result. I have checked my code many time, dry run it, but I cant find the problem. Here is the code:
#include <iostream>
#inclu... | You need to put the operator logic in the mainloop.
#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;
int Prec(char c)
{
if(c == '^')
{
return 3;
}
else if(c == '*' || c == '/')
{
return 2;
}
else if(c == '+' || c == '-')
{
return ... |
72,218,432 | 72,333,983 | How to read and write on serial ports on Unity Linux through C++ library? |
Introduction to the problem
I am developing a library in C++ that allows me to communicate with a device connected by USB reading and writing using serial ports, in Windows it works perfectly, but in Linux to be able to communicate with the devices I needed to read and write in the "/dev/tty*" files corresponding to ... | I'm not really sure where the problem lies, but I'll do my best to help.
The official Unity installation guide for Ubuntu that you have linked to does not install Unity as a flatpak.
That explains why flatpak tells you that it is not installed.
The issue you're linking to is describing how flatpak's sandboxing affects ... |
72,218,482 | 72,218,640 | Accessing element of array of pointers to member functions | I am having some troubles with member function pointers. How do I fix this, and why doesn't this work? The issue is inside main()... or so I am guessing!
#include <iostream>
#include <functional>
template<typename T>
using FnctPtr = void(T::*)(); // pointer to member function returning void
class Base {
public:
... | The type of vtable_ptr is void (Base::**)() while the type of base->vtable_ptr[0] is void (Base::*)(). The syntax that you're using for the call is incorrect.
How do I fix this
The correct syntax of using the pointer to member function void (Base::*)() in your example would be as shown below:
(base->*(base->vtable_pt... |
72,218,980 | 72,222,512 | GCC v12.1 warning about serial compilation | I have upgraded my whole arch linux system today (12th May, 2022). gcc was also upgraded from v11.2 to v12.1. I tried compiling some of my programs with g++ (part of gcc compiler collection) by the following command:
g++ -O3 -DNDEBUG -Os -Ofast -Og -s -march=native -flto -funroll-all-loops -std=c++20 main.cc -o ./main
... | Apparently that is a recent change in the -flto option. With a little bit of variation in the google search I was able to find this mail conversation:
Likewise if people just use -flto and auto-detection
finds nothing:
warning: using serial compilation of N LTRANS jobs
note: refer to http://.... for how to use paralle... |
72,220,097 | 72,220,162 | Optimisation and strict aliasing | My question is regarding a code fragment, such as below:
#include <iostream>
int main() {
double a = -50;
std::cout << a << "\n";
uint8_t* b = reinterpret_cast<uint8_t*>(&a);
b[7] &= 0x7F;
std::cout << a << "\n";
return 0;
}
As far as I can tell I am not breaking any rules and everything is we... |
More specifically, turning on optimisations can the compiler optimise away the middle b[7], either explicitly or implicitly, by simply keeping a in a register through the whole function.
The compiler can generate the double value 50 as a constant, and pass that directly to the output function. b can be optimised away... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.