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 |
|---|---|---|---|---|
71,342,226 | 71,342,385 | C++ not printing emojis as expected | I have the following extract of a program
int main(){
cout << "1) ✊\n";
cout << "2) ✋\n";
cout << "3) ✌️\n";
}
But at the time I run it I get strange texts like the following
====================
rock paper scissors!
====================
1) 
2) 
3) ԣÅ
This seems not to be related to my terminal but i... | If your terminal font supports emojis and you don't want to write much code (like switching from cout to wcout), you can use the windows api function below.
#include <windows.h>
#include <iostream>
int main(){
SetConsoleOutputCP(CP_UTF8);
std::cout << "1) ✊\n";
std::cout << "2) ✋\n";
std::cout << "3) ✌️\n";
... |
71,342,767 | 71,342,927 | vector<unique_ptr<T>> takes more than three times as much memory as vector<T> in ubuntu | As far as I understand unique_ptr<T> is not supposed to have such a huge overhead.
What do I wrong?
size_t t = sizeof(DataHelper::SEQ_DATA); // t = 12
std::vector<std::vector<std::unique_ptr<DataHelper::SEQ_DATA>>> d(SEQ_00_SIZE + 1); // SEQ_00_SIZE = 4540
for (unsigned int i = 0; i < d.size(); ++i) {
for (unsigne... | "std::unique_ptr doesn't have huge overhead" means that it doesn't have huge overhead compared to a bare pointer to dynamic allocation:
{
auto ptr = std::make_unique<T>();
}
// has comparable cost to, and has exception safety unlike:
{
T* ptr = new T();
delete ptr;
}
std::unique_ptr doesn't make the cost o... |
71,342,799 | 71,363,195 | How to access elements of symmetric Eigen matrix | My understanding of a symmetric matrix is that A(i,j) == A(j,i), but in Eigen only one of these is defined. What am I missing?
Here is an example below. I've also tried variations of that and don't seem to see an answer elsewhere. Am I supposed to manually ensure that the indices comply to some internal expectations?
M... | Accessing both halves by (i,j) is essentially not how .selfadjointView<>() is intended to work. Supporting that would require a min/max operation and for complex matrices even some kind of proxy-object, for each access which is quite expensive.
You should only access the upper half by the () operator and afterwards you... |
71,342,830 | 71,342,895 | Placement New U on existing T object and Manipulating it is UB? | In this link, Storage reuse section shows the following example.
void x()
{
long long n; // automatic, trivial
new (&n) double(3.14); // reuse with a different type okay
} // okay
and here, one of the answers contains this code.
void f(float* buffer, std::size_t buffer_size_in_bytes)
{
double* d = new (buf... | Both examples are legal.
"Transparent replaceability" only matters when you want to use a pointer to the old object to access the new object without std::launder.
But you're not doing that. You're manipulating the new object using the pointer returned by placement-new (not a pointer to the old object), which never need... |
71,342,973 | 71,343,034 | Understanding what FE_TONEAREST does | The gcc documentation here, explains what FE_TONEAREST does:
This is the default mode. It should be used unless there is a specific
need for one of the others. In this mode results are rounded to the
nearest representable value. If the result is midway between two
representable values, the even representable is chosen... | 1.235 and 1.225 are not numbers in your program.
Your C implementation almost certainly uses the IEEE-754 “double precision” format for double, which is also called binary64. If it performs correctly rounded conversions to the nearest representable values, then the source text 1.235 is converted to the double 1.2350000... |
71,344,218 | 71,344,269 | How to properly insert and display data in an dynamically allocated arrays in C++? | I've been having trouble trying to properly display the correct memory address so I don't know in which memory address I'm inputting data.
#include <iostream>
using namespace std;
int main() {
system("cls");
int *p = new int[2];
for(int i = 0; i < 2; i++) {
cout << "... | Your input loop is displaying the p pointer as-is (ie, the base address of the array) on every iteration. It is not adjusting the pointer on each iteration, unlike your output loop which does.
You are also leaking the array, as you are not delete[]'ing it when you are done using it.
Try this instead:
#include <iostrea... |
71,344,994 | 71,345,028 | fstream is writing on file against an if else statement | I have a file named "password.txt" which has 2 rows of usernames and passwords
2 string vectors named, user & password
This function uses a new username and password and checks if the username already exists in the user vector using a for loop
If it does exist, it breaks out of the loop
If it does not exist, it will ad... | WHILE you are looping through the user vector, any time you encounter an entry that does not match the newuser being searched for, you are writing the newuser/newpassword to the file and pushing them into the vectors 1 (which then affects subsequent iterations of your loop), and then you move on to the next entry.
So, ... |
71,345,823 | 71,348,979 | How do I use SetTimer() to create certain number of message boxes after another in c++? | I am trying to make it so when a messagebox opens another one opens a couple seconds later without any user input (pressing the OK button). I want the old one to stay open, but a new one to appear. I also want to be able to use SetWindowsHookEx and set a limit on how many message boxes are created. I know this uses the... | You are passing an uninitialized HWND to MessageBox().
Also, MessageBox() is a blocking function, it doesn't exit until the dialog is closed, so you need to create the timer before you call MessageBox(). Unless you use SetWindowsHookEx() or SetWinEventHook() to hook the creation of the dialog, then you can create the t... |
71,346,670 | 71,346,717 | '\r\n' deletes the whole buffer when the length is too long | I'm learning socket programming and there is a requirement in my project to put \r\n in every returned message. Something I notice that \r\n will delete the whole buffer when it exceeds some number of characters. For example, I have a code like this:
#include <iostream>
int main()
{
std::string message = "mkdir ho... | (message + "\r\n") creates a new std::string, and it is backed with a pointer.
This new std::string will get destroyed at the end of the full-expression.
So you should do this,
#include <iostream>
int main()
{
std::string message = "mkdir homework"; // Just one more 'k' at the end
std::string messageSuffixed =... |
71,346,817 | 71,347,756 | C++ 17 programming on visual studio 2017? | In title, I am specific about the task that I want to achieve. I want to utilize the c++17 features such as parallel STL etc. On visual studio 2017, I configure to c++17 under project properties for language. Even after doing this I get the error with #include that no execution file.
I am just starting with simple exa... | Please check if the header file is included in the header file directory. the C++ headers path are:
1.C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include
2.C:\Program Files (x86)\Windows Kits\10\Include\10.0.17134.0\ucrt
The first contains standard C++ headers such as iostrea... |
71,347,219 | 71,347,913 | How to find unique values in a vector c++ | I am trying to solve a coding problem where I am to check and see if a vector has unique values and if it does then return true else false.
So Far I thought of using a nested loops where you would compare the first to the last, but I am wanted to know if C++ has anything else then doing a o(n^2) type iteration. I saw ... | std::unique checks for consecutive duplicates and moves them to the end of the range. It does not remove them from the vector. Anyhow you can make a copy. It also returns an iterator to the end of the range of unique values (that are now in the front of the vector):
#include <iostream>
#include <vector>
#include <algor... |
71,347,375 | 71,347,466 | Iterating over a parameter pack | I have a parameter pack args... of vectors of arbitrary types, corresponding to which there is a vector of indices say v = {3,0,5...} having the same size, and order as the number of members of args.... I would like get_tuple to return a tuple of the elements of args... at the indices given by v.
Here's what I have so ... | In C++17, you need additional level of indirection to get a pack of indices to get a pack of elements at those indices:
template<typename... Args, std::size_t... Is>
auto get_tuple_impl(const std::vector<std::size_t>& indices,
std::index_sequence<Is...>,
const Args&... args) {
... |
71,347,415 | 71,348,050 | Finding if a path exists between two Nodes in a Graph using Depth First Search(DFS) C++ | I'm trying to implement the Depth First Search(DFS) suing recursion to return a boolean value if a path exists between two Nodes in a graph. Below is my implementation. The edges input is in the form of a Vector array.
I tried debugging the program to detect where exactly I am going wrong, but I don't know why it gives... | Seg faults usually occur due to access of un-allocated memory so that's what you should investigate first. You said that the validPath_helper is triggering the seg fault, so you should check that function.
In your case the culprit is this line :
if(adjList[source][destination]){
return true;
}
Here you wanted to c... |
71,347,589 | 71,347,625 | how do I allow free usage of enum and enum class member? | enum class A
{
ORANGE,
APPLE
};
...
{// workspace brackets
if(B == ORANGE){...} // use it like this
}// end of workspace
instead of keep using B==A::ORANGE, what can I do to make it like B==ORANGE within my workspace such as using namespace std?
| You can only do this in c++ 20 onwards with
using enum A
enum class foo {
a,
b,
c
};
int main() {
{
using enum foo;
foo f = b;
}
{
//foo f = b; // does not compile
}
}
|
71,347,981 | 71,348,048 | Is there a C++14 alternative to explicit(expr) introduced in C++20? | TL;DR: I am looking for a C++14 equivalent of the following C++20 MWE:
template<int sz>
struct bits {
int v; // note explicit(expr) below
explicit(sz > 1) operator bool() const { return bool(v); }
};
int main() {
bool c = bits<1>{1}; // Should work
bool d = bits<3>{1}; // Should fail
}
Context:
We have a C++ ... | Yes. You can SFINAE the conversion operator:
#include <type_traits>
template<int sz>
struct bits {
int v;
explicit operator bool() const { return bool(v); }
template <int S = sz>
operator std::enable_if_t<S == 1, bool> () const { return bool(v);}
};
Check it on godbolt
int main()
{
bool c1 = bits<1>{1}; ... |
71,348,386 | 71,357,534 | Emscripten C++ to WASM with Classes - "error: undefined symbol" | I have a really simple C++ project (removed as much code til the problem is still there.) Running em++ is always leading to an error, error: undefined symbol
main.cpp
#include "edgeguard.hpp"
int main()
{
EdgeGuardConfig core = EdgeGuardConfig::BuildEdgeGuard();
}
edgeguard.cpp
#include "edge-guard.hpp"
EdgeGuar... | Thanks to Marc Glisse's comment, I realize now that I needed to not just pass main.cpp but also all related .cpp files (I thought it would pick up that information from the includes ♂️)
It is now compiling
|
71,348,675 | 71,349,187 | How to sort a vector using std::views C++20 feature? | I want to loop through a vector in a sorted way without modifying the underlying vector.
Can std::views and/or std::range be used for this purpose?
I've successfully implemented filtering using views, but I don't know if it is possible to sort using a predicate.
You can find an example to complete here : https://godbol... | You have to modify something to use std::ranges::sort (or std::sort), but it doesn't have to be your actual data.
#include <iostream>
#include <ranges>
#include <numeric>
#include <algorithm>
#include <vector>
#include <chrono>
struct Data{
int a;
friend auto operator<=> (const Data &, const Data &) = default;... |
71,349,240 | 71,381,959 | C++ OpenSSL: libssl fails to verify certificates on Windows | I've done a lot of looking around but I can't seem to find a decent solution to this problem. Many of the StackOverflow posts are regarding Ruby, but I'm using OpenSSL more or less directly (via the https://gitlab.com/eidheim/Simple-Web-Server library) for a C++ application/set of libraries, and need to work out how to... | OK, to anyone who this might help in future, this is how I solved this issue. This answer to a related question helped.
It turns out that the issue was indeed that the SSL context was not making use of the certificate store that I'd set up. Everything else was OK, bu the missing piece of the puzzle was a call to SSL_CT... |
71,349,401 | 71,349,627 | error: expected ',' or '...' before 'nullptr' | The below code snippet is generating the error: expected identifier before 'nullptr' as well as error: expected ',' or '...' before 'nullptr' in line edge minIncoming(nullptr, NOPATH);
Any idea what is wrong? All I want to do is use the constructor to initialize minIncoming. I tried searching but couldn't find a answer... | Due to C++'s most vexing parse, the statement:
edge minIncoming(nullptr, NOPATH);
is treated as if you're declaring a function named minIncoming with return type of edge and taking two parameters. But since during declaration of a function, we specify the types of the parameters instead of specifying the arguments(as... |
71,349,651 | 71,352,156 | Longest palindrome in a string? | I want to print the longest palindrome in a string , I have written the code but this is giving wrong answer for some test cases . I am not able to find the error in my code .
Anyone help me with this , Anyhelp would be appreciated.
Input
vnrtysfrzrmzlygfv
Output
v
Expected output
rzr
Code:
class Solution {
public:
... | You are using substr(.) incorrectly. The second argument is the size of the substring.
string s2 = S.substr(i, j); should be replaced by string s2 = S.substr(i, j-i+1);
Moreover, this code will not be very efficient. To speed it up, I modified your code in the following way:
I pass the string by reference to the ispal... |
71,349,888 | 71,350,225 | Do while loop c++ assistance | I'm trying to make a cpp program that asks the user for two number inputs. Then print from 1 to the first number the user entered or until the first multiple of the second number. Print "Multiple of X(second number)" if the number is a multiple of the second input. using Do while loop.
This is what I managed to do so f... | You should use break when you get to the target number.
#include <iostream>
int main() {
std::cout << "enter two numbers: ";
int first = 0;
int second = 0;
std::cin >> first >> second;
if (second != 0 && first % second == 0)
std::cout << first << " is a multiple of " << second << '\n';
... |
71,349,963 | 71,350,560 | Which C++ random number distribution to use for the Java skip list generator? | The Java ConcurrentSkipListMap class contains a method randomLevel that outputs the following, according to The Art of Multiprocessor Programming:
The randomLevel() method is designed based on empirical measurements to maintain the skiplist property.
For example, in the java.util.concurrent package, for a maximal Skip... |
This looks like a geometric distribution, but not quite.
You are right, but problem is only probability of 0. Note that you can use std::geometric_distribution, by merging first two values into one.
class RandomLevel
{
std::geometric_distribution<unsigned> distribution;
std::mt19937 gen{std::random_device{}()... |
71,350,000 | 71,351,370 | C++ template lambda wrapper | Can anyone figure out how to make this compile ?
I'm trying to wrap a lambda in another function that does something (here printing "you know what") + calling the lambda.
Best would be to have automatic template parameters deduction.
#include <iostream>
#include <functional>
#include <utility>
void youKnowWhat(const s... | How about
#include <iostream>
#include <functional>
#include <utility>
template <typename F>
void youKnowWhat(F&& fun)
{
std::cout << "You know what ?" << std::endl;
fun();
}
template <typename F>
auto youKnowWhatSomething(F&& fun)
{
return [fun{std::move(fun)}](auto&&... args) -> decltype(fun(std::forwar... |
71,350,907 | 71,599,446 | SNMP++ library ignore USM model and accept every input even without auth | I am building a C++ application which purpose is, among other thing, to receive SNMP traps. For this I am using SNMP ++ library version V3.3 (https://agentpp.com/download.html C++ APIs SNMP++ 3.4.9).
I was expecting for traps using no authentication to be discarded/dropped if configuration was requesting some form of a... | Disclaimer I am not expert so take the following with a pinch of salt.
I cannot say for the library you are using but regarding the SNMP v3 flow:
In SNMPv3 exchanges, the USM is responsible for validation only on the SNMP authoritative engine side, the authoritative role depending of the kind of message.
Agent authori... |
71,350,929 | 71,351,311 | Casting from long double to unsigned long long appears broken in the MSVC C++ compiler | Consider the following code:
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
long double test = 0xFFFFFFFFFFFFFFFF;
cout << "1: " << test << endl;
unsigned long long test2 = test;
cout << "2: " << test2 << endl;
cout << "3: " << (unsigned long long)test << endl;
ret... | You are seeing undefined behaviour because, as pointed out in the comments, a long double is the same as a double in MSVC and the 'converted' value of your 0xFFFFFFFFFFFFFFFF (or ULLONG_MAX) actually gets 'rounded' to a slightly (but significantly) larger value, as can be seen in the following code:
int main(int argc, ... |
71,351,077 | 71,351,131 | How to handle classes that are not copyable? | An example:
class File {
public:
File(const char* path);
File(File& other) = delete;
File& operator=(File& rhs) = delete;
~File();
private:
char* path;
FILE* cfile;
};
class Filesystem {
public:
Filesystem();
Filesystem(Filesystem& other);
~Filesystem();
File Search(const cha... | Moveable types
You can make the class moveable by adding the move constructor and move assignment operator. (Some possibly useful overview of that.)
...
// rough sketch
// Having the path as `char*` seems
// bad (use std::string instead),
// but let's stick with the example as posted)
File(File&& other)
: path(null... |
71,351,243 | 71,351,443 | C++ vector insert with Iterator is not working as I expected | C++11, Input is nums = [1,2,3,4,5]
void rotate(vector<int>& nums, int k) {
nums.insert(nums.begin(), nums.end() - k, nums.end());
}
When k = 2, I expect this function should make nums to [4,5,1,2,3,4,5]
but it becomes [2,3,1,2,3,4,5]
When k = 1, nums is [4,1,2,3,4,5]
but when k = 4, nums is [2,3,4,5,1,2,3,4,5], wh... | The std::vector::insert overload that you are using has a precondition that neither the second nor the third argument are iterators into the vector itself.
You are violating that precondition and therefore your program has undefined behavior.
|
71,351,373 | 71,417,216 | How to force exe file to run on Nvidia GPU on windows | I have a program written in C++ language. My whole code contains only 3 files: a header file for my own class, a cpp file with code implementation for the class and a 3rd cpp file where I have the main() method.
I need to make very complicated calculations, and on a normal CPU my code takes about 3 months to complete t... | As far as I know, there is no easy and/or automatic way to compile general C++ code to be executed in a GPU. You have to use some specific API for GPU computing or implement the code in a way that some tool is able to automatically generate the code for a GPU.
The C++ APIs that I know for GPU programming are:
CUDA: in... |
71,351,702 | 71,351,814 | /usr/bin/ld: cannot find during linking g++ | This question has already been here so many times. But I didn't find the answer.
I have this .cpp file
#include <clickhouse/client.h>
#include <iostream>
using namespace clickhouse;
int main(){
/// Initialize client connection.
Client client(ClientOptions().SetHost("localhost"));
client.Select("SELECT l.... | ld's manual page describes the -l option as follows (irrelevant details omitted):
-l namespec
--library=namespec
Add the archive or object file specified by namespec to the list of
files to link. [...] ld will search a directory for a library called
libnamespec.so
If you read this very carefully, you will reach the c... |
71,352,014 | 71,357,710 | How to safely terminate a multithreaded process | I am working on a project where we have used pthread_create to create several child threads.
The thread creation logic is not in my control as its implemented by some other part of project.
Each thread perform some operation which takes more than 30 seconds to complete.
Under normal condition the program works perfectl... | What is it that you need to do before the program quits? If the answer is 'deallocate resources', then you don't need to worry. If you call _exit then the program will exit immediately and the OS will clean up everything for you.
Be aware also that what you can safely do in a signal hander is extremely limited, so at... |
71,352,306 | 71,352,970 | How to make a timeout at receiving in boost::asio udp::socket? | I create an one-thread application which exchanges with another one via UDP. When the second is disconnecting, my socket::receive_from blocks and I don't know how to solve this problem not changing the entire program into multi-threads or async interactions.
I thought that next may be a solution:
std::chrono::milliseco... |
PS. As for "it doesn't work when debugging", debugging (specifically breakpoints) obviously changes timing. Also, keep in mind network operations have varying latency and UDP isn't a guaranteed protocol: messages may not be delivered.
Asio stands for "Asynchronous IO". As you might suspect, this means that asynchron... |
71,352,429 | 71,353,008 | SDL2.dll was not found | I'm trying to set up SDL2 in C++ Visual Studio but when I run the code(just some starter code I copied) it pops up with an error box box that talks about "SDL2.dll cannot be found" I tried switching to x64 but that was no help. I can see that the dll is right next to the lib files but it just won't work.
| Your problem is the lib folder is not a place that your OS will search for dependent dlls by default. To fix this you would have to help your OS find the dll. There are several methods you can use to tell your OS where to look. One is adding an entry to your PATH environment variable that contains the full path to the ... |
71,352,799 | 71,352,953 | Evaluating if ( std::function<void()> == function )? | How can I evaluate given expression (function<void()> == functor).
Code example:
#include <functional>
using namespace std;
void Foo() { }
int main() {
function<void()> a;
// if (a == Foo) -> error
}
Edit: debugging details, and remove picture.
| std::function::target() will retrieve a pointer to the stored callable object. And that's what you're trying to compare.
You must specify the expected stored type, and target() will return nullptr if the type does not match.
(This means that if std::function holds a function pointer, target() will return a pointer-to-... |
71,352,971 | 71,354,055 | Post a multipart/form-data HTTP request with WinHTTP | I have been trying for the past few days to send an HTTP POST request to my SpringBoot application with the Win32 API, but I'm always receiving the same error. The request is a multipart consisting of a binary file and a JSON. Sending the request via Postman works with no problems, and I'm able to receive the file and ... | The MIME boundaries in your postdata1 and postdata2 strings are incomplete, which is why WireShark and the SpringBoot app are not parsing your data correctly.
Every MIME boundary in the body data must start with a leading --, followed by the value you specified in the Content-Type's boundary attribute, followed by a tr... |
71,354,023 | 71,355,052 | Is there a standard binary representation of integer data types in c++20? | I understand that with c++20 sign magnitude and one's comp are finally being phased out in favor of standardizing two's comp. (see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0907r3.html, and http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1236r1.html) I was wondering what this meant for the impl... | The sign bit is required to be the most significant bit (§[basic.fundamental]/3):
For each value x of a signed integer type, the value of the corresponding unsigned integer type congruent to x modulo 2N has the same value of corresponding bits in its value representation.
Things only work this way if the sign bit is ... |
71,354,571 | 71,354,847 | Replacing specific chars with different and more chars | I'm trying to do an interesting exercise from a book with the following question:
For our dynamically allocated strings, create a function replaceString that takes
three parameters, each of type arrayString: source, target, and replaceText.
The function replaces every occurrence of target in source with replaceText.
F... | For starters using this typedef
typedef char *arrayString;
is a bad idea. For example if you need to declare a pointer to a constant string then this declaration
const arrayString p;
will not denote
const char *p;
It means
char * const p;
that is not the same as the above declaration..
And the second and the third ... |
71,354,703 | 71,354,749 | How to perfectly forward `*this` object inside member function | Is it possible to perfectly forward *this object inside member functions? If yes, then how can we do it? If no, then why not, and what alternatives do we have to achieve the same effect.
Please see the code snippet below to understand the question better.
class Experiment {
public:
double i, j;
Experiment(double p_... | This is not possible in C++11 without overloading sum for & and && qualifiers. (In which case you can determine the value category from the qualifier of the particular overload.)
*this is, just like the result of any indirection, a lvalue, and is also what an implicit member function call is called on.
This will be fix... |
71,354,825 | 71,355,567 | C++ my own class predicate is not working | I'm a complete newbie at C++. I want to create my own predicate. But the part with bool operator seems to be wrong (at least in my humble opinion). Could someone give me a hint? I don't want to change the overall structure of this idea, I'm just sure I don't understand some details about operator () implementation or s... | What you need is:
define Predicate as an abstract type,
implements different versions of it.
Predicate as an abstract type:
class Predicate {
public:
virtual bool operator(int v) const = 0;
};
Implementing (realising) a given Predicate:
class IsNegative : public Predicate { // means IsNegatives are Predicates
... |
71,354,935 | 71,356,028 | Pass method as other method callback parameter | I'm trying to give a method as a callback of another method just like that:
Actions actions;
Button button;
int main()
{
actions = Actions();
button = Button();
button.onClick(actions.doSmthg);
return 0;
}
Here is my Actions:
class Actions {
public:
Actions();
void doSmthg();
};
and h... | Method 1
You can make use of std::bind and std::function as shown below:
#include <iostream>
#include <functional>
class Actions {
public:
Actions(){}
void doSmthg(){
std::cout<<"do something called"<<std::endl;
}
};
class Button {
public:
Button() {};
void setFunc(std::function<void ()>... |
71,355,654 | 71,355,778 | Same code, one works one doesn't. What's different? | i'm an beginner programmer, this is my first time posting. I'm currently writing a snake game in c++. Most of the game wasn't so hard to implement but when it came to the tail of the snake the entire program broke. I spent like 2 hours trying to figure out what was wrong and then i decided to try to rewrite the problem... | k==tail[s].width==k is not the same as tail[s].width == k. You may think you've written something like (k == tail[s].width) && (tails[s].width == k. But C++ doesn't automatically put in && operators like that. What actually happens is that the associativity of the == operator is left to right. So what that actually mea... |
71,355,745 | 71,356,070 | Overwriting object with new object of same type and using closure using this | In the following code an object is overwritten with a new object of same type, where a lambda-expression creates a closure that uses this of the old object. The old address (this) remains the same, the new object has the same layout, so this should be ok and not UB. But what about non trivial objects or other cases?
st... | You are not actually replacing any object. You are just assigning from another object to the current one. o = simply calls the implicit copy assignment operator which will copy-assign the individual members from the temporary A constructed in the assignment expression with A{...}.
The lambda is going to capture this f... |
71,356,155 | 71,356,382 | constructor initialisation order when Base constructor depends on reference from Derived | I have a base class which writes objects to a std::ostream with buffering. I want to call this with
Obj obj;
flat_file_stream_writer<Obj> writer(std::cout);
writer.write(obj);
writer.flush();
but also with
Obj obj;
flat_file_writer<Obj> writer("filename.bin");
writer.write(obj);
writer.flush();
The ... | You can put std::ofstream ofstream_; in a separate struct, then have flat_file_writer inherit from that struct using private. Base classes are initialized in the order they are declared, so make sure to inherit from that struct before flat_file_stream_writer. You can now initialize that ofstream_ before the base class ... |
71,356,243 | 71,356,294 | Dynamic memory allocation confusion | I saw a tutorial where the instructor dynamically allocates memory for n*int size (n is not known in advance, user would give it as an input). Just out of curiosity, I have changed the code from calloc(n,sizeof(int)) to calloc(1,sizeof(int)) and I was expecting to see an error, but I did not face an error, and the code... |
I was expecting to see an error
Your expectation was misguided. If you access outside the region of allocated storage, then the behaviour of the program is undefined. You aren't guaranteed to get an error.
Don't access memory outside of bounds. Avoid undefined behaviour. It's very bad. The program is broken.
Other a... |
71,356,247 | 71,358,681 | RAII: do mutexes in a vector declared in a loop all unlock in the next iteration? | Suppose I have the following:
// ... necessary includes
class X {
struct wrapper{ std::mutex mut{}; }
std::array<wrapper, 20> wrappers{};
void Y()
{
for (auto i{0u}; i < 10; ++i)
{
std::vector<std::unique_lock<std::mutex>> locks_arr{};
for (auto& wrapp : wrappe... | To answer my own question—yes, this is how RAII works. The vector is declared inside the body of the for loop; it is destroyed and recreated every iteration. continue also causes the execution of the rest of the loop to be short-circuited.
When the vector is destructed, every object it contains is also destroyed. As su... |
71,358,353 | 71,358,616 | C++03 equivalent for auto in the context of obtaining an allocator | auto source_allocator = source.get_allocator();
Is there a way of replacing auto in the above with something C++03/98-friendly, in the event where the type of allocator is not known in advance?
| Based on what you posted in the comments, it sounds like you're trying to do this inside a template.
Assuming you are expecting your templated type to be a std::container, or something compatible, you can do this:
typename T::allocator_type in place of auto.
https://godbolt.org/z/Pda77vjox
|
71,358,578 | 71,359,064 | std::disjuction not finding type in parameter pack passed to template function | I'm trying to use std::disjuction to test whether a parameter pack contains std::wstring, and nothing I've tried seems to want to make it return the value I'm expecting.
Here's the code as it is currently (https://godbolt.org/z/x99M8avYE):
#include <string>
#include <iostream>
#include <type_traits>
template <typename... | Note that the parameter type received by f is forwarding reference Args&&, so when you pass in an lvalue wstr, Args will be instantiated as std::wstring& instead of std::wstring, you should remove the reference, e.g.
template<typename... Args>
void f(Args&&... args) {
std::cout << HasWS<std::remove_reference_t<Args... |
71,358,665 | 71,390,333 | How to access Qlist of structure elements in QML | How can I access Qlist of struct elements in QML.
I have implemented as follows, but the output is not working as expected.
Can some one please help me how to get the values of qlist struct elements in qml
sample.cpp
#include "sample.h"
int xVal[5] = {1,2,3,4,5};
int yVal[5] = {6,7,8,9,10};
Sample::Sample(QObject *pa... | use QVariantList instead of QVariant for the return type
code like below
.pro file
QT += quick qml
SOURCES += \
ctestforqml.cpp \
main.cpp
resources.files = main.qml
resources.prefix = /$${TARGET}
RESOURCES += resources \
Resources.qrc
CONFIG += qmltypes
QML_IMPORT_NAME = com.demo.cppobject
QM... |
71,358,875 | 71,359,381 | abi::__cxa_demangle cannot demangle symbols? | I am unsure why this fails to demangle symbols:
#include <cxxabi.h>
void _debugBacktrace(code_part part)
{
#if defined(WZ_OS_LINUX) && defined(__GLIBC__)
void *btv[20];
unsigned num = backtrace(btv, sizeof(btv) / sizeof(*btv));
char **btc = backtrace_symbols(btv, num);
unsigned i;
char buffer[255];
... | For one thing, you are not calling __cxa_demangle correctly. Documentation says:
output_buffer
A region of memory, allocated with malloc, of *length bytes, into which the demangled name is stored. If output_buffer is not long enough, it is expanded using realloc. output_buffer may instead be NULL; in that case, the de... |
71,358,961 | 71,359,024 | C++ read only integers in an fstream | How do I read in a file and ignore nonintegers?
I have the part down where I remove the ',' from the file, but also need to remove the first word as well.
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
above is all the STL I am using.
string line, data;
int num;
bool IN = false;
ifst... | You already know how to read line-by-line, and break up a line into words based on commas. The only problem I see with your code is you are misusing stoi(). It throws an exception on failure, which you are not catching, eg:
while (getline(ss, data, ','))
{
try {
num = stoi(data);
}
catch (const exc... |
71,359,065 | 71,363,890 | Group pairs of elements based on connecting element in C++ | Assume I have pair of integers like: [(1,2), (3,4), (2,3), (3,5), (7, 8), (7,9)] and I would like to sort the pairs into unique groups based on connected elements amongst them i.e. if elements share a common element with one other pair in the same group, then they should be put into the same group. So in the example ab... | Assumptions: Pairs are ordered. (a,a),(a,b),(b,a) is a valid input.
Yes this problem can be solved using an undirected graph.
For each given pair (a, b), create an undirected edge between a and b. Now traverse this graph to find its connected components. Remember the component of each node, eg. by coloring them. Finall... |
71,359,084 | 71,359,181 | String subscript out of range error for code that traverses string c++ | I am trying to count the count the number of positive numbers, negative numbers and zeros in a string of space separated integers. The number of integers in the input string is specified by the user.
The code compiles fine, however every time I try to run it, it crashes with the error "Debug Assertion Failed. ... Expre... | For a start std::cin >> some_string_var is going to stop at the first white space character it finds, so there's little point in using that to search for spaces separating words.
You would be better off just reading in integers and just comparing them directly with zero. Here's how you could do with with the MNC (minim... |
71,359,227 | 71,359,267 | Is it safe to use a reinterpret_cast if I can guarantee the correct type was used to allocate the memory? | I am trying to make my C++ code cross platform. On Windows I am using the Windows.h header file and on macOS and Linux I use the unistd.h header file.
I am calling a function if the OS is windows which takes a char* type. The equivalent call for mac and linux takes char**. I currently have a function that takes a void*... | It sounds like what you're asking about would be safe. However, your code looks a bit off:
void DoSomething(void* thing) {
thing = new char*[...];
That will leave the caller with no access to the allocated memory, because thing is an addressed the caller passed in but then you immediately overwrote the address, s... |
71,359,388 | 71,359,448 | How to construct a class with user inputs and no variables? | One of my assignments involve creating a class using a constructor with parameters, where the arguments sent to create the object are based on user input.
#include <iostream>
#include "HRCalc_lib.h"
HeartRates::HeartRates(const std::string &first, const std::string &last,
int day, int month, int year){
fi... |
Is there a more direct way of creating the same object without the need for variables to store user inputs in main?
Yes, there is. You can use operator overloading. In particular, you can overload operator>> as shown below:
#include <iostream>
#include<string>
class HeartRates
{
private:
std::string first, ... |
71,359,572 | 71,372,935 | How do I use Serial Monitor in Arduino to give word like my name, "DASH" and only that to blink an LED? | So,I have a task at hand and that is to use a word, like my name "DASH" as input to Serial Monitor in Arduino so that the LED in the ESP32-WROOM-32 blinks and otherwise, it won't. I am fairly new to the Arduino side and would really appreciate any guidance at all, even though it may be very little info so feel free ple... | So, upon carefully reading and understanding more about Arduino and serial monitor, I feel ready to say that the problem wasn't the code, in fact it was fine.
The problem was me and the serial monitor showing the output options. It should have been "No new line" and in my case it had always been "Newline" which is what... |
71,359,610 | 71,359,664 | Templating a Derived class of a Base class that is already templated | I get the compiler error "Use of undeclared identifier '_storage'"
#include <iostream>
struct Storage{
int t;
};
struct DerivedStorage : Storage{
int s;
};
struct DerivedStorage2 : DerivedStorage{
int r;
};
template<typename DS = Storage>
class Base{
public:
DS* _storage = nullptr;
Base(){
... | Because Derived itself does not have a member variable named _storage, use this->_storage to access Base's _storage instead.
void m2(){
this->_storage->s++;
}
Demo
|
71,359,638 | 71,359,749 | Thread 1: EXC_BAD_ACCESS (code=257, address=0x100000001) in C++ | I've written a program that will check if a given string has all characters unique or not. I usually write in Python, but I'm learning C++ and I wanted to write the program using it. I get an error when I translate Python into C++: Thread 1: EXC_BAD_ACCESS (code=257, address=0x100000001)
I am using Xcode. When I run th... | The problem is here:
int arr[] = {};
The array you're creating has length 0 which you can verify using
cout << "sizeof(arr): " << sizeof(arr) << endl;
The error occurs when you try to access values beyond the size of the array here:
arr[i] = 0;
What you need to do is specify a size of the array, for example... |
71,359,686 | 71,360,087 | Is there a scenario where adding a const qualifier to a local variable could introduce a runtime error? | Here's an (admittedly brain-dead) refactoring algorithm I've performed on several occasions:
Start with a .cpp file that compiles cleanly and (AFAICT) works correctly.
Read through the file, and wherever there is a local/stack-variable declared without the const keyword, prepend the const keyword to its declaration.
C... | If you're willing to accept a contrived example, you could enter the world of undefined behavior.
void increment(int & num)
{
++num;
}
int main()
{
int n = 99;
increment(const_cast<int&>(n));
cout << n;
}
The above compiles and outputs 100. The below compiles and is allowed to do whatever it wants (bu... |
71,359,711 | 71,359,836 | Efficient way to perform summation to infinite in c++ | I am new to c++ and I am trying to implement a function that has a summation between k=1 and infinite:
Do you know how summation to infinite can be implemented efficiently in c++?
|
Do you know how summation to infinite can be implemented efficiently in c++?
Nothing of this sort, doing X untill infinity to arrive at any finite result can be done in any language. This is impossible, there is not sugar coated way to say this, but it is how it is for digital computers.
You can likely however make a... |
71,359,894 | 71,359,941 | Why is my bool return statement returning something other than 0 or 1? | I have a bool function that performs some calculations and checks to see if certain conditions are true. If so, it returns true or false, as a bool function should.
However, when it is true, instead of returning 1, it returns random numbers, such as 48, 240, 112, 224, etc.
I'm sure you want the code ... here it is:
boo... | Looks like your attempt to implement recursive function is not correct.
isHappy(sumSquares);
should probably be
return isHappy(sumSquares);
|
71,359,982 | 71,359,992 | Is there a way to limit the number of times we type template <typename T> in the cpp file? | In my cpp file, before every function I need to include the line:
template <typename T>
Is there some short hand notation so that, instead of typing this before every function, I can type the statement just once for a group of functions ?
Also, I need to include <T> after the class name, for example:
void MyClassName<... | Nope. If you need it for each function, then the compiler needs to be told this directly before each function.
A slightly shorter way is of course template <class T>
And we could get even shorter if we resort to macros.
|
71,360,562 | 71,360,728 | do-while in fibonacci sequence repeating answer | I made a program about Fibonacci program. I would like to repeat the program so I used do-while loop. However, it seems like the last two numbers from the previous result keep coming. It is supposed to reset back to the first term. Please help me how to get there.
#include<iostream>
using namespace std;
void ... | When you are running the code for first time, the values of variables t1,t2 and nextTerm are changing. So before repeating the same code again you need to set the default values of those variables again.
Simply try this:
#include <iostream>
using namespace std;
int main (){
int i, n, t1=1, t2=1, nextTerm=0;
cou... |
71,360,576 | 71,360,661 | The meaning of __ and __ in clang variables and functions | In clang's standard library, what do the _ and __ on variables mean?
Here is a part of string_view.
inline
void __throw_out_of_range(const char*__msg)
{
throw out_of_range(__msg);
}
// __str_find_first_not_of
template<class _CharT, class _SizeT, class _Traits, _SizeT __npos>
inline ... | _ and __ are just part of the identifier. They don't have any other special meaning.
However, identifiers containing a double underscore or starting with an underscore followed by an upper-case letter are reserved for the standard library. The user code is not allowed to declare them or define them as macro.
The standa... |
71,360,650 | 71,360,722 | How to pass a set of different kinds of templated components to a function? | I have components:
struct ComponentStorage : Storage{
...
};
template<typename T = ComponentStorage>
class Component{
public:
T* storage;
...
}
There are derived classes of the form:
struct Component2Storage : Storage{
...
};
template<typename T = Component2Storage>
class Component2 : public Component<T>{...... | If you need to store different components in the same container, you need polymorphism.
So you need your Components to have a common base class, to be able to treat them as such.
struct ComponentStorage : Storage{
...
};
class ComponentBase {
// ... define your common interface
}
template<typename T = Compone... |
71,360,896 | 71,360,934 | Is this gcc and clang optimizer bug with minmax and structured binding? | This program, built with -std=c++20 flag:
#include <iostream>
using namespace std;
int main() {
auto [n, m] = minmax(3, 4);
cout << n << " " << m << endl;
}
produces expected result 3 4 when no optimization flags -Ox are used. With optimization flags it outputs 0 0. I tried it with multiple gcc versions with -O1... | The overload of std::minmax taking two arguments returns a pair of references to the arguments. The lifetime of the arguments however end at the end of the full expression since they are temporaries.
Therefore the output line is reading dangling references, causing your program to have undefined behavior.
Instead you c... |
71,361,112 | 71,361,186 | Structured bindings in foreach loop | Consider fallowing peace of code:
using trading_day = std::pair<int, bool>;
using fun_intersection = vector<pair<int, bool>>;
double stock_trading_simulation(const fun_vals& day_value, fun_intersection& trade_days, int base_stock_amount = 1000)
{
int act_stock_amount = base_stock_amount;
for(auto trade : trade... | As said by user17732522, you can use range-based for loops for this purpose as such:
#include <iostream>
#include <vector>
using trading_day = std::pair<int, bool>;
using fun_intersection = std::vector<std::pair<int, bool>>;
int main()
{
fun_intersection fi({ {1, true}, {0, true}, {1, false}, {0, false} });
f... |
71,361,149 | 71,361,212 | C++ concept: check if a method/operator exists no matter what return type is | Suppose I am writing a template function that wants to call operator+= on its template parameter and does not care whether it returns the new value (of type T), a void, or whatever else. For example:
template<class T>
void incrementAll(T *array, int size, T value) {
for (int i = 0; i < size; ++i) {
array[i]... | If you don't care what its return type is, then you can simply use the requires-clause to require the expression a += b to be well-formed:
template<class T>
concept Incrementable = requires(T a, T b) {
a += b;
};
However, such a concept seems too loose for the incrementable type, and it seems more appropriate to req... |
71,361,574 | 71,361,617 | Creating a suitable begin() and end() function for a class | I have the following class:
template<typename DataType>
class Bag
{
DataType* arr;
int len, real_size;
public:
// Class methods
};
I have implemented different methods such as add, remove, etc. for Bag. I have also overloaded the operator[].
While testing this out, I wanted to print all the elements of an ... | begin and end need to return iterators/pointers to the first and the last+1 element, whereas you return the first and last element.
DataType *begin() const { return arr; }
DataType *end() const { return arr+len; }
should work, assuming that len is the number of elements in your array.
Note: end needs to point beyond ... |
71,361,839 | 71,362,109 | Constness and comparison concepts in generic code | Taking a look at cppreference
template<class T, class U, class Cat = std::partial_ordering>
concept three_way_comparable_with =
std::three_way_comparable<T, Cat> &&
std::three_way_comparable<U, Cat> &&
std::common_reference_with<
const std::remove_reference_t<T>&,
const std::remove_reference_t<U>&> &&
s... | As hinted by @StoryTeller in the comments:
According to the "implicit expression variations" in [concepts.equality]/6, because the expression t <=> u is non-modifying (the operands are const lvalue references), variations of the expression expecting non-const lvalue references instead of const lvalue references are imp... |
71,361,923 | 71,361,974 | how to implement unique func on a string in c++ | Excuse me does anyone here know how can we remove duplicates from a string using unique func or any other func?
for example if i want to turn "fdfdfddf" into "df"
I wrote the code below but it seems it doesn't work
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int>t;
int n;
cin>>n;
... | According to the documentation, unique:
Eliminates all except the first element from every consecutive group of equivalent elements from the range [first, last) and returns a past-the-end iterator for the new logical end of the range.
If you want to get rid of the excessive elements, you have to do that explicitly, e... |
71,362,123 | 71,363,681 | Visual Studio's gtest unit calculates incorrect code coverage | I try to use gtest in visual studio enterprise 2022 and generate code coverage.
// pch.h
#pragma once
#include <gtest/gtest.h>
// pch.cpp
#include "pch.h"
// test.cpp
#include "pch.h"
int add(int a, int b) {
return a + b;
}
TEST(a, add) {
EXPECT_EQ(2, add(1, 1));
}
This image is my test coverage report:
Suc... | You should write tests in dedicated files and exclude test sources from analysis by test coverage tools. Unit tests are not subjects of any test coverage tools by their nature.
// First file, a subject for a tool
int add(int a, int b) {
return a + b;
}
// Second file, excluded from analysis by a tool
TEST(a, add) ... |
71,362,259 | 71,365,752 | Building boost::log::formatter on runtime condition | I want to build boost::log::formatter conditionally, however, formatter objects do not seem to behave as 'normal values'.
For example:
auto sink = boost::log::add_console_log(std::clog);
auto format =
expr::stream << expr::format_date_time(timestamp, "%Y-%m-%d %H:%M:%S.%f");
boost::log::formatter formatter = form... | Formatting streaming expression constructs a function object that will be executed when a log record is formatted into string. The function object type is final in the sense that you cannot modify it by adding new formatting statements to it. In fact, any streaming statement effectively creates a new formatter function... |
71,362,412 | 71,363,503 | QT creator get the time from another time zone (not local time zone) | I was trying to find how to get a current time, however, I am looking to get a time from another time zone. I tried to play with it, even trying to simply add hours to the current time, to make up to what I am trying to get, but it did not work well
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
... | To get QTime for different time zone, you could just create new QTime object based on currentTime() with specific offset.
To do that you can just call addSecs(int) function like below:
QTime currentTimeZoneTime = QTime::currentTime(); // Your time zone current time
QTime differentTimeZoneTime = localTime.addSecs(3600);... |
71,362,575 | 71,364,195 | Can't use QFont type property values when extending QML properties? | here is my code
mytext.cpp
#ifndef MYTEXT_H
#define MYTEXT_H
#include <QObject>
#include <QtQml/qqml.h>
#include <QFont>
class MyText:public QObject
{
Q_OBJECT
Q_PROPERTY(QFont font READ font WRITE setFont)
Q_PROPERTY(QString fontFamily READ fontFamily WRITE setFontFamily)
Q_PROPERTY(int fontSize READ ... | You can use the font method of Qt Qml type:
font: Qt.font({family: "Arial", pixelSize: 20})
https://doc.qt.io/qt-5/qml-qtqml-qt.html#font-method
Or setting the font's properties individually:
font.family: "Arial"
font.pixelSize: 30
Note, that the two methods cannot be mixed, so if you set the font property you cannot... |
71,363,061 | 71,363,248 | How to check if datetime object in CPP is null or not | I am using std::chrono::system_clock::time_point; this in my abstract class (header file) .
my code is as below
using datetime = std::chrono::system_clock::time_point;
class
datetime _endDate;
Now in my cpp file, I want to check if it has a value different than epoch .How can I do that?
| I did as it said in comment secion.
I used _endDate != datetime{}
|
71,363,164 | 71,498,322 | OpenVR: Implementation of virtual API functions (GetProjectionMatrix) | I couldn't find the implementation (aka. source) of the pure virtual functions from the openvr header.
I am mainly interested in the GetProjectionMatrix() function.
Where I searched (with no results):
Simple goole search
Searched the repo for the function name
In the extracted symbols, import and export tables of most... | You won't like the answer, because the sad reality is that it has no open sources available to us.
OpenVR is a purely virtual interface library, yes interfaces are open source, but the actual implementations of those interface are not. In case of libopenvr_api (it looks like) those are appended as a binary blob to the ... |
71,363,309 | 71,364,719 | FPC: file not recognized: file format not recognized | I have something that need to link some C++ codes to main Pascal program. I followed this tutorial, now I have:
download.h
#include <iostream>
#include <curl/curl.h>
using namespace std;
// function goes here
int downloadsrc(char* pkg_name){
// do stuff
}
download.pas:
unit download;
{$link download.obj} // fpc ma... | FPC, like GCC, uses COFF objects. Make sure your .obj is COFF not OMF.
If you fix that, you probably must also link some C++ runtime library, and declare downloadsrc in a C callable way, and alter the FPC declaration to match (cdecl)
|
71,363,361 | 71,363,947 | Unqualified lookup of operators in standard library templates | namespace N {
struct A {};
template<typename T>
constexpr bool operator<(const T&, const T&) { return true; }
}
constexpr bool operator<(const N::A&, const N::A&) { return false; }
#include<functional>
int main() {
static_assert(std::less<N::A>{}({}, {}), "assertion failed");
}
See https://godb... | What matters here is whether the unqualified lookup from inside std finds any other operator< (regardless of its signature!) before reaching the global namespace. That depends on what headers have been included (any standard library header may include any other), and it also depends on the language version since C++20... |
71,363,478 | 71,363,543 | CDT C++ library: How to define an edge? | I'm trying for a while to define an edge in CDT. Below is my code. The first function works fine, but the compilation of the second function throws this error: no matching function for call to CDT::Edge::Edge(). I also attempted numerous other trials, with no luck.
typedef CDT::V2d<double> Vertex;
typedef CDT::Edge Edg... | Edge does not have a default constructor, so you can’t give a vector<Edge> an initial size (since that would require each element to be initially default-constructed). Instead, make the vector empty to begin with (you can reserve() capacity for it if you like) and then add edge with push_back()… or, better yet, constru... |
71,364,060 | 71,386,916 | Design pattern for isolating parsing code? | I have C++ class Foo:
class Foo
{
public:
[constructor, methods]
private:
[methods, data members]
};
I want to add to class Foo the possibility for it to be constructed by reading data from a text file. The code for reading such data is complicated enough that it requires, in addition to a new constructor, se... | I think this would be a good opportunity to use the so-called Method Object pattern. You can read about that pattern on various web sites. The best description I have found, though, is in Chapter 8 of Kent Beck's book Implementation Patterns.
Your use case is unusual in the sense that this pattern would apply to a cons... |
71,364,236 | 71,364,315 | Run C++ on MacOS without xcode | I don't have Xcode installed on my Mac OS 13.6 but I would like to run c++ on vs code. Is there a way to do that without the need for Xcode to be installed? Also, can I run an older version of Xcode and run c++ without problems?
Note: Would be great if someone posted a link for a tutorial.
| You may download and install LLVM 13.0.1 for Darwin or a small part of Xcode, Xcode command line tools: xcode-select --install.
Both will result in installing clang++.
|
71,364,272 | 71,364,387 | C++ FlatBuffers - Assertion failed: (finished), function Finished | Here is my schema:
namespace Vibranium;
enum GameObject_Type:uint { STATIC = 0 }
table GameObjectDatabase
{
gameobjects:[GameObjectsTemplate];
}
table GameObjectsTemplate
{
id:int;
name:string;
prefab:string;
type:GameObject_Type;
position_x:float;
position_y:float;
position_z:float;
... | If you get an assert, it is always good to check the assert code, it may give you a hint as to why:
void Finished() const {
// If you get this assert, you're attempting to get access a buffer
// which hasn't been finished yet. Be sure to call
// FlatBufferBuilder::Finish with your root table.
// If yo... |
71,364,817 | 71,364,849 | Library that includes undefined behavior function working on a certain compiler is portable? | If I compiled a library that includes an undefined behavior function guaranteed to work on a certain compiler, is it portable to other compilers?
I thought that the library has already generated assembly, so, when other programs call UB function, the function assembly well-defined to a certain compiler would be execu... | Do not look to the C++ standard for all your answers.
The C++ standard does not define the behavior when object modules compiled by different compilers are linked together. The jurisdiction of the C++ standard is solely single C++ implementations whose creators choose to conform to the C++ standard.
Linking together di... |
71,364,829 | 71,365,568 | Generating an NxN magic square using a dynamically allocated 2D array in C++ with user-input dimension | I'm trying to generate and solve an NxN odd-numbered magic square through dynamic memory allocation but whenever I run the code, it displays nothing on the terminal and the programme ends. I reckon it has something to do with the dynamic allocation of the 2D array, as when I make a normal NxN array with a constant size... | This isn't too bad.
int ** Array=new int*[N];
for(int i=0; i<N; i++)
{
Array[i]=new int[N];
}
memset(Array, 0, sizeof(Array));
The memset is causing your trouble, and it's wrong for two reasons. First, let's say you really wanted to do that. You don't, but let's say you did. How big is size... |
71,365,310 | 71,365,388 | Defining a struct method with function parameter in C++ | Looking at C++ interface code. I do not have access to the implementation.
I made a small example to show the behavior.
struct MessageInfo{
MessageInfo() : length{}, from{}, to{} {}
MessageInfo(int _length, string _from, string _to) : length{_length}, from{_from}, to{_to}
{}
int length;
... | It expects you to pass a generic callable, e.g. a lambda. You don't have to specify the template argument. It can be deduced from the function argument.
For example:
MessageInfo messageInfo (1000, "A", "B");
auto printFields = [](auto&& f){ std::cout << "Value of this field is " << f << ".\n"; };
messageInfo.enumerat... |
71,365,319 | 71,365,385 | Unique combinations of dice | I'm trying to model Yahtzee (a dice game).
As a first step, I'm trying to enumerate all possible combinations of 5 dice being rolled simultaneously. I only want unique combinations (e.g. 5,5,5,4,4 is the same as 5,5,4,5,4 and so on). Is there an easy way to do this in Python, C++, or Mathematica?
| You can use itertools.combinations_with_replacement() in Python:
from itertools import combinations_with_replacement
options = list(range(1, 7))
print(list(combinations_with_replacement(options, 5)))
|
71,365,756 | 71,365,939 | When reusing a variable assigned to a class, why is only the last destructor call causing a crash? | I have case where I have a class that allocates memory in the constructor, and frees it in the destructor -- pretty basic stuff. The problem happens if I reuse the class instance variable for a new instance of the class. When the final (and only the final) instance gets destroyed when it goes out of scope, it will cras... | First of all the constructor itself has undefined behavior, because you allocate only enough space for the length of the string (strlen(c)) which misses the additional element required for the null-terminator.
Assuming in the following that you fix that.
The destructor on an object/instance is only ever called once.
I... |
71,365,895 | 71,365,930 | Acces private static member variable in namespace from another class C++ | I have a problem. In the following example, there is a static private member variable called private_b of class A inside namespace a. And then I'm trying to access that variable from class B, which I have declared to be a friend of class A, but it doesn't work, with a compile error from GCC:
error: ‘B* a::A::private_b... | friend class B; declared friendship with B in the same namespace a. You may want friend class ::B;.
Note, friend class B; does not refer to the global forward declaration class B, it has own forward declaration class B after the keyword friend.
|
71,366,866 | 71,366,972 | Do inlined pass-by-reference functions still create reference variables? | I am writing a loop that has some state variables.
int MyFunc(){
int state_variable_1 = 0;
int state_variable_2 = 12;
while(state_variable_1 != state_variable_2){
BodyOfWhileLoop(state_variable_1, state_variable_2);
}
}
As you can see, I have written the body of the while loop in a separate fu... | No, they do not. Demonstration: https://godbolt.org/z/qc1ne7ezM.
References are typically implemented as pointers under the hood (though they do not have to be). Once the function is inlined the compiler will eliminate the indirection. In LLVM, this optimization is performed as part of SROA.
Any function with only one ... |
71,366,901 | 71,376,243 | Is searching a string using a switch inside a for loop inefficient? | Recently did an online programming assessment, where the question was essentially "search a number for specified integers and increment a count".
My solution was to convert the given number to a string, and then search through the string using a for loop and a switch statement.
So basically:
for (int i = 0; i < str.len... | switch is generally not inefficient; internally it is typically implemented either as a jump-table to the various options, or as a binary search, or as a series of if-then statements, depending on what the compiler/optimizer thinks will execute fastest.
However, you could gain some efficiency in this case by avoiding t... |
71,367,332 | 71,367,352 | Can't sum a vector of integers using for loop c++ | I am writing a function that takes a vector of integers as input, and iterates through the vector to obtain the maximum and minimum values in the vector, as well as the sum. The maximum possible integer in the argument vector is 1000000000.
void miniMaxSum(vector<long> arr) {
long sum = 0;
long min = 1000000000... | long is usually a 32-bit type on most operating systems (at least 32-bit). So the maximum value it can hold is 2,147,483,647.
The sum of your numbers is 3,467,737,930. So it overflows.
Consider using unsigned long or long long (at least 64 bits) or unsigned long long for larger numbers. Or you could even use intmax_t o... |
71,367,385 | 71,368,919 | Stack allocating intermediate objects in contructors | When a constructor allocates intermediate objects that need to be passed to other constructors with longer lifetimes, can the intermediate objects be stack-allocated?
For example, I have a class Reader that has various utilities build atop an std::wistream that has several constructors for various use cases:
Reader(st... |
Yes, you have to keep bytestream alive and the typical way is storing it in a unique_ptr member variable.
Yes it is a problem that m_character_stream is going to use the pointer you pass beyond the lifetime of conversion. So yes, make conversion a member variable.
C++ does not have garbage collection. Lifetime ma... |
71,367,464 | 71,367,565 | Why isn't my char* shrinking after popping a char | For context, I'm rewriting the string class in C++ to use on microcontrollers, specifically Arduino, so that it doesn't use the standard library functions not supported by Arduino.
I've looked at several answers here that show how to pop a char off a char*. However, within my function it doesn't seem to correctly edit ... |
Why isn't the data member data being altered when calling the pop_back function?
Even if the code compiles (which it shouldn't, since you are trying to construct x with a string literal, which is a const char[] array that cannot be assigned to a non-const char*), x would be pointing its data member at a string litera... |
71,367,676 | 71,367,804 | Using a pointer to a member function as a key in unordered_map | I have a unordered map std::unordered_map<void (MyClass::*)(), double> used to store the time that has elapsed since a function has been called. I'm getting an error saying that
error: use of deleted function ‘std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::unordered_map() [with _Key = void (MyClass::*)(); _Tp = d... | std::unordered_map stores its data using some calculations involving std::hash function. As described in the documentation for std::hash, under subsections "Standard specializations for basic types" and "Standard specializations for library types", there are only limited types that std::hash can perform on and void (My... |
71,367,695 | 71,371,709 | How to implement Big Int in Javascript? | I am working on open-source project. It doesn’t properly meet its specs due to the representation as JavaScript numbers ie let,const... I want to add support for Int, Long Int, and Big Ints similar to c++.
Can anyone please suggest any resource or approach to achieve this?
Thank you
| JavaScript has gained BigInt support as a feature a couple of years ago. By now, most users have browsers new enough to support it: https://caniuse.com/bigint.
If you want to support even older browsers, there are a variety of pure JavaScript implementations with different pros and cons, for example JSBI, MikeMcl's big... |
71,368,541 | 71,368,677 | Defining "hidden" constants in c++ header-only libraries | I'm creating a C++ header-only implementation of a library in which I defined multiple constants (defined as static constexprs) that I only want to use in the library, to make my code more clear and readable. I thought having internal linkage would be enough to "hide" these constants from any other source files in whic... | A couple of viable approaches:
inner namespace, (boost-style)
namespace mylib
{
namespace detail
{
inline constexpr int const goodenough{42};
}
int foo(void)
{
return detail::goodenough;
}
}
conversion into private static fields of some class with access granted by frien... |
71,368,645 | 71,368,722 | difficulty in understanding c++ function that resolves function names by ordinals | I am following a malware analysis course. And I came across this code which I found confusing. The first two sections make sense but the part where the if statement starts is very difficult for me to understand. This "if" statement is supposed to resolve function names by ordinals. I have put my questions in the commen... | This allows you to split a number (here dword or double word) in two parts using bit operations, e.g:
0x12345678 >> 16 = 0x1234 (hi order word)
0x12345678 & 0xFFFF = 0x5678 (lo order word)
Why is the code doing that? It's documented with GetProcAddress's lpProcName parameter:
The function or variable name, or the fun... |
71,368,658 | 71,368,789 | How to move an element in std::list to the end using std:move and back inserter? | In my std::list, i have 10 elements, and i want to move the number 1000 to the back of the list.
https://leetcode.com/playground/gucNuPit
is there a better way, a 1 liner using std::move, back inserter or any other C++ syntax to achieve this with consciously?
// Move the number 1000 to the end of the list
#include <io... | You can use the std::list::splice(..) to achieve this
myList.splice(myList.end(), myList, std::find(myList.begin(), myList.end(), 1000));
Check out the documentation
|
71,368,669 | 72,119,435 | Cannot get gfwl source package to work in vscode | I wanted to learn OpenGl because I was just getting into c++ and I thought it would be cool to learn but now I'm stuck and I don't know what to do.
So basically I am not using the microsoft version of VScode, I am using your basic VScode application.
I install MinGw and added it to the path.
and i created a folder, in ... | Make sure to add it to the path and use a MakeFile to compile and to connect everything!
|
71,368,709 | 71,369,074 | How to use an enum attribute of a class for an argument of a setter function for that class? | I have a class method that needs to know the value of a variable named mode which takes the values 1 an 0 and is a private attribute of the class. I want to write a setter function that can change mode to 1 or 0. However, I must use an enum to determine the new value that I should set mode to: enum sequence {error=0,ac... | It's pretty straight forward. This is how I would do it in C++11 and above:
class Blink {
public:
enum class Sequence { Error, Active };
void setter(Sequence s) {
if (s == Sequence::Active) {
mode = 1;
} else {
mode = 0;
}
}
private:
int mode = 0;
};
Blink b;
int main() {
b.se... |
71,369,087 | 73,994,605 | Why does temporary struct member not have the expected value in C++? | Consider this code:
#include<iostream>
struct A
{
int b;
};
int main()
{
int c = (A() = A{2}).b; // Why is c zero after this?
std::cout << "c = " << c << std::endl;
std::cout << "A.b = " << (A() = A{2}).b << std::endl;
}
In my mind this is two equivalent ways to print the same value, but I get this ... | As mentioned by @StoryTeller-UnslanderMonica, this is a GCC bug. I tested several versions on godbolt.com. Here's what I found:
works as expected on gcc 6.* with c++ 11 and 14
fails on gcc 7.*, 8.*, 9.1-4 with c++14
works on gcc 7.*, 8.*, 9.* with c++11
works on gcc 9.5 with c++14
works on gcc 10 with c++ 11 and 14
I... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.