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 |
|---|---|---|---|---|
64,187,653 | 64,187,697 | C++ limit input to only be integars so letters aren't valid | See code below. It works fine for numbers but if I enter a letter (eg 'a'), it will output 'first number 0 is divisible by second number, 6487956' without asking for input of second number.
#include<iostream>
using namespace std;
int main()
{
int first, second;
cout << "Please enter your first number (must b... | Here is an example which will not accept if input has any characters. Function to check if string has only numbers.
#include <iostream>
#include <string>
#include <algorithm>
bool is_digits(const std::string& str)
{
return std::all_of(str.begin(), str.end(), std::isdigit);
}
void get_number(std::string& number, c... |
64,187,874 | 64,188,005 | Why my pointer variable is holding different address and still pointing to variable successfully? | Code:
# include <iostream>
using namespace std;
int main(){
int num = 10, *p;
*p = num;
cout<<" &num = "<<&num<<" p = "<<p<<endl<<" *p = "<<*p<<endl;
return 0;
}
Output:
&num = 0x7ffeef0908c8 p = 0x7ffeef0908e0
*p = 10
Theoretically content of 'p' is equal to the address of 'num'. But it's not happe... | Your code is UB. It may look as if it worked, but could as well corrupt or crash the system, or anything else (usually bad) could happen.
int num = 10, *p; // this leaves p unitialized; you don't know to what it points
*p = num; // OUCH! This is UB because you dereference an unitialized pointer
Here a wor... |
64,187,889 | 64,188,796 | Is there a way to change where a reference member of std::pair is pointing? | So once an std::pair with at least one reference variable has been initialized, for example like this:
int a = 53;
int b = 42;
std::pair<int, int&> foo(33, a);
Is there a way to change where the reference variable is pointing?
Assignment:
foo = std::make_pair(33, std::ref(b));
and swapping:
std::pair<int, int&> bar(3... | You shouldn't rebind references...
...but you kinda can. Trying to assign a reference is impossible, but you can achieve the same effect
new (&foo) std::pair<int, int&>(33, b);
will destroy the old pair† and construct a new pair referencing b. You are correct, a pair with a reference member isn't the same as a plain r... |
64,188,087 | 64,188,164 | Access a variable value having it's reference address as string | I want to convert a pointer value to string, so I have a variable address as string, and then using this string to convert back to a pointer value, and be able to access the original variable value.
#include <sstream>
#include <string>
int *a = new int[5];
a[0] = 105;
a[1] = 106;
a[2] = 107;
a[3] = 108;
a[4] =... | Use a uintptr_t to hold your pointer value. The type uintptr_t is an unsigned integer which is guaranteed to be large enough to hold any pointer. Like this
int *a = new int[5];
a[0] = 105;
a[1] = 106;
a[2] = 107;
a[3] = 108;
a[4] = 109;
const void * address = static_cast<const void*>(a);
std::stringstream ss;
ss << re... |
64,188,247 | 64,188,433 | Do standard library containers have unused variables in their structure? | I've been doing a bit of reverse engineering on an application, and have managed to identify a couple of standard library containers, like std::vector and std::map, but what I found using std::map as an example is that it has 20 bytes between the pointer to itself and the rest of the fields (members pointer and count).... | Standard library containers are not specified to have, or to not have, unused variables (or any padding) in their structure. The standard states how containers must behave and what their interface must be, not how they must be implemented.
Such a thing is certainly not impossible — most compilers add padding to class t... |
64,188,551 | 64,188,570 | Using the only the preprocessor for string concatenation? | Is it possible to concatenate quoted string literals outside of the language (C++, in this case)?
That is, can I define MY_MACRO(a,b,c) and use it thus:
MY_MACRO("one", "two", "three")
and have it expand to: "onetwothree"?
The use case is to apply an attribute and its message to, say, a function signature, like so:
MY... | The language already does string concatenation!
This:
"hi" "James"
becomes just one string literal.
That means you do not need any preprocessor tricks for this at all.
You need only employ this in the output of your macro:
#define MY_ATTRIBUTE_MACRO(x,y,z) [[nodiscard(x y z)]]
Now this:
MY_ATTRIBUTE_MACRO("this", "i... |
64,189,013 | 64,189,130 | how to find location of missing library | I have installed the mysql connector for c++. I am writing a c++ cgi app. The cgi page has been compiling. I rebooted yesterday and it stopped compiling. g++ -o sales.cgi sales.cpp -lcgicc -lmysqlcppcon. Gives the following error. /usr/bin/ld cannot find -lmysqlcppcon
apt-get tells me I have the latest version of ... | Since you installed with apt-get, then you can use dpkg to determine which files were installed.
EXAMPLE (you would substitute "mysqlcppcon"):
dpkg -l|grep -i mysql
ii php-mysql 1:7.2+60ubuntu1 all MySQL module for PHP [default]
... <= Search for the exact pa... |
64,189,530 | 64,189,601 | C++: Why is unordered_set::find faster than find? | When I do unordered_set::find
unordered_set<int> uniqueNum;
//code...
if(uniqueNum.find(num + k) != uniqueNum.end())
//code ...
the runtime of this code is faster than
unordered_set<int> uniqueNum;
//code...
if(find(uniqueNum.begin(), uniqueNum.end(), num + k) != uniqueNum.end())
//code...
Accord... | This is due to how they are implemented. std::find operates as you might expect. Start at the beginning and compare each element until it reaches the end. This is fairly universal, but won't benefit from the specific data structure used. However, unordered_set is a hashset so if there are no hash collisions, every elem... |
64,189,536 | 64,201,653 | Is the visual studio release mode exe file standalone or not? | I want to build a single standalone executable file for a windows console application built in Visual Studio 2019. By standalone, I mean that I want a single exe file that I can move to any location on any computer and it will still run without extra files surrounding it (no dependencies).
For the life of me, I can't f... | You could use Microsoft Visual Studio Installer to deploy a Visual C++ Application.
For third-party libraries, you could select static linking version. If there is no static link version and only dll, copy the corresponding dll together when publishing.
For the c++ runtime library, select the static compilation method:... |
64,189,683 | 66,238,128 | Unable to Inspect C++ STL content in VS Code | Problem Statement:
The debugger is not able to provide the content of an STL container (i.e. vector or string).
Overview:
Below is my launch.json, where I have added -enable-pretty-printing as per this thread but I'm unable to see the content of the STL Container.
{
"version": "0.2.0",
"configurations": [
... | Firstly, you probably used x64 Windows.
I found one valid solution, when installing MinGW in x64 Windows, install i686 (win32) version (the bottom of this comment gives its official download link) of MinGW instead of x86_64 version, see below:
win32 version of MinGW download:
i686-win32-dwarf
I just extracted the down... |
64,189,855 | 64,189,870 | C++ list/queue top return value | I have a C++ code as following :
#include <iostream>
#include <queue>
#include <list>
using namespace std;
int main(){
priority_queue<pair<int, int>> q;
q.push({8, 8});
q.push({19, 19});
q.push({23, 23});
while (q.size() > 0){
auto& cur = q.top();
q.pop();
cout << cur.first... | When you do:
auto& cur = q.top();
you are taking a reference to the top element in the priority_queue. But when you do:
q.pop();
this element is removed, and all references to it, including cur, are left dangling. Any attempt to read from cur e.g:
cout << cur.first << " " << cur.second << " ";
will invoke undefined ... |
64,189,878 | 64,189,900 | Pointer to a Vector of Vectors in a Function Gives 'expression must have pointer type' error | Visual Studio Code gives me an 'expression must have pointer type' error for the line int size = graph->at(node)->size();. I am aware that I could use references but I want to know how to do it with a pointer.
#include <vector>
using namespace std;
void getPathEdges(vector<vector<int>>* graph, int sink, int count, int ... | You're going to want
graph->at(node).size();
The first access is a -> because you have a vector<vector<int>>* (a pointer). graph->at(node) returns a vector<int> (not a pointer), so access on it is done simply via ., not ->.
|
64,190,350 | 64,190,852 | How to get HWID in c++ simular to c# | Using this code in c#:
WindowsIdentity.GetCurrent().User.Value;
And getting output:
S-1-5-21-3050176684-2277112922-4090480026-1001
How to get same output in c++?
| Here is some code on how you can get the SID for an account name on the local computer using LookupAccountName (Link to API):
#include <windows.h>
#include <iostream>
#include <sddl.h>
LPCWSTR GetSid(LPCWSTR szAccountName)
{
LPWSTR pszRet = NULL;
DWORD dwDomainSize = 32, dwSidSize = 32;
LPWSTR pszDomainNa... |
64,190,535 | 64,190,637 | Mocking C++ classes that copy constructors | I'm coming from C# to C++ and when I try to construct tests, copy constructors are making it hard for me to mock the usual way I am accustomed to.
#include <iostream>
using namespace std;
class DB {
public:
virtual int getValue() { return 42; }
DB(const DB& source) { }
DB() { }
};
class DB_Mock: public D... | m_db is not a reference or pointer, c++ polymorphism is work with only base class pointer or reference.
A(DB db) {
m_db = db; // m_db just sliced copy of base part of db.
}
Change this to reference like
class A
{
public:
explicit A(DB &db) : m_db(db) // it is initializing not copy
{
}
v... |
64,190,976 | 64,190,994 | Why there set macro definition and namespace in C++ .h file? | I am reading this open source project:
I have two questions:
I found the
#ifndef _RANGE_REQUEST_GENERATOR_H_
#define _RANGE_REQUEST_GENERATOR_H_
#endif
and I only find the _RANGE_REQUEST_GENERATOR_H_ in this .h file, other place not use it.
so, what's the usage of the macro definition?
there use the namespace wrap ... | Question #1
See Purpose of Header guards
Question #2
Consider the case where you are using libraries. And two libraries would both like to have a function named Push(). We could name them: LibraryFoo_Push(), and LibraryBar_Push(), or we could use namespaces. Namespaces have some additional benefits with lookups as well... |
64,191,653 | 64,191,654 | How do you create a reference to an array at a certain address? | In C++, it is possible to create variables that are references to memory addresses.
volatile uint8_t& PPUSTATUS = *(volatile uint8_t*)0x2000;
This can be useful for things like memory-mapped I/O or hardware reserved memory regions, especially for embedded systems.
You can even create pointers to memory regions.
volati... | uint8_t(&FDS_WAV)[64] = (uint8_t(&)[64])(*(uint8_t**)0x4040);
This will create an array of 64 uint8_t at address 0x4040.
&FDS_WAV will return 0x00004040, and sizeof(FDS_WAV) will return 64.
|
64,191,793 | 64,191,841 | How do I use other values in a vector in a std::transform? | Given the code below which just adds 1 to each element of a vector:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
// Create vector 1 - print it out
std::vector<int> v1 {1,2,3,4,5,6,7,8,9};
for (auto val : v1)
{
std::cout << val << " ";
}
std::cout << std::endl;... | You can add lambda capture to store the previous element's value.
E.g.
std::vector<int> v2(v1.size());
std::transform(v1.begin(), v1.end(), v2.begin(),
[pv = 0](int val) mutable { int nv = pv + val; pv = val; return nv; });
LIVE
PS: Captures with initializer was supported since C++14.
|
64,192,585 | 64,192,688 | Can I type check a template parameter? (C++) | I want to check if a given variable is a char. Right now, my function returns a string based on the elements of a vector.
The issue is if I give it a char vector, then to_string() gives me the numeric value of the character 'foo'. So where I want it to read:
a b
it instead reads
97 98
I would rather implement something... | You can try with an if constexpr and the type traits is_same
#include <iostream>
#include <type_traits>
#include <vector>
template <class T>
std::string vtos (const std::vector<T> &v )
{
std::string ret;
int i = 0;
auto to_string = [](const auto& elem)
{
if constexpr ( std::is_same_v<T,char> )
... |
64,192,817 | 64,193,955 | how to test for equality between objects with common superclass | I have a virtual class called X and subclasses X1 X2 and X3.
Clarification: these classes are dumb data: int, double, string, vector<> of the preceding. There may be pointers to read-only static data structures whereby equality is a shallow check that the pointers be equal. There won't be for instance FILE* where it ... | In C++, often the virtual methods are public.
There is an idiom that some C++ programs use where the base class public methods are not virtual, and it is used to call a private virtual method. The rationale for this approach is that it separates out the public facing API from the derived class extensibility API (the v... |
64,192,885 | 64,193,136 | Is this use of offsetof guaranteed to be correct? | I have read that offsetof macro is commonly implemented as:
#define offsetof(st, m) \
((size_t)&(((st *)0)->m))
And according to Wikipedia there is debate about whether this is undefined behavior because it may be dereferencing a pointer. I have a buffer of information that I need to send to different places, but ... | The standard specifies behaviors of things, not how are they implemented. The implementation part is left to implementators - people who write compilers and libraries - and they have to implement things in a way they work in a way specified by the standard. If that implementation of standard library has by itself undef... |
64,193,165 | 64,195,070 | Two interdependent member functions with no default constructor | I am sure that this question must be answered somewhere, but I cannot formulate the question...
My issue is that I have two objects (foo, bar), where bar needs to be initialized using foo instance. How to do it, when both objects are data members of another class (baz)?
I cannot initialize bar in baz constructor body a... | Since mBar depends upon mFoo, just reorder the declarations:
private:
foo mFoo;
bar mBar;
and initialize mFoo first:
baz() : mFoo(), mBar(mFoo) {
// ...
}
Here's a demo.
|
64,193,355 | 64,196,592 | Lowest Common Ancestor Time Limit Exceeded using the root to node path approach | I have implemented the solution for LCA problem. The problem statement is that Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
The approach that I used, was to find the path from root to the given 2 nodes and store the 2 paths in a vector.
Start comparing nodes in both paths s... | The problem is that your code makes all vector pointers to reference the same vector. But you need path1 and path2 to be separate vectors. So if after doing path = res you have another res.push_back(root), this will affect path which has become a synonym for res...
Secondly, your recursive search still continues search... |
64,193,445 | 64,218,616 | How can I calculate 2^n+2^n-1+...+2^k mod 2^60 in C++, where the value of 2^i can be very big? | For a programming question I have to print the expression 2^n+2^n-1+...+2^k mod 2^60, where 1<=k<n<=240?
Basically, how can I calculate 2^240 mod 2^60? If this can be solved, I can make it work for n<240 as well!
I read an answer here:
How can I calculate 2^n for large n?
But, that calculates for large values of n and ... | 2^k + 2^k+1 + ... + 2^n-1 + 2^n mod 2^60
=
2^k * (2^0 + 2^1 + ... + 2^n-k-1 + 2^n-k) mod 2^60
=
2^k * ((2^n-k+1)-1) mod 2^60
=
(2^n+1 - 2^k) mod 2^60
=
(2^n+1 mod 2^60 - 2^k mod 2^60) mod 2^60
k >= 60: result is 0 because both 2^n+1 and 2^k can be divided by 2^60
k < 60:
n >= 59: result is -2^k
n < 59: result is... |
64,193,803 | 64,193,836 | Cannot start process from different directory | I'm trying to write a program in C++ that launches an executable. When I try to run the program, nothing happens. But when I try to run the program on the same directory and drive the exe is in, it does work.
Here's the code:
else if (result1 == 0) {
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstan... | Most likely you should set the lpCurrentDirectory parameter to the directory the exe is in.
See: CreateProcess
It's often that executables like RA95Launcher.exe are depending on other files. Usually these are reffered to by a relative path from perspective of the Current Working Directory.
If you launch the process fr... |
64,193,811 | 64,194,318 | Stockfish 12 source code: Templates replacing function parameters | Since Stockfish is the highest rated chess engine, and it's known to be quite CPU-effiecient I decided to open its source code and try to understand and see how it works.
I came across this snippet of code, simply shifts a bitboard to a certain direction (north, south, east...)
TAKEN FROM STOCKFISH 12 SOURCE: Download
... |
What is the need to have a template in this context, and why would something like
// omitted code
not work?
The version with the parameter given will work as well.
Is the first way more efficient in any way?
Yes, using the template will be more efficient, since D is always evaluated at compile time, as it's a cons... |
64,193,984 | 64,194,905 | Trying to diagnose difference between C++ standard for-loop and accumulate with side effects | I'm implementing the Max-Profit Algorithm in C++.
Find the Maximum Profit for a given stock trading day. Solution should be O(N) in Time and O(1) in Space requirements. You're allowed to purchase once in the day, and sell once in the day.
And I originally implemented like:
int maxprofit_int(vector<int> const& v) {
... | Your code is benchmarked, but not tested...
resProfit = max(resProfit, price);
should read
resProfit = max(resProfit, profit);
After this change the two versions run at the same speed.
|
64,194,118 | 64,503,104 | Swap operation error: binding value of type 'const vector<...>' to reference to type 'vector<...>' drops 'const' qualifier | I have a class method which returns const std::vector:
class TriangleMesh
{
public:
const std::vector<Vec3i>& indices() const { return m_indices; };
private:
std::vector<Vec3i> m_indices;
};
I'm calling the above method by another struct and doing a swap operation:
struct Contour3D {
std::vector<Vec3i> fa... | Thanks to @Yksisarvinen this statement works fine:
faces3 = trmesh.indices();
|
64,194,216 | 64,194,252 | added subdirectory to CMakeLists.txt isn't detected by main.cpp | I'm working on creating a python binding to a c++ code using Pybind11.
My project architecture is the following:
-- MyProject
| -- lib
| -- pybind11
| -- CMakeLists.txt
| -- include
| -- myCPPCode
| -- CMakeLists.txt
| -- MyCodeDefinitions.h
... | The add_subdirectory just tells cmake to find a CMakeLists.txt in the directory given as argument.
You need to change your add_subdirectory(lib/myCPPCode) into include_directories(lib/myCPPCode) and it should work better.
|
64,194,698 | 64,194,925 | The constructor's member initializer list can't include superclass's members? | I've been programming C++ for decades and never expected this limitation.
Is there something obvious I'm overlooking? I guess I need to make the X() constructor take an argument for i and let that constructor initialize it? What can the point of this weird limitation possibly be? I can understand forbidding us from ... | That's meant to be as initialization of object is a part of that objects creation, you either have to provide initialization via X, or redesign to be able initialize it directly:
class X {
public:
X() {};
X(int _i) : i(_i) {};
int i;
};
or
class X {
public:
int i;
};
so you can do this:
class X1 : public X {
... |
64,194,829 | 64,194,866 | C++17 error: "expected primary-expression before '.' token" when passing enum value to function | Writing a small project. Need to pass value from enum into function.
Compilling using G++. gcc version 9.3.0 (Homebrew GCC 9.3.0_1) with -std=c++17
enum memberType {DIRECTORY, EXECUTABLE, BASIC}; // Types member can be (basic - default file)
struct directoryMember{ // Directory member basic structure
std::string n... | Firstly, the return type of defineDirectoryMember is not void, so it must return something using return statement or abort execution like throwing exceptions.
It seems you wanted to return tmp.
Secondly, memberType is not a variable name but a type name, so :: should be used instead of . to separate with its member.
#i... |
64,194,968 | 64,195,003 | Callback: function pointer as argument and passing an aditional agrument | How to pass a function pointer as argument with an argument?
void A(){
std::cout << "hello" << endl;
}
void B(void (*ptr)()){ // function pointer as agrument
ptr(); // call back function "ptr" points.
}
void C(string name){
std::cout << "hello" << name << endl;
}
void D(void (*ptr2)(string name)){ // fun... | You should make D taking two parameters, one for the function pointer, one for the argument to be passed to function pointer. E.g.
void D(void (*ptr2)(string), const string& name){
ptr2(name);
}
then call it like
D(q, "John Doe");
|
64,195,021 | 64,213,781 | Telemetry server using boost::signals2 | I'm trying to build a telemetry server for one of my projects, which connects a raspberry pi with my local computer. My idea was to have a request driven server, which then captures the required data. Therefore I'm using boost:signals2, to provide the mapping between names and the approriate functions.
The example code... | The reason you're seeing this error is related to how class methods work.
The address for the code that executes the method is &message::getMessage. But this isn't a function pointer because a class has both code and data, and this is only the address to the code.
To execute the method, you need both the address of the... |
64,195,050 | 64,197,282 | How to draw UML to illustrate 2 threads working on a critical section | I have a small program that runs 2 threads on the same critical section and uses mutex. The program works fine. But I would like to draw a UML, referably activity or state diagram, illustrating that the 2 threads runs the same critical section, not different parts of the codes. Please help me revise my UML.
Below is th... |
It definitely has some faults
yes, for instance :
both join finish before the execution of hello, this is impossible
each join are executed in one the separated threads, this must be done by main
there is a fork but no join (the UML one)
after the action unlock the flow goes to t2.join which is false and produces a ... |
64,195,482 | 64,198,731 | Chained compound assignments with C++17 sequencing are still undefined behaviour? | Originally, I presented a more complicated example, this one was proposed by @n. 'pronouns' m. in a now-deleted answer. But the question became too long, see edit history if you are interested.
Has the following program well-defined behaviour in C++17?
int main()
{
int a=5;
(a += 1) += a;
return a;
}
I bel... | In order to follow better what is actually performed, let's try to mimic the same with our own type and add some printouts:
class Number {
int num = 0;
public:
Number(int n): num(n) {}
Number operator+=(int i) {
std::cout << "+=(int) for *this = " << num
<< " and int = " << i << st... |
64,195,486 | 64,195,606 | can u use head->data as an integer variable, if the "data" is integer type in chained lists? | can u use head->data as an integer variable, if the "data" is integer type in chained lists.
for example, I have a code where I have to transform a simply chained list of integer variables, into 2 lists, one with positive numbers, the other one with negative numbers. I cant find the error in my code...
using namespace... | Errors in your code:
Required #include directives don't present.
extra "```" exists at the end of code.
No return type is specified for write.
In the function write, return with value is used while no return statement presents at the end of the function, so no return type is valid for that.
The function write breaks t... |
64,195,788 | 64,196,080 | How to dynamically store address of a QVector<T> in another QVector<QVector<T>*>? | I am working with large amounts of data, something like 100,000 double values, being gathered every 100 milliseconds or so. I have to store 25 or even more of these generated data in my software at any given time. Both, the data length on each acquisition as well as the number of acquisitions varies depending on the cu... | You're storing addresses to objects that are then destroyed. That means your vector of pointers contains dangling pointers:
void MainWindow::addData()
{
myVec << &QVector<double>(0);
// the temporary vector is destroyed here and myVec contains a
// dangling pointer
*myVec[0] << 2.7 << 3.4 << 4.5;
}
I'm... |
64,196,297 | 64,196,475 | what does unique_lock mean when a single thread acquire 2 unique_lock of the same mutex? | I have the following code, which is from https://en.cppreference.com/w/cpp/thread/unique_lock. However, upon, printing the output, I see some unexpected result and would like some explaination.
The code is:
#include <mutex>
#include <thread>
#include <chrono>
#include <iostream>
struct Box {
explicit Box(int num)... |
I expected the lock1 fill be unlocked first, and lock2 later.
No, the reverse is true. In your function lock1 gets constructed first, then lock2. Therefore, when the function returns lock2 gets destroyed first, then lock1, so lock2's destructor releases its lock before lock1's destructor.
The actual order in which st... |
64,196,362 | 64,196,598 | Comma operator returns an unchanged value | I am following the C++ primer 5th edition book as it was mentioned to be a good beginner friendly book to learn C++. As I proceeded to solve the exercise in chapter 4 I came across the question 4.33 in section 4.10. I am posting below the question as written in book:
Using Table 4.12 (p. 166) explain what the following... | Although you are correct in your assumption that the order of evaluation of expressions separated by the comma operator is guaranteed (to be left-to-right), what you have not considered here is the priority of operators.
The comma operator has the lowest priority of all. So, the following:
std::cout << (true ? ++x,... |
64,196,584 | 64,216,515 | How can I write a const propagating pointer type wrapper? | To better understand the C++ type system, I have endeavored to write a pointer wrapper class which propagates constness similar to std::experimental::propagate_const:
template <typename Pointee> class Ptr {
public:
Ptr() = delete;
explicit Ptr(Pointee *);
Ptr(const Ptr<Pointee> &) = delete;
Ptr(Ptr<Pointee> &... | You are looking at problems that do not really exist.
To prevent non-const access of a const
pointed-to object by copying a const Ptr into a non-const Ptr.
This should not be a goal, as it goes against the idea of propagating const.
There are two aspects to propagating const. First, when the pointer is const-qualif... |
64,196,626 | 64,196,645 | What does -0 mean in C and C++? | I was writing an algorithm in C/++ and when I was debugging using a print statement (very professional, I know), I saw an odd value: -0. Does this mean the same thing as a regular 0 or could this cause bugs? If so, how can I fix those bugs?
| In both languages -0 is the unary negation of the int constant / literal 0.
If your int is 2's complement (most likely in C, and must be from C++20), then it's exactly the same as 0, and no sane formatter would ever print -0 for 0.
If your int is 1's complement or signed magnitude then -0 is a signed negative zero. It ... |
64,196,726 | 64,198,622 | How is char array stored in C++? | int main()
{
char c1[5]="abcde";
char c2[5]={'a','b','c','d','e'};
char *s1 = c1;
char *s2 = c2;
printf("%s",s1);
printf("%s",s2);
return 0;
}
In this code snippet, the char array C2 doesn't return any error but the char array C1 returns string too long. I know that C1 must require a siz... |
I know that C1 must require a size of 6 to store 5 characters as it stores the \0 (NULL char) in the last index. But I'm confused why C2 works just fine then?
The compiler does not complain about the initialization of c2 because initializing with {'a','b','c','d','e'} does not implicitly include a terminating null ch... |
64,197,389 | 64,197,596 | Difference between lists created with struct and list library c++ | I learned about lists in school.
struct Node {
Node* next;
int data;
};
I saw that there is a library with lists;
#include <list>
using namespace std;
int main() {
list <data_type> variable_name;
return 0;
}
Is there any difference between them ?
| The differences are that std::list
is a templated class, which can take any type as value, not only int
keeps the Node structure interned, and head and tail pointers will be managed by that class
it is implemented as a double-linked list, where the nodes have a pointer to the next and to the previous node, the mode ex... |
64,197,517 | 64,198,684 | Why is this friend method not found as expected? | When I have a small piece of code like this:
#include <iostream>
class A {
public:
friend inline std::ostream& operator<<(std::ostream& os, const A&);
};
inline std::ostream& operator<<(std::ostream& os, const A&) {
os << "Called\n";
return os;
}
class B {
public:
operator A() { return A(); }
};
int... | It comes down to how C++ generates candidate functions when performing overload resolution. It's trying to find candidates for operator<<(std::cout, b). This means it performs unqualified name lookup which includes performing argument-dependent lookup (ADL). Let's take a look at how that works.
For the first code snipp... |
64,197,525 | 64,214,845 | How to repeat rotation from Scipy in C ++ (Eigen or Qt) | I have a rotation done with Scipy, I would like to replicate it in C++ using the Qt library (Or Eigen as a last resort). How can this be done? I tried using QQuaternion::fromEulerAngles,but the output is completely different Euler angles. Can you tell me how can I repeat this composition of rotations?
from scipy.spatia... | You can use Eigen and easily create rotation objects from Euler angles (see https://eigen.tuxfamily.org/dox/group__TutorialGeometry.html#TutorialGeoEulerAngles). However, intrinsic/extrinsic systems have to be handled manually and requires a little bit more effort.
Using C++11 and development/master branch of Eigen:
#d... |
64,197,713 | 64,197,907 | Does the operand to a fold expression need to be parenthesized? | For the following program:
#include<iostream>
auto f(auto ...args)
{
(std::cout << 1 << ... << args);
}
int main()
{
f(0, 0, 0);
}
gcc prints 1000, but clang gives an error:
error: expression not permitted as operand of fold expression
(std::cout << 1 << ... << args);
~~~~~~~~~~^~~~
( ... | The grammar of a fold-expression ([expr.prim.fold]) is:
fold-expression:
( cast-expression fold-operator ... )
( ... fold-operator cast-expression )
( cast-expression fold-operator ... fold-operator cast-expression )
You are using the third form. What you want to be parsed as the first cast-expression is a shift-ex... |
64,197,926 | 64,198,004 | c++: atomic variable's value is invalid when saved in local variable | I defined atomic variable current inside some Obj-C file:
std::atomic<long long> current;
after that it was initiated:
current=4;
After that the variable became accessible by number of threads.
Some threads modified the variable like this:
current=(current.fetch_add(1))%4;
While other threads modified the variable i... | Atomic values are not synchronisation primitives. One of possible execution flows:
current.fetch_add(1); // T1
long long cs=current; // T2
if(current>=4){ // T1
current=0;
}
And
auto tmp = current.fetch_add(1); // T1
long long cs=current; // T2
current=tmp%4; // T1
The solution is in using mutexes or spin l... |
64,198,197 | 64,210,373 | How to prevent too aggressive text elide in QTableview? | I have an issue with text elide in Qt being too aggressive in a table, see picture.
The cell with the full figure 0.8888.... I've edited since the QTableWidget was shown, the others are are as the were when the QTableWidget was created. It seems like the elide is calculated on a lesser width that is actually the case.... | When everything just worked...
...the solution could have been as simple as disabling the elide in the QTableWidget and set directly an elided string as item's text like that:
tableWidget->setTextElideMode(Qt::ElideNone);
tableWidget->setItem(0, 0, new QTableWidgetItem(tableWidget->fontMetrics().elidedText("0.234823489... |
64,199,584 | 64,206,020 | Create a view by selecting elements of a range by their index | In range-v3, is there a more efficient way (less steps, cleaner, more expressive, more elegant, more performant, ...) to create a view by selecting elements of a range by arbitrary indexes of the range than using views::counted plus views::concat as in
auto v = std::vector<int> {6,7,8,9,10,11};
auto v1 = views::counted... | You can wrap up the calls to ranges::views::concat by putting the indices in a range, and calling ranges::views::for_each which maps each element to a function returning a range, then concatenates everything.
auto v = std::vector<int>{6,7,8,9,10,11};
auto i = std::vector<int>{1,3,4};
auto vFinal = i
| ranges::views... |
64,199,664 | 64,199,729 | Why C++ ranges "transform -> filter" calls transform twice for values that match the filter's predicate? | Consider the following code using the ranges library (from c++20)
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<int> inputs{1, 2, 3, 4, 5, 6};
auto square_it = [](auto i) {
std::cout << i << std::endl;
return i * 2; };
auto results = inputs | std::views:... |
why can't filter just pass the value to whoever is after it in the pipeline as soon as it finds a match?
Because in the iterator model, positioning and accessing are distinct operations. You position an iterator with ++; you access an iterator with *. These are two distinct expressions, which are evaluated at two dis... |
64,199,766 | 64,199,947 | How to reliably get a destructor to overwrite buffer without it being optimized out in c++ | I'm reviewing someone else's code and I See the in a destructor he is overwriting a buffer that is an int array inside the class. I thought maybe the compiler might optimize that out.
So I made a small program to test, and it does optimize the destructor out.
The only simple solution to this I found is to use attribute... | A bare metal way is to access it via volatile - that way it will not be optimized. A C way would be:
#include <cstddef>
void volatile_memset(volatile void *s, int c, size_t n) {
volatile unsigned char *m = reinterpret_cast<volatile unsigned char *>(s);
while (n--) {
*m++ = c;
}
}
int main() {
cha... |
64,199,974 | 64,200,097 | I'm having trouble understanding the syntax used in a piece of code | I've been looking at this for a while and I have some ideas on what this code could be doing, but I'm not sure if I correctly understand what the syntax of the code does.
The code iterates through a 2D array of unsigned chars, its meant to fill the array with 0's unless the spot in the array represents; the bottom, or ... | The code is using a 2-dimensional array that is allocated in memory as a 1-dimensional array. The expression y*fieldWidth + x is calculating a 1D array index from a pair of 2D indexes.
The array represents a rectangle. The code is assigning a 9 to the 1D array elements that represent the rectangle’s left, right, and b... |
64,199,979 | 64,200,470 | Program crashes after checking index at array | Please note: I am not sure if this fits here, if not, please move to the proper forum.
So I have a progrmam that tries to solve th Traveling Salesman Problem, TSP for short.
My code seems to run fine until I try to use 33810 cities, in which the program crashes after trying to access the position costs[69378120], it si... | If compiling in 32-bit size_t is 32 bit and then
1143116100*4
is larger than the largest 32-bit number hence int overrun.
Compiling in 64-bit
size_t siz = 1143116100;
std::vector<long long> big(siz);
std::cout << big.size() << ", " << big.max_size() << std::endl;
which prints
1143116100, 2305843009213693951
if I cha... |
64,200,773 | 64,202,236 | Recursion - what's the difference with this BST? | So I sometimes hiccup a bit on recursion. What ultimately is the difference logically between this:
Node *lca(Node *root, int v1,int v2) {
// Write your code here.
if (root == NULL)
{
return NULL;
}
// If both v1 and v2 are less than node->data, lies on the left
if (v1 < root->data && v... | The second one does NOT return what it found. it returns only NULL or root.
Let's try to check with following example:
3 <-- root
/ \
1 5
\ /
2 4
If you call lca(root, 1, 2), the first one returns pointer for a instance of Node.
Then you can use it as:
Node *found = lca(root, 1, 2);
int answer = found-... |
64,201,110 | 67,250,578 | Why don't you have to dereference a pointer using strcpy and strlen? | I've been trying to create my own string class, but I ran into a problem with the following code below:
String::String(const char *s) : str {nullptr}
{
if(s == nullptr)
{
str = new char[1];
*str = '\0';
}else{
str = new char[std::strlen(*s)+1];
strcpy(*str,*s);
}
}
What ... | Both strcpy and strlen have char * as parameters therefore you would not need to deference.
More information:
https://www.cplusplus.com/reference/cstring/strcpy/
https://www.cplusplus.com/reference/cstring/strlen/
|
64,201,175 | 64,203,667 | name 'cc_library' is not defined | Trying to build a C++ library in C++ and I've successfully confused myself
tools/vector_gen.bzl
def drake_cc_vector_gen_library(
name,
srcs = [],
deps = [],
**kwargs):
generated = cc_vector_gen(
name = name + "_codegen",
srcs = srcs,
include_prefix = "drak... | Inside a .bzl file the builtin definitions need to be qualified as native.cc_library
|
64,201,340 | 64,201,401 | Breaking out of an inner loop doesn't terminate the loops | The code is a four-character password generator. I have an if/else break system setup, but I can't figure out why it isn't working. The loop generates past the limit until it exhausts all options, which I'm having a hard time properly debugging. I'm very new to anything other than javascript and HTML, so any help would... | If you want to stop early, put this in a function and instead of break use return.
Remember that break only kicks out of the loop you're in, not all loops in the scope of the function.
Here's a reworked version with a more flexible input arrangement for the limit using argv:
#include <iostream>
void generatePasswords(... |
64,202,560 | 64,202,627 | How to read a specific amount of characters | I can get the characters from console with this code:
Displays 2 characters each time in a new line
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
char ch[3] = "";
ifstream file("example.txt");
while (file.read(ch, sizeof(ch)-1))
{
cout << ch << endl... | The following piece of code should work:
while (file) {
file.read(ch, sizeof(ch) - 1);
int number_read_chars = file.gcount();
// print chars here ...
}
By moving the read call into the loop, you'll be able to handle the last call, where too few characters are available. The gcount method will provide you w... |
64,203,072 | 64,208,008 | Is it OK to create Gtk::Builder from resource without implementing try/catch block? | Gtk::Builder::create_from_resource() throws the following exceptions when something goes wrong, for instance, the resource file wasn't found or there's a markup error in the Glade/UI file, etc
BuilderError
Glib::MarkupError
Gio::ResourceError
But I don't have any intention to handle those exceptions and do something ... | If you really don't want to handle the exception, the program will simply terminate abruptly if some exception is thrown.
I personally prefer to use global exception handling in these cases. In your case, all exceptions derive from std::exception or Gtk::BuilderError, so your handler could look like:
int main()
{
t... |
64,203,207 | 64,203,259 | I get segmentation fault in my C++ code while using std::cin | I was solving an algorithm problem (it's a problem about topology sort, and is in Korean http://boj.kr/1948) and while testing example input, I get segmentation fault in the middle of input
7
9
1 2 4
1 3 2
1 4 3
2 6 3
2 7 5
3 5 1
4 6 4
5 6 2 // here when I input 6, I get segmentation fault
6 7 5
1 7
I found out cin ca... | I think you should be used m instead of n.
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
edges[a].push_back(Edge(b, c));
}
|
64,203,626 | 64,204,745 | error when trying to compile with MinGW: cannot execute cc1plus | I did a clean install of MinGW on Windows 7 32bit with the GUI Installer, and installed
ming32-base-bin
mingw32-gcc-g++-bin
msys-base-bin
When trying to compile a simple "Hello World.cpp" from the cmd.exe i get the error:
C:\Users\Lorenzo\Desktop>g++ "Hello World.cpp" -o"Hello World.exe" -m32
g++: fatal error: canno... | Ok. I found the solution with some luck.
It is as simple as adding .exe to g++
> g++.exe *input file* -o*output.exe*
Don't Know if it's a bug or not, but this works for me.
|
64,203,996 | 64,204,786 | Call a function inside an unknown class that extends a known class | As the title says I have the following "base" class that user can extend:
class BaseScene
{
private:
bool sceneloop = false;
public:
virtual void Start();
virtual void EventHandler(SDL_Event event);
virtual void Update();
virtual void Draw();
void _toggleLoopMode() { sceneloop = !sceneloop; }
... | You take a reference or pointer to BaseScene, and call the methods on that. The caller passes an instance of their derived class.
class UsesScene {
BaseScene & scene;
public:
UsesScene(BaseScene & scene) : scene(scene) {}
void doStuff() { scene.Start(); scene.Update(); }
/*... etc*/
};
int main() {
... |
64,204,001 | 64,204,069 | How can C++ array pointers have different location, yet point to the same element? | I know the variable that holds the array stores the address of the array and any indexing on it performs a pointer arithmetic on the same. While I was brushing up my basics this is what I found.
int main() {
int equal;
char c[] = {'a', 'b', 'c'};
char* p = c;
char* q = &c[0];
cout<<*p<<endl;
c... | When you allocate an array, that variable you assign the array to points to the beginning of that array. The beginning of that array is an address in the memory.
The address of the beginning of an array is the address of its first element, so it doesn't matter whether you take char *x = arr; or char *y = &arr[0]; they ... |
64,204,451 | 64,204,656 | Cannot read .jpg binary data, buffer only has 4 bytes of data | My question almost exactly the same as this one which is unanswered. I am trying to read the binary data of a .jpg to send as an HTTP response on a simple web server using C++. The code for reading the data is below.
FILE *f = fopen(file.c_str(),"rb");
if(f){
fseek(f,0,SEEK_END);
int length = ftell(f);
fsee... |
When the request for the image is made and this code runs, fread()
returns 25253 bytes being read, which seems correct. However, when I
perform strlen(buffer) I get only 4.
Well there is your problem: You read binary data, not text, meaning that special characters like newline or the null character is not a something... |
64,204,573 | 64,204,691 | How to define preprocessor ifdef in .dll for Unity? | I have a .dll (unmanaged code) that I use in Unity. I need to add some functional in my .dll in order to build Unity project for Android devices.
So, I need to use preprocessor functionality such as if in my case
I tried to add it just for test in my .cpp file
DecoderStream::DecoderStream()
{
debug_in_unity("Decode... | From here and as the name already suggests
Pre-processors are a way of making text processing with your C program before they are actually compiled.
So if you don't compile your DLL already defining the according directives your code will basically simply result in compiling
DecoderStream::DecoderStream()
{
debug... |
64,205,700 | 64,206,458 | c++ allocator traits reference and const_reference missing and iterator to const iterator conversion | I am trying to implement a custom std compliant container class with an iterator.
To do so, i started to define the public type definitions to be used by traits for the container class as well as the iterator.
I want to make it c++17 compliant and try to not use c++20 removed features or c++17 deprecated.
This is what ... |
Do i have to define reference and const_reference types myself like i did in the example
Yes. The allocator doesn't know how your container is implemented, so it cannot know how to define those type aliases.
Another question would be how to define a const_iterator without duplicating my iterator.
With the magic of ... |
64,205,847 | 64,206,053 | How can i split text input to a list in C++? | I can split a given text into a list, but it doesn't work if I want to split a string given by the user.
void removeDupWord(string str)
{
string word = "";
for (auto x : str)
{
if (x == ' ')
{
cout << word << endl;
word = "";
}
else
{
... | Use std::getline instead of std::cin. With std::cin the input after whitespace will be discarded.
int main()
{
string ss;
std::getline(std::cin, ss);
//ss = "split this";
removeDupWord(ss);
}
Also, you should use C++ standard algorithm for such trivial task
void removeDupWord(const std::string& str)
... |
64,206,119 | 64,207,988 | Assimp linking error with mingw-w64 (WinBuilds) | I'm trying to compile project that uses assimp with mingw-w64 (x86_64-w64-mingw32-g++), and linker produces this errors:
render/model.o: In function `Model::loadModel(std::string)':
render/model.cpp:9: undefined reference to `Assimp::Importer::Importer()'
render/model.cpp:15: undefined reference to `Assimp::Importer::G... | I replaced WinBuild (g++ 4.8.0) with MSYS2 (g++ 10.2.0), and recompiled assimp with mingw. Now everything from project compiles fine.
|
64,206,448 | 64,207,194 | Idiomatic way to check std::chrono duration is less than 0 | I know I can do this
if (timeLeft.count() < 0)
But I wonder what is the best way since I could also do:
if (timeLeft<std::chrono::seconds(0)) // or milliseconds or nanonseconds...
note: I assume both checks are the same, but I am not a chrono expert.
edit:full example:
#include<chrono>
int main(){
const std::chro... | One of the ways to express this is by using std::chrono::duration literals (https://en.cppreference.com/w/cpp/chrono/duration). It's short and clean:
#include<chrono>
int main(){
using namespace std::chrono_literals;
const auto timeLeft = -5ns;
if(timeLeft<0s){
return 47;
}
}
|
64,206,587 | 64,207,612 | Ambiguous call to overloaded function in variadic template function | I am using a variadic template function where the function parameters isn't the templated types.
I got a compilation error:
Error C2668 '_TailHelper': ambiguous call to overloaded function
Here it is the code snippet.
template <typename HEAD>
void _TailHelper(int) {
std::cout << typeid(HEAD).name() << std::endl... | Both overloads match with single template argument, so you have to disable one. For example like that:
#include <iostream>
#include <typeinfo>
template <typename T>
void TailHelper(int) {
std::cout << typeid(T).name() << std::endl;
}
template <typename HEAD, typename ... TAILS>
typename std::enable_if<(sizeo... |
64,207,252 | 64,207,394 | Is there any way to determine stdin content size in bytes in c++? | I'm new to programming, and I'm trying to write a c++ program for Linux which would create a child process, and this child process would execute an external program. The output of this program should be redirected to the main program and saved into a string variable, preserving all the spaces and new lines. I don't kno... | The child process writes into the pipe but the parent doesn't read the pipe until the child process terminates. If the child writes more than the pipe buffer size it blocks waiting for the parent to read the pipe, but the parent is blocked waiting for the child to terminate leading to a deadlock.
To avoid that, the par... |
64,207,370 | 64,207,389 | Sum two vector and store stl algorithm | I have two vectors and I want to do something like
v2[i] = v1[i] +v2[i];
I have tried std::copy, but obviously that only do v2[i] = v1[i];
Is there any algorithm in the STL that performs this sum?
| You can use std:::transform
std::transform(v1.begin(), v1.end(), v2.begin(), v2.begin(), std::plus<>());
|
64,209,188 | 64,209,244 | Calling Another Function in a Recusive Function results in error. Why? | I've two functions fun() and fun2();
fun() calls itself while incrementing the global variable a=0 and terminates if a==5. But if I call another function called fun2() which basically returns and do nothing, then Build Error happens. Why?
I'm just experimenting with recursion and I got this error.
#include<iostream>
us... | You would get similar error with
void fun() {
fun2();
}
void fun2() {}
int main() {
fun();
}
The error is not related to the recursion. You need to delcare a function before you can call it:
#include<iostream>
void fun2(); // declaration
void fun() {
// ...
fun2();
}
void fun2() { } // defin... |
64,209,537 | 64,210,155 | Receive data from specific address using QUdpSocket | I'm trying to do a client-to-client communication over UDP. I'm using QUdpSocket to do that.
The IP of my first client is 127.0.0.2 and the IP of the second client is 127.0.0.3.
In my first client, I want to send data, so I'm doing this:
socket = new QUdpSocket(this);
socket->bind(QHostAddress("127.0.0.2"), (quint16)ac... | The readDatagram method is non-blocking: you can only usefully call it if hasPendingDatagrams() is true. This flag is in turn governed by running the Qt event loop.
You have two options:
Use socket->waitForReadyRead() to block your program for a set time (30s);
Or put the above code in a slot handler connected to the ... |
64,209,706 | 64,209,795 | Function specialization with default arguments can't be called because too few arguments | I have this code
#include <iostream>
#include <type_traits>
enum class Color: char { Red = 'r', Yellow = 'y', Green = 'g' };
template<Color color>
auto say_my_name(unsigned times = 1) {
for (unsigned i = 0; i < times; i++) {
std::cout << static_cast<std::underlying_type_t<Color>>(color) << ' ';
}
... | Default arguments are substituted at the call site. They are not part of a functions type. Hence you need "something" to enable the default argument for say_red. You can use a lambda:
#include <iostream>
#include <type_traits>
enum class Color: char { Red = 'r', Yellow = 'y', Green = 'g' };
template<Color color>
auto... |
64,209,910 | 64,215,783 | How to construct a convenient iterator over blocks of Matrix using Eigen | I want to construct a "block-columnwise" iterator which runs over all possible blocks of of Dense Matrix with Eigen.
#include <iostream>
#include <Eigen/Dense>
int main() {
Eigen::MatrixXd A(4,4);
A << 1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16;
for (Eigen::Index k=0; k< ? ; ++k) {
... | I couldn't find anything in the Eigen documentation, but a simple forward iterator doesn't need too much:
equality operators
increment operators
dereference operator
This is what I came up with
template <Eigen::Index RowSize, Eigen::Index ColSize>
struct EigenBlockIt {
using Self = EigenBlockIt<RowSize, ColSize>;... |
64,210,127 | 64,210,161 | c++ std::intializer_list and constructor | Im trying to create a function that works with 'groups' of vectors.
Let the groups be named A, B, C, ... there may be any number of groups. Each group has one 'main' vector, eg. v_A of type int and a variable number of associated vectors, eg. v_A1, v_A2, ... all of type float.
I wish to create a function groupwise that... | You just need another pair of braces in the function call to indicate the outermost initializer_list, like this:
groupwise({ // here
{ v_A, { v_A1, v_A2 } },
{ v_B, { v_B1, v_B2, v_B3} },
{ v_C, { v_C1 } }
}); // and here
Here's a demo.
|
64,210,146 | 64,210,340 | How to make getline play nice with ios::exceptions? | I am trying to use an ifstream that I need to be able to loop through using getline but would like to have throw exceptions using ios::exceptions:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream f;
f.exceptions( std::ifstream::failbit | std::ifstream::badbit );
try {
... | You turn on throwing exceptions on failbit and later when std::getline(f, l) fails to extract any characters it will set failbit which is triggering the exception.
|
64,210,645 | 64,213,331 | Identity element for std::min/float monoid | In this (very interesting) talk the speaker poses a question:
What is the e value for the float/std::min monoid.
In other words: what is the identity element for the monoid composed of standard C++ floats and std::min operation? The speaker says that the answer is "interesting".
I think that std::numeric_limits<float... | It's obviously true that min on the affinely-extended reals (ie, including +/-inf but excluding NaN) is a monoid.
However, the result of comparing anything to NaN is not false, but "unordered". This implies that < is only a partial order on float, and std::min<float> (which is defined in terms of <) is therefore not a ... |
64,210,847 | 64,210,902 | Calling C++ function with default parameters from Python | I have exported this simple function from an DLL (Am working in MSVC2015, Windows 10, x64) :
// Main.h
#define DLL_SEMANTICS __declspec (dllexport)
extern "C"
{
DLL_SEMANTICS int CheckVal(const int x, const int y = 1);
}
code:
// Main.cpp
int CheckVal(const int x, const int y)
{ cout << y << endl; return... | Default parameters are a nicety of C++. You need to pass two arguments if you're calling outside C++.
|
64,211,022 | 64,211,202 | C++ DIR * dir need to use to only one working at a time | Hello I am programming using code block using C++, All I want is to use opendir twice and it is only opening once both chunks of codes are working but only the top one works and not the bottom one.
Please some one help me only one dir is working at a time:
I want one DIR to work and give me values to drill down in to a... | You are using f and j uninitialized. For f this probably works by accident, as the stack is still relatively fresh.
However, by the time you start using j the stack has been thoroughly polluted and your uninitialized use returns random stack garbage.
Any half-decent compiler should yell at you if you do this, so please... |
64,211,456 | 64,211,694 | Access and insert a map of map of pair and int in C++ | For example I've got a map like this:
std::map<std::map<pair<int, int>, pair<int, int> >, int> mp;
How do I insert/access element into/in that map?
For inserting I've tried with
// using nested map
std::map<pair<int, int>, pair<int, int> > mp2;
mp2.insert(make_pair(1,2), make_pair(3,4));
mp.insert(make_pair(mp2, 1)... | Please reconsider your choice of data structure. Using std::map as a key to std::map will incur large overheads due to necessity of creating temporary keys to compare (when accessing outer map elements). It's highly unlikely that it will help you get through the time limit of yours.
std::map::insert requires a ready st... |
64,211,652 | 64,212,026 | std::fmod abysmal double precision | fmod(1001.0, 0.0001) is giving 0.00009999999995, which seems like a very low precision (10-5), given the expected result of 0.
According to cppreference, fmod() is implementable using remainder(), but remainder(1001.0, 0.0001) gives -4.796965775988316e-14 (still far from double precision, but much better than 10-5).
Wh... | If we modify your program to:
#include <cmath>
#include <iomanip>
#include <iostream>
int main() {
double a = 1001.0, b = 0.0001;
std::cout << std::setprecision(32) << std::left;
std::cout << std::setw(16) << "a:" << a << "\n";
std::cout << std::setw(16) << "b:" << b << "\n";
std::cout << std::se... |
64,211,956 | 64,212,475 | Can I initialize a std::vector<bool> from uint8_t (or std::byte) range so that every bit in input is treated as a boolean? | I know that std::vector<bool> is bad, but I have a really nice use case for it.
I would like to do something like this:
uint8_t data [] = {7,32};
std::vector<bool> vb/*...*/ ;
// now vb is size of 8 vector with this values:
// false, false, false, false, false, true, true, true, (7)
// false, false, true, false, ... | std::vector<bool> is a poor choice here, because you are thinking about it in terms of its implementation rather than its behavior.... just avoid vector<bool>.
Use a boost::dynamic_bitset instead. Anecdotally I have personally found it to be far more performant anyway:
std::array<std::uint8_t, 2> data {7,32};
boost::dy... |
64,212,450 | 64,220,596 | Iterate over types of tuple in C++ | I want to iterate over types of a tuple, not its elements.
Imagine you have a generic, base-class interface Controller and you want to have a vector of pointers (I use raw pointer instead of smart, for readability): std::vector<Controller*> ctrls;
Now you want to add many implementations of Controller interface to this... | You can use std::tuple_size and std::tuple_element to get the type of every tuple element (this will put it in reverse order, but with a little modification you can revert the order):
#include <iostream>
#include <variant>
#include <vector>
using namespace std;
using Controllers = tuple<int, char, float>;
using Contr... |
64,212,614 | 66,315,352 | Make clang-format order includes in a case-insensitive way | I'm trying to configure .clang-format. My intention is for it to keep my include groups as they are in the code, but sort them alphabetically. I managed to get close to what I wanted with IncludeBlocks: Preserve, but it sorts includes in each block in a case sensitive way:
This is what I get after applying my format
#i... | This has been added as of LLVM 12 (which will be released Clang 13? Somewhat confusing); citing the in-progress release notes of LLVM 12/Clang 13 [emphasis mine]:
clang-format
Option SortIncludes has been updated from a bool to an enum with
backwards compatibility. In addition to the previous true/false
states (now Ca... |
64,212,808 | 64,213,066 | Divide and conquer sum algorithm | i was looking for some D&C algorithms and came out founding this one
int sumArray(int anArray[], int size)
{
//base case
if (size == 0)
{
return 0;
}
else if (size == 1)
{
return anArray[0];
}
//divide and conquer
int mid = size / 2;
int rsize = size - mid;
i... | Because the function sumArray calls itself recursively,
int lsum = sumArray(anArray, mid);
int rsum = sumArray(anArray + mid, rsize);
the base case is needed regardless of the size of the array. Otherwise Fnction can never exit the loop of calling itself!
And remember that base on the fact that one of mid and ... |
64,212,936 | 64,213,016 | How to force specific type in C++ preprocessor macro? | I'm trying to generate a static variable via a preprocessor macro for logging purposes. The variable serves as a counter how often a specific message as been sent already. in order to make this thread-safe I wanted to switch from using an int counter to std::atomic<int> - which works fine on most compilers:
#define GEN... | You should change your macro to be
#define GENERATE_LOG_VAR(Count) static std::atomic<int> local___FUNCTION__##Count##__LINE__(Count)
This will avoid constructing a copy, or trying to construct a copy, or whatever the precise standardese says in this situation.
|
64,213,027 | 64,213,250 | 3D Vector addition with Template and Overloading (+operator and += operator) | using namespace std;
template <typename A>
class vector3d_add
{
public:
vector3d_add(A x, A y, A z);
virtual ~vector3d_add();
void setX(A x);
void setY(A y);
void setZ(A z);
void display();
A getX();
A getY(... | There are too many errors in your code.
First never use using namespace std;
Second why the return types of the operators are A. they should be vector3d_add<A>!
Here is a working code:
template <typename A>
class vector3d_add
{
public:
vector3d_add(A x, A y, A z);
virtual ~vector3d_add();
void setX(A x);
... |
64,213,156 | 64,213,197 | initializing a vector from an initializer_list generates an unclear compilation error | This code compiles if the std::copy is commented out, and the atc initializer is uncommented.
class MyClass {
MyClass( OtherClass* poc_in, std::initializer_list<ThirdClass> iltc) :
poc( poc_in)
//, atc(iltc)
{
std::copy( iltc.begin(), iltc.end(), atc );
}
OtherClass* poc;
std::vector<ThirdClass> ... | This has nothing to do with initialiser lists.
You're using std::copy wrong.
That third argument should be an output iterator, not a vector.
Try using std::back_inserter:
std::copy( iltc.begin(), iltc.end(), std::back_inserter(atc) );
The compilation error is admittedly a little esoteric, but it's saying that the comp... |
64,213,225 | 64,562,473 | How to programmatically stop editing QTreeWidget in Qt? | I have a QTreeWidget and two buttons "+" and "-". When I press "+" I want to add new item to QTreeWidget and I want that item to be in edit mode. I managed to do that with following code (it gets called every time "+" is pressed):
// QTreeWidgetItem* lastItem = getLastItem();
// if (lastItem) { widget->closePersistentE... | Ok, it looks like this is a bug in Qt for macOS. Workaround that I did is following:
QTreeWidgetItem* lastItem = getLastTreeWidgetItem(widget);
if (lastItem) {
widget->setDisabled(true);
widget->setDisabled(false);
}
conversation->setFlags(conversation->flags() | Qt::ItemIsEditable);
getLastTreeWidget() is my ... |
64,213,528 | 64,213,673 | C++ How to correctly cap FPS (Using GLFW) | So I have been trying to limit my fps to 60:
//Those are members inside the Display class
double tracker = glfwGetTime();
const float frameCap = 1 / 60.0f;
void Display::present() {
glfwSwapBuffers( _window );
//Getting the time between each call
double now = glfwGetTime( );
double frameTime=now - tr... | For the first call of present your double frameTime=glfwGetTime( ) - tracker;, sets frameTime to the difference between the current time (glfwGetTime() and the inital value of tracker you set with glfwGetTime().
In the next line, you set tracker=frameTime; (frameTime is not the time but the difference here.)
For the ne... |
64,213,736 | 64,216,436 | converting string to char * fails (codecvt) | I have the following code:
std::wstring my_string = L"foo";
std::wstring_convert<std::codecvt_utf8<wchar_t> > my_conv;
const char *chars = my_conv.to_bytes( my_string ).c_str();
The conversion return an empty pointer (Not NULL, just "").
Is to_bytes returning a temporary pointer?
How do I write this code properly?
| std::wstring_convert::to_bytes() does not return a temporary pointer. It returns a temporary std::string object. You are saving a pointer to the temporary's data, and then the temporary goes out of scope and gets destroyed afterwards, leaving you with a dangling pointer to invalid memory.
Save the std::string itself,... |
64,213,817 | 64,213,871 | Is there a difference when instantiating an object as follows | class Entity
{
};
//Entity e(); This was a mistake
Entity e;
Entity e1 = Entity();
The second method looks like an anonymous object is created which in turn
initializes e1,but i dont think that is what's happening.
| Before C++17
Entity e1 = Entity();
You're right about this one. A temporary, default-constructed Entity is created, then used to copy-initialise e1.
Since C++17
Despite appearances, that no longer creates a temporary, it only looks like it does. The semantics of the line are now that there is simply a declaration of a... |
64,214,050 | 64,214,118 | (C++) Problem with if statement ,simple == condition | I have something which outputs all the factors for an integer using a fixed loop.
in this case, int_end_int_ = 4
and middle_x_coefficient = 4
for (int i = 1; i <= int_end_int_; i++)
{
if (int_end_int_ % i == 0) // This gets the factors
{
//here
}
}
i have that inside the if... | You converted the character end_int_ to the integer int_end_int_, but you didn't convert the character middle_x_coefficient to an integer. Convert and use converted integer just as you did for end_int_.
Instead of using magic number 48, using character literal '0' is better.
|
64,214,076 | 64,214,180 | why passing string_view by value is faster than const reference | I checked this question, and most answers say that I should pass it by value despite it's clearly passing more data (since by value you pass 8 bytes while by reference only 4 bytes, in 32bit system sizeof(string_view) > sizeof(string_view*))
is that still relevant in C++20/17 ? and can someone explains why exactly ?
| Indirection through a reference (as well as a pointer) has a cost. That cost can be more than the cost of copying a few bytes. As in most cases, you need to verify through measurement whether that is true for your use case / target system. Note that if the function is expanded inline, then there is unlikely to be any d... |
64,214,283 | 64,214,405 | Is there a way to have two getters with different accesses and use in for loop one of them? | class Foo {
// friend Bar;
public: const std::list<int*>& numbs () const { // (1)
return mNumbs;
}
protected: std::list<int*>& numbs () { // (2)
return mNumbs;
}
private: std::list<int*> mNumbs;
};
int main () {
Foo foo;
for (const auto& e : foo.numbs()) { // (3)
... | Method 1 is not a better match since foo is not a constant object. It will only be called if your object is constant.
If your callers choose to mark the object as a const, only then the error will go away. For instance, this will work as expected:
const Foo foo;
for (const auto& e : foo.numbs()) { // (3)
// some wo... |
64,214,490 | 64,215,441 | Need help understanding this line in an FFT algorithm | In my program I have a function that performs the fast Fourier transform. I know there are very good implementations freely available, but this is a learning thing so I don't want to use those. I ended up finding this comment with the following implementation (it originated from the Italian entry for the FFT):
void tra... |
But there's one thing I don't get: this is a length-N DFT, and yet only N/2 twiddle factors are ever calculated. Shouldn't the array be of length N, and the modulo should be by N?
The twiddle factors are equally spaced points on the unit circle, and there is an even number of points because N is a power-of-two. After... |
64,215,114 | 64,215,284 | C++, strings and ints from command line using cin with unknown input size | I got this code that I'm working with. I need to take in inputs from command line and work with that input.
For example, I could have the input:
a 3 b 2 b 1 a 1 a 4 b 2
which will give the output:
1 3 4 1 2 2
My problem is that I can't use another input than of size 6 (or 12).
If I use the input
a 3 a 2 a 3
I will g... | You can use a combination of std::getline with std::stringstream to parse the input, this allows you to use a variable size input without having to worry about it:
Live demo
#include <sstream>
//...
std::string my_vec_str;
char type; //to store type 'a' or 'b'
int value; //to store int value
std::vector<int> vect_a;... |
64,215,484 | 64,221,593 | c++ read access violation with extended classes | As the title says when I run my program, visual studio, give me that error. The class that produce that error is the following:
class UsesScene {
BaseScene & scene;
public:
UsesScene(BaseScene& scene) : scene(scene) {}
void Start() { scene.Start(); }
void EventHandler(SDL_Event ev) { scene.EventHandler... | So, after a few hours of coding, thanks to Remy Lebeau, I've finally resolved this issue.
First I've changed the regScene() method and now looks like this:
void GameManager::regScene(UsersScene *scene) {
if (SceneManager::_display == NULL)
_display = scene;
else
_buffer = scene;
}
And then I pa... |
64,215,535 | 64,248,276 | Event System and Move Semantics in C++ | I have recently been messing around with event systems in C++ like boost::signals2 and similar libraries. They all seem to have one limitation in common: they don't really work with move semantics.
If you connect your signal to a slot that is a member of an object it refers to the current memory address of that object ... | The thing is that slot's location in memory doesn't depend on instances data. Member function exists in memory as single definition for all instances of the class and doesn't change its location. When you call the function for specific object (like object->member_func()), "this" pointer is implicitly passed among with ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.