question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
65,359,588 | 65,360,197 | Function accepting functions as parameter with templated types | im fairly new to programming and C++. I have a function that i want to accept function-pointers with templated values as argument. Here is what i mean...
i have this function:
template<typename... ColumnTypes, typename... ParameterTypes>
void query(std::function<void(bool success, ozo::rows_of<ColumnTypes...>& resul... | Template deduction only works on the exact type that you pass in, so if you pass in a function pointer the template can't deduce what kind of std::function to convert that function pointer to.
Make the callable a template parameter, instead of using std::function.
template<typename Callable, typename... ParameterTypes>... |
65,359,706 | 65,363,113 | Using multiple versions of same DLL | I've run into a situation where an application has multiple (incompatible) versions of one or more dll.
app.exe
a.dll // v3.0
...
plugins/foo/foo.dll
plugins/foo/a.dll // v4.0
plugins/foo/...
In this example, app.exe depends on a.dll v3.0 and foo.dll depends on a.dll v4.0. Due to the search order of ... | What you are looking for is an Activation Context:
Activation contexts are data structures in memory containing information that the system can use to redirect an application to load a particular DLL version, COM object instance, or custom window version. One section of the activation context may contain DLL redirecti... |
65,359,775 | 65,360,054 | How to build 3x3 translation matrix in c++ | I am new to c++. I am looking to create a 3x3 matrix that looks like this:
I want theta to be a parameter that I can define outside of the matrix and plug it in when doing matrix multiplication. How do I do this?
If it were python, I'd want something like this:
define matrix(theta):
row1 = np.array([cos(theta), -s... | You don't necessarily need to define a dedicated class if you want to go a bit quick and dirty:
#include <iostream>
#include <cmath>
#include <array>
using Mat3x3 = std::array<std::array<double, 3>, 3>;
auto rotationMatrix(double theta)
{
Mat3x3 mat
{ std::array{ cos(theta), -sin(theta), 0. },
std::array... |
65,359,820 | 65,360,029 | Arduino restarts after serial input from Raspberry Pi | I have this code running on the arduino:
#include <SoftwareSerial.h>
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// pins!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
const int delayTime=10;
const int pin_yes_gate=3;
const int pin_no_gate=5;
int switchVal =0;
void setup()
{
Serial.begin(9600); // Initialize serial port t... | Just solved it, apparently the problem is the
Serial.print("I received: ");
Serial.print(string);
Serial.print("\n");
It errors out if serial is not read. So either removing this, or as in my case I can't change anything on the arduino side run this command on raspi boot tail -f /dev/ttyACM0 & which opens ... |
65,360,278 | 65,360,439 | Copy current executable to another path C++ (Windows only) | I forgot how to program in C++, I want my exutable to copy itself to another path. I found a code that do what I want to do but there are conversion error that I don't know how to resolve :
void Victim::replicate()
{
char filename[ MAX_PATH ];
char newLocation[]="C:\\Users\\myUsername\\Desktop\\";
BOOL stats=0;
... | It seems your project is set to use the W versions of the API functions by default.
You override that by calling the A (Ansi) version of GetModuleFileName. Don't - or do, but then you also need to call CopyFileA.
Forcing Ansi version usage:
void Victim::replicate()
{
char filename[ MAX_PATH ];
char newLocation[] = ... |
65,360,332 | 65,360,461 | Understanding when checks happen in () and {} initization through class constructors | From what I understand, {} is a way to initialize variables with some "safety" advantages over other methods, such as forbidding narrowing:
int some_int_a = 1.2; // narrows
int some_int_b (1.2); // narrows
int some_int_c {1.2}; // does NOT compile, cannot narrow
So far so good. The thing I recently discovered, that... | What happens here is that the constructor:
ExClass(int i=0): i{i}
Takes an int parameter, and narrowing here:
ExClass ex_a (2.3);
is fine. Once you are in the contructor, i is an int (the parameter, not the member). Hence there is no narrowing in i{i} (it is int to int). You do get the error when you change your cons... |
65,360,508 | 65,360,781 | How this 'for' loop for reverse stack affecting front stack?(Balanced brackets problem using stacks) | I need to separate a sequence of brackets to check whether it is balanced or not . My approach is to divide the sequence into two equal halves and push them into separate stacks.
The problem is occurring when I try to push the 2nd half of the sequence into reverse stack. It is affecting the first stack . I have no ide... | Your arrays have 0 items in them, so when you do front_stack[0], front_stack[1], ... you're overwriting some other variable.
If you want to store data in arrays, you need to make them actually have some items in them e.g. char front_stack[100], char rev_stack[100]
By the way, you don't need ={} in this program.
|
65,360,812 | 65,360,840 | jump to case label crosses initialization of 'std::unique_lock<std::mutex>' | I am learning thread synchronization between two threads using condition variable but getting this compilation error:
CVV.cpp:21:3: error: jump to case label [-fpermissive]
default:
^
CVV.cpp:14:33: error: crosses initialization of ‘std::unique_lock<std::mutex> ul’
std::unique_lock<std::mutex> ul(m, std::de... | switch(opn_type) {
case 1: {
std::unique_lock<std::mutex> ul(m);
// do processing and add to queue
cv.notify_one();
ul.unlock();
} break;
default:
break;
}
case labels don't end variable lifetime, so ul exists and is destroyed after default: but o... |
65,361,362 | 65,362,425 | Policy Based Design - Conditional use of Base class (functions) | In the hello world example of policy based design from wikipedia we have this very nice way of defining the implementation (policy-) specific member functions via using directives:
template <typename OutputPolicy, typename LanguagePolicy>
class HelloWorld : private OutputPolicy, private LanguagePolicy {
public:
// Beha... | If it can be set design decision in the project, that every policy derives from default-policy - like:
class SomeLangaugePolicy : public DefaultLanguagePolicy { ... };
Then there is nothing to be changed in class HelloWorld - I mean the first version of this class.
Otherwise - use tools from <type_traits>:
Detecting ... |
65,361,382 | 65,398,009 | How to access values of elements of std::set in gdb? | I was implementing a set of arrays in C++, and wanted to track the values in it using gdb so I created a breakpoint after the data is initialized. The gdb in Vscode is fired up, but all I see for the set is a myriad of pointers. I see no values to follow. I know that sets are implemented using red-black trees so the po... | Finally I found my answer after loads of google searches. The answer was pretty-printers, I'm on windows so I had to install MinGW but mine didn't have the ability to support python scripts and also were lacking libstdc++-v3 library.
Download MinGW which supports python scripts and has the libstdc++-v3 library
Delete... |
65,361,845 | 65,361,977 | class methods not recognized by class c++ Stack | This class is a stack and I'm trying to get the user to call functions related to the stack. However, no changes seem to be made, since when calling the display function, my entire stack is filled with zeros. This is after pushing values onto the stack.
#include <iostream>
using namespace std;
class Stack {
pub... | You never actually put anything in the stack:
void push(int val) {
if (isFull()) {
cout <<"stack overflow" << endl;
}
else {
top++;
array[top] == val; // Change == to =
}
}
Currently, you are m... |
65,362,027 | 65,362,234 | Range condition using UINT32_MAX | I need to check if a int64_t is in the range -UINT32_MAX <= x <= UINT32_max
I've tried like so:
if(x >= -(UINT32_MAX) && x <= UINT32_MAX)
But it seems that -(UINT32_MAX) overflows to 1
Any ideas?
| In -(UINT32_MAX), the negation is performed in the type uint32_t (and the parentheses have no effect). Negating within the uint32_t type wraps modulo 232, so it produces 1. To truly negate UINT32_MAX, do it in a wider type, as in - (int64_t) UINT32_MAX.
In x >= - (int64_t) UINT32_MAX && x <= UINT32_MAX, the usual arith... |
65,362,205 | 65,385,834 | How to NOT target any .NET Framework in Visual Studio 2010 for a C++ application | Is it possible to create a new Win32 C++ project in VS2010 that wouldn't target a .NET Framework? Visual Studio seems to refuse to create a project unless at least one .NET Framework version is selected as a target. It also refuses to load a project if .NET is not installed on a computer, even if SLN / VCXPROJ files do... | [tl;dr] Visual Studio 2010 has the .NET Framework 4.0 as a prerequisite. The VS 2010 setup installs it if necessary, and the IDE will not function correctly if the .NET components are manually uninstalled afterwards. Unmanaged C++ applications can still be built outside the IDE without any .NET installed, and the res... |
65,362,227 | 65,362,339 | Parsing date and time string into a number to compare C++ | My application receives a date and time string. I need to be able to parse this string and compare it to the current time in seconds.
I am parsing this as below into a struct tm t to get the year, month, day, hour, minute, and second separately.
std::string timestr = "2020-12-18T16:40:07";
struct tm t = {0};
... | You want C++ parsing:
https://en.cppreference.com/w/cpp/io/manip/get_time
std::stringstream timestr = "2020-12-18T16:40:07";
struct tm t = {0};
timestr >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S");
I should note there is a bug in your code as: tm_year is not the same as year as we know it. This is the number of ... |
65,362,620 | 65,362,742 | How to compare two objects? | I'm trying to compare two objects but I keep on getting the error:
binary '==': 'robot' does not define this operator or a conversion to a type acceptable to the predefined operator
This is my cpp file:
void move(const robot r, vector<robot>& vec_r) {
// 0 = north, 1 = east, 2 = south, 3 = west
int x = r.xpo... | For your own class types you can define operators for it, where operator== is one of them.
class robot {
// ... all your other stuff
public:
bool operator==(const robot& other) const {
return _id == other._id; // Use whatever logic makes sense for you here
}
};
|
65,362,699 | 65,362,957 | can we use cin>> in member functions in a class in C++? | I'm trying to initialize a class matrix using a member function like thiis
class mat{
int r,c;
float **p;
public:
mat(){}
mat(int,int);
void initialize();
};
mat :: mat (int r, int c){ //check for float and int if error occurs
p=new float*[r];
for(int i=0; i<r; ++i){
p[... | You need to initialize r and c like this:
mat :: mat (int r, int c) :r(r), c(c){
p=new float*[r];
for(int i=0; i<r; ++i){
p[i]=new float[c];
}
}
and don't forget to add the destructor.
|
65,363,107 | 65,363,290 | Three-way comparison operator with inconsistent ordering deduction | Some time ago I defined my first three-way comparison operator. It compared a single type and replaced multiple conventional operators. Great feature. Then I tried to implement a similar operator for comparing two variants by delegation:
auto operator <=> (const QVariant& l, const QVariant& r)
{
switch (l.type())... | The types of the operator<=> for int and double differ but they should have a common type. You probably want to leverage the compiler in automatically finding the proper type. You could use std::common_type to do but that would be quite ugly. It is easier to just leverage what std::common_type type does under the (when... |
65,363,283 | 65,365,322 | sf::Event::Keypressed not working inside of poll event loop -SFML-2.5.1 | #include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
int main(){
sf::RenderWindow window(sf::VideoMode(640, 480), "Window");
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
... | Add an << std::flush; after your couts and you will see the key codes. Otherwise they will not be printed until SFML main loop is left (not when interrupted but when closed gracefully using x button).
|
65,363,684 | 65,363,725 | Why is there an `equivalent` value for std::strong_ordering? | The valid values of std::strong_ordering are less, equal, equivalent, and greater. However, it appears that strong_ordering::equivalent and strong_ordering::equal are equal (i.e., interchangeable), since in both cases the exposition-only value field equals zero, and there is no other state for the exposition-only const... | This allows C::equivalent to be defined for all comparison categories C. There used to be five of them, all of which had this, now just the three.
If you need something like that, it helps to have it. And it costs nothing to provide, so... there it is.
|
65,364,243 | 65,364,345 | Values keep resetting when changing an object of a vector of objects | I created two classes. The first class take in a string as a param which it sets to the name of the person.
The second class is where I create an object of a vector which holds objects. I need this object to make additional functions later on in the code. (this code is an example of the problems I have with my main cod... | You return copy instead of reference,
use
const std::vector<person>& getRobots() const { return _peeps; }
std::vector<person>& getRobots() { return _peeps; }
|
65,364,718 | 65,364,767 | Why lock_guard not get destructed after another function is called? | In my codebase I have two functions which looks something like this:
void inside() {
lock_guard<mutex> lock(LOCK);
cout << "Finished inside" << endl;
}
void outside() {
lock_guard<mutex> lock(LOCK);
inside();
cout << "Finished outside" << endl;
}
This causes a deadlock in my codebase, which I find weird bec... |
I was under the impression that lock_guard gets destructed when it goes out of scope.
It does. The problem is, you are creating 2 separate lock_guard objects in 2 separate scopes. In outside(), you create one object that stays in scope while inside() is running. inside() then creates its own object, which goes out... |
65,364,958 | 65,365,049 | Why does ((*i)->getFirstName()) work, as opposed to *i->getFirstName() or Employee[*i]getFirstName()? | Why does this line of code work in this scenario?
cout << ((*i)->getFirstName());
The context
class Employee{
private:
string FirstName;
public:
Employee(string FirstName);
void setFirstName(string FName) {
FirstName = FName;
}
string getFirstName(){
return FirstName;
}
} //End of Class
... | i is an iterator object, not a numerical index, so both Employee[i] and Employee[*i] are wrong (as you've seen).
Regarding *i->getFirstName() vs (*i)->getFirstName(), the -> operator has a higher precedence than the * operator. So *i->getFirstName() would be interpreted as if you had written *(i->getFirstName()), ie “e... |
65,365,015 | 65,365,126 | Printing out values in loops, values is not being printed out than a certain number | I want to make a program that Multiplies every other digit by 2, starting with the number’s second-to-last digit, and then add those products’ digits together. For example, lets take an integer 4003600000000014
Okay, let’s multiply each of the underlined digits by 2:
1•2 + 0•2 + 0•2 + 0•2 + 0•2 + 6•2 + 0•2 + 4•2
That g... | Your problem is using the wrong data type. First, floating-point arithmetic leads to rounding errors. Second, float can only hold about 7 significant decimal places, and even double is not large enough for your example (4003600000000014).
What you should use instead is std::vector<int> and store individual digits of th... |
65,365,023 | 65,365,074 | Private inheritance and virtual function | Could someone please help me understand how virtual function works here even though the call is not via pointer or a reference?
#include <iostream>
class Base {
public:
virtual void f() { std::cout << "Base::f()" << std::endl; }
void g() { f(); }
};
class Derived : private Base {
public:
void f() { std::cout <... | The call to d.h() is not being made by pointer or reference, yes.
But the call to f() IS being made via a pointer - an implicit this pointer.
Base::f() is virtual and overridden by Derived::f(), so any call made to f() via a Base* pointer (or Base& reference) will dispatch polymorphically to Derived::f() when referring... |
65,365,116 | 65,365,184 | Does `#pragma GCC system_header` in a header file extend into another source or header file that includes it? | I need to disable all warnings inside a certain header file, and only that file only.
The version of my compiler is g++-4.8. I have to use that compiler.
I looked up in the documentation of that compiler:
g++-4.8 documentation support for System-Headers
It is written:
All warnings, other than those generated by #warni... | It's just a reaffirmation of the main rule:
There is also a directive, #pragma GCC system_header, which tells GCC to consider the rest of the current include file a system header
That's it. Not other headers, not the file where you wrote #include.
Just that file.
|
65,365,591 | 65,366,066 | Object going out of scope and destructor called causing the pointer following that object's address to have unreadable memory on each attribute | So I have a vector of pointers to Movie objects in a class called Movies and the Movies class has a member method add() which you pass in the following arguments: std::string name, std::string rating, size_t watched_times. Then that add() method constructs a Movie object with all the arguments passed in, then I push_ba... | As has been said in the comments, the issue is with
Movie to_add{name, rating, times_watched};
movies.push_back(&to_add);
After these lines, the Movie object goes out of scope, causing the to_add variable to be destroyed. The pointer you pushed onto the movies variable is no longer valid. Using it is then und... |
65,365,635 | 65,365,702 | Error with big number of characters while making a letter pyramid | The task is to make a letter pyramid. I have done it but its behaviour goes very strange after I pass a certain number of characters that were inputed. Looking forward to an answer.
string input{};
string reverseString{};
getline(cin,input);
for(int j = input.length()-1;j>=0;j--){
reverseString += input.at(j)... | string spaces(" ",numberOfSpaces);
This doesn't do what you think it does.
This constructor takes an array and a count.
It copies count (in this case numberOfSpaces) items from the passed in array.
The passed in array has length 1 (technically 2 with the null terminator), and so anything > 2 will cause undefined behavi... |
65,365,647 | 65,365,732 | c++, linux - mmap() permission denied on file created by program, created file has all permissions open | The permission keeps being denied, but as far as I can tell, my permissions are wide open.
//snip
int outfile = creat("outFile.txt", O_RDWR | O_CREAT | S_IRWXU | S_IRWXG | S_IRWXO);
if (outfile < 0)
{
cout << "\n" << "output file cannot be opened, error" << "\n";
cout << strerror(errno) << "\n";
exit(1);
}
... | int outfile = creat("outFile.txt", O_RDWR | O_CREAT | S_IRWXU | S_IRWXG | S_IRWXO);
Two problems here:
creat creates a file in write-only mode, and it's second parameter is a mode_t mask. Passing O_flags here, slapped together with S_ mode bits, results in nonsensical garbage.
The parameters to the mmap call require... |
65,366,200 | 65,367,271 | How does Line Trace / Raycasting works in game engines to test intersections? | I've been in game development for a while and since then this is the question that I couldn't find an answer to.
So, seriously how does this magic works on its very bases? For example, when I'm using Unreal Engine 4, I can simply call LineTraceByChannel, pick a start and end point, and then the engine will trace a line... | Nice question. To dense to obtain a short answer of the kind "raycasting works just like this" and that's it. The big deal is how the raycasting and the collision point obtained is optimized and all the math and software tricks behind it for it to be that cheap. However, that's too deep and complex stuff to be explaine... |
65,366,206 | 65,366,392 | In C++, is a 2D array slower in overall operations than a 1D array that behaves like a 2D array? | I just want to ask which is better to implement in terms of performance and efficiency when dealing with 2D arrays, and possibly code complexity since we need to make a matrix library for our group project.
I have a code below (which I think may not be a good example, and I also have a limited ram that's why)
#include ... | In your particular case, both of your for loops are actually accessing the memory sequentially, even in the 2-D array case (due to the memory layout of the 2-D array), so there is no real difference. To see some difference execution speed, try the following pattern:
for(unsigned long long int i=0; i<10000ull; ++i){
... |
65,366,418 | 65,376,322 | Question about the object adress of a return object with the type of boost::function & | Why the addresses of this two variable(i.e hoofunc and Ctx::hookFunc4Boost) are not same whereas the Ctx::getBoostHookFun() return a left reference to Ctx::hookFunc4Boost?
I intend to avoid the copy of a temporary object by returning a left reference to Ctx::hookFunc4Boost.
Here is the code snippet:
#include <boost/fun... | With the help of JaMiT, I think I find the answer.
Here is a demo code(https://coliru.stacked-crooked.com/view?id=12bc35c31c9eb605):
#include <iostream>
class Ctx
{
public:
Ctx(int cnt):m_cnt(cnt){}
const int& getCnt(void)
{
std::cout << "inner:" << (void*)&m_cnt << std::endl;
return m_cnt;
}
private:
int m_... |
65,366,489 | 65,366,533 | How to disable warning from VS-Code GCC Compiler? (not use #pragma) |
I'm working on VS-Code with C/C++ intellisense[gcc-arm]. When I do compile , The VS-Code show me hundred of warning like that:
Conversion from 'int' to u16_t{aka 'short unsigned int'} may change value [-Wconversion]
I do not want the VSCode show me those warning. But I have no permission to edit the source code. So, ... | Referring to my own reference document here, if you have access to the build flags, you can pass in -Wno-conversion to disable this warning at compile time.
From my document:
Additional C and C++ build notes (ex: w/gcc or clang compilers):
Use -Wwarning-name to turn ON build warning "warning-name", and -Wno-warning-n... |
65,366,764 | 65,367,376 | why is the method of assigning one to another is different from assigning two individual variables in C++? | so in the picture, it says that the problem is with the starting address of the array as we cant change it. but why does this apply only for arrays. int x = 1; we could easily say int y = x; and it would work. doesnt this change the memory address of the variable too?
| [tl;dr] The first and sole reason why newValues = oldValues; is illegal ("will not work") is that the C++ standard prohibits it. Array assignment is not defined, supported or allowed in C++, and therefore any such statement is invalid code. Any other attempts to "explain" it, using memory addresses or other speculation... |
65,366,996 | 65,530,430 | Getter & Setter in C++/C project? | I am trying to update C/C++ code, want to use getters and setters for tracking and/or testing.
Made a template class for general declarations
#include <iostream>
using namespace std;
#define TRACK_PROP(a,b) TrackProp<a> b(#b);
#define TRACK_PROP_SET(a,b,c) TrackProp<a> b(#b, c);
template <class T>
class TrackProp {
... | I am a not expert, but isn't it too complicated to generate C++/C functions and replace your variable by some macro ?
Your a bit modified version:
#ifdef __cplusplus
#define TRACK_C(a, b) \
extern "C" a _get$##b() { \
return b; \
}; \
extern "C" void _set$##b(a c) { \
##b = c; \
};
#define TRACK_PROP(a,b) TrackProp<a> ... |
65,367,000 | 65,368,186 | Swift memcpy doesn't have any effect when used with ZMQ zmq_msg_data | I've been trying to write a libzmq wrapper for Swift by building off of an existing wrapper called SwiftyZeroMQ. However, for our purposes, we require the usage of raw UDP which means we need to use ZeroMQ's Radio/Dish draft method.
I've been able to successfully write a wrapper for receiving data via the Dish socket b... | The API-documented zmq_msg_data() function is fine & safe to "read" a data-part from a delivered ZeroMQ message.
The context of use & the order of parameters :
void* memcpy( void* dest,
const void* src,
std::size_t count
);
shows, that your code tries to "store" data ... |
65,367,228 | 65,367,390 | Write a program that corrects an extra character in a string |
Write a C++ program that corrects an extra character in a string.
For example:
Input
Excellent time too listen to music
Output
Excellent time to listen to music
I am new to C++ and do not understand how to do this. Can somebody please help?
| In C++ you can use the string library to perform string manipulation. Here I have used 2 methods of the string library to answer your question
Method 1 : Using replace()
string sentence = "Excellent time too listen to music";
sentence.replace(15, 3 , "to"); // replaces string found in 15th position, 3 places, with the ... |
65,367,467 | 65,367,475 | std::is_same_v<> returns false for enum declared with type? | Below is some code I am testing following the example for std::underlying_type. I'm expecting it to output "true", but instead it outputs "false":
#include <iostream>
#include <type_traits>
enum class Color: int
{
Red,
Blue
};
int main()
{
constexpr bool match = std::is_same_v<std::underlying_type<Color>, int>;... | std::underlying_type is a class with a member type alias type which encodes the actual underlying type.
If you want that type, you need to ask for it explicitly:
constexpr bool match = std::is_same_v<std::underlying_type_t<Color>, int>;
// ^^
or
constexpr bool m... |
65,367,493 | 65,367,687 | Is it possible to find the intersection of 3 sets in c++ in a single line? | I have 3 sets A,B,C. I will need to find
Union (intersection(A,B), intersection(B,C), intersection(A,C) )
(A ∩ B) ∪ (B ∩ C) ∪ (A ∩ C) in set notation.
Is it possible to convert it into code without needing to declare 4 more sets.
#include <set>
using namespace std;
set<int> set1, set2, set3;
set1.insert(1);
set1.inser... | You can, but it'd be an extremely long line that would piss off anyone who would try to read it.
As for a more "elegant" approach, you should split up what you're trying to do into functions:
vector <int> getIntersection(vector < vector <int> > &sets)
{
vector <int> result; // To store the reaultant set
... |
65,367,974 | 65,368,057 | How to null terminate pointer passed as an argument | So i have this function that reads file, allocates memory, and puts file's content into buffer. I constantly get garbage data in the end though, so i need a way to null terminate the buffer.
#include "GetText.h"
void GetText(const char* filename, char** buffer)
{
FILE* file = fopen(filename,"rb");
long file_le... | Since the bracket operator has higher precedence than pointer dereference you need to dereference buffer before indexing, like this:
(*buffer)[file_lenght] = '\0';
In your program you also need to make sure malloc was successful.
|
65,368,064 | 65,370,734 | Implicitly deleted special functions with std::chrono::time_point | I have some code like this
#include <chrono>
using std::chrono::steady_clock;
using std::chrono::time_point;
class MyClass
{
public:
MyClass() noexcept = default;
MyClass(MyClass const&) noexcept = default;
MyClass(MyClass&&) noexcept = default;
MyClass& operator=(MyClass const&) noexcept = default;
... |
How come time_point's default constructor isn't noexcept?
When noexcept first went into the standard in C++11 the committee was very hesitant to "over apply" it. noexcept is much easier to add to the standard than to remove. In applying it conservatively, "conditional" noexcept was often shunned.
I would like to ... |
65,368,223 | 65,375,135 | Index of first byte having its MSB set | I have eight 8-bit values stored in a 64-bit integer. The MSB of each byte can either be 1 or 0, and the rest of their bits are all 0. Example:
MSB 10000000 00000000 10000000 ... 10000000 00000000 00000000 LSB
I now need to find the index of first byte that has its bit set. First meaning that we search from the least s... | (Edit)
Isolate the lowest set bit x &= (-x) then see How to find the position of the only-set-bit in a 64-bit value using bit manipulation efficiently? which is examining this exact problem (despite the title).
The answers below are slightly more general.
A couple cycles of latency could be saved over the de Bruijn bi... |
65,368,365 | 65,369,750 | Using KeyPress in C++ from string input creates errors | Solved: Check the void SendInputString( std::wstring &str) function in this answer
I am developing an executable in C++ which can be given a string as a command-line parameter and it will be typed emulating the keyboard; using keypresses.
In the format on command line:
{program name} {string to reproduce} {time betwee... | Can use the function SendInputString( std::wstring &str) from this answer
|
65,368,477 | 65,368,603 | Arithmetic calculation anomaly | I was trying to solve this exercise. Here is the solution:
#include <iostream>
using std::cout;
using std::cin;
int main()
{
int n, a;
cin >> n;
int* answers = new int[n]; // allocating memory
for (int i = 0; i < n; i++)
{
cin >> a;
answers[i] = (a - 32) * 5/9;
}
for (int ... | In (a - 32) * 5/9; the expression is done from left to right as ((a - 32) * 5)/9 because * and / have the same precedence with left-to-right associativity
If you do (a - 32) * (5/9) then it's exactly the same as (a - 32) * 0 because the expressions in () are done first, and 5/9 is an integer division that results in 0.... |
65,368,490 | 65,369,993 | How gets size of char[] when i read from a text file | I'm reading a .txt file. I need to read at most 254 characters into my char* buffer, so I did this:
char *buffer = new char[255];
***Some Code***
if (!feof(fichero))
{
if (fgets(buffer, 254, fichero) != NULL)
{
How do get the size of the buffer read? Right now I'm using a manual method to find '\n' and use its... | int getSize(char* buffer)
{
int i;
for(i = 0; i < int(strlen(buffer));i++)
{
if(buffer[i] == '\n')
return i;
}
return strlen(buffer);
}
By now no other way to do with char*
|
65,368,582 | 65,368,906 | why is my code result showing Segmentation fault (core dumped)? | Ive created class mat (matrix) with consructor functions and operator + overloaded to add two matrix' but when i compile and run my code, Everything works fine till i initialize my m1, m2..and then result is "segmentation fault (core dumped)".
I cant figure out why is it showing it?
i've not posted here the ostream& op... | The mat tmp; in the operator+ is not initialized. It uses default argumentless constructor which does nothing, and, in particular, does not set the p pointer to anything, which causes the segmentation fault when you try to assign to its contents. A good operator+ should check if both matrices have the same dimensions a... |
65,368,600 | 65,370,873 | *pt = x; not working (meaning of * and & in C++) | I am totally newbie and have hard time digesting pointer section in C++.
What I have understood is this:
to access the content of the address, use *
to access the address of the content, use &
So basically my question is this: why is the codes below throw errors?
int x = 10;
int *pt;
*pt = x;
Why should I code in form... | I think you are confusing about mean of '&' and '*'.
In a nutshell,
&x: A bowl of x address.
*pt: A fork for choose address(only address).
And if you declare as 'int *pt', you don't need to declare as '*pt=&x'. Because 'pt' is already pointer variable.
|
65,368,683 | 65,370,684 | C++ How do I stop resizing Sf :: Text on screen resize ( but at the same position) | Im making map editor and i want to add resizing window but when i resize window my gui elements are resizing too how can i stop that,
i stop resizing map surface with set new size of map view but i cant do it with gui elements because it changes positions of gui elements
if(events.type == sf::Event::Resized)
{
... | If you currently DO NOT have a GUI view your rendering code might look something like:
m_stateData->window->clear();
m_stateData->window->setView(m_mapView);
m_stateData->window->draw(m_map);
m_stateData->window->draw(m_gui);
m_stateData->window->display();
This is drawing the GUI on the same view as the map, so if th... |
65,368,769 | 65,368,842 | How to separated numbers by a comma in output? | I want to find prime numbers in a given range.
The output number must be separated by a comma.
#include <iostream>
using namespace std;
int main()
{
int i,j,lower, upper;
cin >> lower;
cin >> upper;
for (i = lower + 1; i < upper; i++)
{
for (j = 2; j < i; j++)
{
if (i % j == 0)
{
... | Instead of printing the result right away, you can store it in a vector, so you know exactly how many numbers you want to print. Then you print your vector this way :
std::vector result;
std::string output = "";
for (size_t i = 0; i < result.size(); ++i) // Notice the ++i, not i++
{
if (i != 0)
output += ", ";
... |
65,368,895 | 65,369,663 | Find all array permutations of splitting a string in C+++ | I have a string of numbers that I'd like to split into all possible combinations (the order of letters must be remain fixed), so that:
data = "12479"
Output
combs = [[1, 2479], [1, 2, 479], [1, 24, 79] ...etc]
How can I do that?
| The recursive algorithm is straight forward:
combinations(data)
if size(data) == 0 return []
if size(data) == 1 return [ data ]
return
[ head(data) ] + combinations(tail(data)) +
[ head(data) + head(combinations(tail(data))) + tail(combinations(tail(data)))
The first two return statement are base cases... |
65,369,110 | 65,369,372 | Making multiple operator<<() definition for a single class | So basically this is what I want to make:
void someMethod() {
StreamClass streamClass{};
streamClass << "Something" << "\n"; //do something
streamClass.doA << "Something" << "\n"; //do another thing
streamClass.doB << "Something" << "\n"; //do something else
//If the first one is impossible, what ... | The first way is perfectly viable, as long as you make doA and doB members of StreamClass, give them a reference to the StreamClass instance that has them (during construction) and make them implement operator<<.
At the end, the types of doA and doB should hold a reference/pointer to StreamClass or StreamClass::Data. C... |
65,369,355 | 65,369,400 | Void function doesn't print | I am trying to write a code to print values using function and the program doesn't print anything and I don't know why. I know void function don't return any value so I put cout inside the function and I call is correctly
#include <iostream>
using namespace std;
void Print(int n){
for (int i = 0; i <= n; i++){
... | Start your loop from 1 in Print function. You can not mod a number with 0. Division by zero is not allowed.
|
65,369,421 | 65,370,201 | C/C++ compiler optimisations: should I prefer creating new variables, re-using existing ones, or avoiding variables altogether? | This is something I've always wondered: is it easier for the compiler to optimise functions where existing variables are re-used, where new (ideally const) intermediate variables are created, or where creating variables is avoided in favour of directly using expressions?
For example, consider the functions below:
// 1.... | Good modern compilers generally do not “care” about the names you use to store values. They perform lifetime analyses of the values and generate code based on that. For example, given:
int x = complicated expression 0;
... code using x
x = complicated expression 1;
... code using x
the compiler will see that complicat... |
65,369,531 | 65,382,533 | What's the best practice to create new objects in C++? | I'm fairly new to C++ and just learned about smart pointers. Now I'm wondering what the best practice is to make sure that they are efficiently used (let's say my optimization algorithm requires hundreds of millions of objects to be created, evaluated [in relatives] and then then safely discarded - ideally in a concurr... | The concept of std::shared_ptr is so cool that I had to use it everywhere in my first new project after it appeared! It enables RAII (A C++ explicit garbage collection method) for all objects pointed to being destroyed when the object owning the std::shared_ptr is destroyed.
Now std::shared_ptr has a few drawbacks, som... |
65,369,597 | 65,370,198 | How to transfer values/data between 2 programming languages? | suppose I create a program in c++
and create an .exe by the name of ctesting.exe
#include<iostream> //ctesting code
using namespace std;
int main()
{
int n;
cout << "enter number=";
cin >> n;
return n+1;//this value is returned to the program that executed ctesting.exe
}
and now i create another progr... | If I understand correctly, you want to have two pieces of code written in different languages to communicate with each other. There are multiple ways to do so, but most of them are a little too complex to grasp for someone who is new to programming, so here is my advise.
The easiest way to achieve this is by not having... |
65,369,710 | 65,370,104 | What does "PKc", as the output of typeid(var).name(), mean? | I'm getting
PKc as the output when providing typeid(check).name() - where check is a char variable - as the argument to typeid.name()
#include<bits/stdc++.h>
using namespace std;
main()
{
char check='e';
cout<<typeid(check).name()<<"\n";
cout<<typeid(typeid(check).name()).name();
}
output
c
PKc
Getting it ... | PKc is the mangled name of const char*. P is the encoding for "pointer", K refers to "const", and c means "char".
See also Why does typeid.name() return weird characters using GCC and how to make it print unmangled names?.
|
65,369,779 | 65,369,828 | Why does my C++ function, only when it's placed after main(), not work? | I recently picked up C++ and decided to try out making a function. However, I've run into a problem with my function func() where, even if declared beforehand, it only works if it's placed before the main() function.
If I place it after the main() function, the system tells me there is "no matching function for call to... | In C language, the declaration int func(); means a function with an unspecified number of arguments of any type, returning a int.
In C++ language, the same declaration int func(); means a function without any arguments, returning a int.
And therefore, in C++, the definition of func with an argument of type int is an ov... |
65,370,327 | 65,370,525 | How to make a 2d vector from input string? | I got this problem in one of the coding questions in my university exam where I knew the answer but couldn't follow as I didn't know how to parse the string and convert it into a 2d vector.
So I have got a 2d vector in the form of a string
"[[1,4], [5,7], [4,1], [8,9]]"
I want to convert this string into a vector<vect... | Here is quick implementation Godbolt:
Note: This answer does not handle cases where integers have more than one digit. It is not generic or easily extensible, but as this is a homework question, you can understand and improve the code.
#include <string>
#include <vector>
#include <istream>
#include <sstream>
#include <... |
65,370,439 | 65,371,140 | Efficient root finding in directed acyclic graph for multiple requests | I'm struggling to find a solution to this problem with time complexity o(m log n) + O(n).
Assume you have directed acyclic graph with n nodes and m requests, each node has at most one parent. At time = 0, the graph is empty. Requests have two types: add edge (u, v) or find root of the subgraph with vertex u. You shoul... | This can be done by union find with path compression, but without union by rank since it's important to be able to control which node remains the root of its component. The time complexity is as desired, O(m log n + n).
|
65,370,588 | 65,378,519 | How to write a function that takes a variadic number of array<double, N> and deduce N? | The goal is to have a function that takes an arbitrary number of array<double, N> of arbitrary size N (but this can be the same for all), and have N available inside the body of the function. For example let's say I want to return another user defined array type using N, MyArray<N>. I hope it's more clear! Thanks I am ... | I finally managed to do it, the still bad element is that the type of N in the template part of Foo has to match exactly the type used in std::array to indicate the size, this makes N known inside and can be used to make a MyArray object.
Basically I had to declare the parameter pack a template (thus having a template ... |
65,370,647 | 65,806,897 | Clang-tidy alignment suggestion with `altera-struct-pack-align` | I am experimenting with clang-tidy (while using a gcc) with all of it's checks. I was curious if the below case is a bug of clang-tidy as it contradicts my compiler's warnings. Here is a minimum example:
struct a{
virtual void func()=0;
virtual void func2()=0;
};
struct b:a{
void func() override {};
v... | Reasoning
After all the reasoning for that is quite simple. The altera* options of clang-tidy relate with fpga programming in C with some very specific compilers in mind (I think altera uses c2h and there is also a big list of alternatives here). These compilers probably doesn't have these quite advanced warning but I... |
65,370,779 | 65,372,894 | C++ how to print words with views::split? | In p0896r4
23.7.11.1 Overview [range.split.overview]
split_view takes a View and a delimiter, and splits the View into
subranges on the delimiter. The delimiter can be a single element or a
View of elements.
Example (with slight modification to compile)
#include <iostream>
#include <ranges>
#include <string>
i... | None of the standard views are printable, so the short answer is that you basically cannot. We're hoping to change this as part of P2214.
views::split specifically has the issue that you can't even get a contiguous subrange out of it, so you can't meaningfully convert the pieces you get into string_views either. This i... |
65,371,178 | 68,438,888 | Qt6 Android CMake project fails to find Qt component "Core" | I have a problem when I create a new QtQuick project with Qt6 android with CMake. The CMake fails immediately after the creation of the project:
CMake Error at CMakeLists.txt:28 (find_package):
Found package configuration file:
C:/Qt/6.0.0/android_armv7/lib/cmake/Qt6/Qt6Config.cmake
but it set Qt6_FOUND to FALSE so ... | I met this same problem but for Windows Desktop compilation. I just add the prefix path folder, before find_package command:
set(CMAKE_PREFIX_PATH C:\\Qt\\6.1.2\\msvc2019_64)
NOTE that it is just a half of the path to file.
If I well understand, in your situation you should add:
set(CMAKE_PREFIX_PATH C:/Qt/6.0.0/andro... |
65,371,540 | 65,371,608 | Why did my c++ vector become empty in a function | I created an array of vector called ed outside of main, then I modified it in main using push_back, finally I called a function that used the array of vectors. But in the function it says the vector is empty (size()==0)
#include <cstdio>
#include <string.h>
#include <vector>
using namespace std;
int previ[100001], ... | Remove the line:
vector<int> ed[n];
in your main() function.
This line declares the local vector, which is used only in main.
|
65,371,544 | 65,371,666 | Reducing complexity of O(n^2) to at least O(n log n) | I want to reduce complexity of this program but I don't know how.
Program:
You are holding an event and you need money. Every person that participates will give percentage of their salary to the event, but every person must give the same percentage. If the percentage you chose is for example 30% and person P is only w... | First, sort all your people by the percentage they are willing to give descending. Now whatever percentage you pick, only some first people on the list would actually pay. Therefore, you would make the most profit-making it the last person percentage. Now also notice, that from this prefix everyone gives salary * perce... |
65,371,580 | 65,373,058 | Smart pointer toolkit using variadic CRTP | I am about to design and implement a kind of smart pointer toolkit - a set of classes to define various types of smart pointers like unique_ptr, intrusive_ptr, shared_ptr, observing_ptr, tagged_ptr etc. Just to mention I am working in freestanding environment where I have no c++ library available. My intersion is to av... | You might use variadic template:
template<template<typename, typename...> class... TRAITS>
// ^^^^^^^^^^^^^
struct make_traits {
template<typename DERIVED>
struct Traits : public TRAITS<DERIVED>... {};
};
template<typename T, template<typename> class POINTER_TRAITS>
class SmartPointer : p... |
65,371,638 | 65,375,964 | List iterator is not incrementable | I'm a bit rusty on c++ and am returning to it to get better. I searched a bit on StackOverflow already to no avail. The issue I am having is "list iterator not incrementable". Below is the section I believe to be the culprit, as this is the only location that I use an iterator with a modifier.
if (!io_queue.empty()) ... | You are incrementing it unconditionally on every loop iteration. But when erase() is called, it returns a new iterator to the next list element after the one being erased, and so if that results in it being set to the end iterator than incrementing it again is undefined behavior.
Simply move the ++it from the for state... |
65,371,730 | 65,372,016 | pointer minus pointer in array and variable | Can anyone help me with this.
I thought pointer is a object that hold address of a variable. So when i minus a pointer to a pointer. it get this result.
int a = 2;
int b = 7;
int* c = &a;
int* d = &b;
int e = c - d; // = 3
int array[] = { 1, 2, 6, 4, 7, 8, 5, 3 };
int* f = &array[0];
int* g = &array[8];
int h = g - f... | You are right, a pointer holds address of an object in the memory. In C and C++ we can do pointer arithmetic which lets us subtract pointers from each other and more. Substracting pointers gives us the distance between the two addresses in the memory. The unit of the distance is determined by the pointer type. Meaning ... |
65,372,722 | 65,372,764 | insert function on a linked list doesn't work | The insert function on my single linked list doesn't work. I've narrowed down the problem to the while loop statement. Since the statement has an AND operator, the entire statement either evaluates to true or false.
while(value > nodePointer->value && nodePointer != nullptr)
this is what I wrote, and it doesnt work
w... | while (value > nodePointer->value && nodePointer != nullptr)
When nodePointer reaches the end of the road and becomes NULL, the above condition will check nodePointer->value first, before checking whether nodePointer is NULL. This is not going to end well.
You need to check for the NULL pointer as the first order of b... |
65,373,222 | 65,373,691 | How to use mutex properly? | I have mailBox class with send and receive methods shared between threads, and threads: thread1 send message, threads 2 and 3 receive messages, how I must using mutex for synchronize this?
Any combinations that I have tried hasn't led to success.
std::mutex g_lock; //in global
void sendMessage(Message msg) {
if (g_... | Box up low level mutexes into building block types.
Lock based thread safety is ridiculously easy to get wrong. Not only is it fragile, it doesn't compose; three routines that are pairwise thread safe can be when combined unsafe.
Thread safety is a relational property, not an absolute one.
There are various known patt... |
65,373,289 | 65,373,378 | Does string in C++ have no out of bound exeption/error? | string p="a";
cout<<p[4];
This piece of code doesn't give any error. Does this mean the string data type in C++ is also not bounded as are the arrays?
| Your code has undefined behavior.
std::string::operator[] does not perform any bound checks.
std::string::at() on the other hand performs bound checks and throws an exception of type std::out_of_range when you access data that is out of bounds.
Does this means the string "data type" in C++ is also not bounded as are t... |
65,373,680 | 65,373,865 | Making a 2D array of children elements | I'm trying to create a chess engine, so I made a Board class (only showing the h file because the implementation is pretty straight forward):
class Board {
private:
Piece* board[SIZE][SIZE];
bool turn;
public:
Board();
Piece* getBoard() const;
void printBoard() const;
};
The idea is to make a 2D ar... | On the right side of the following statement:
board[i][j] = EmptyPiece(0, i, j);
EmptyPiece(0, i, j) created a temporary object with type EmptyPiece, which is also convertible to type Piece. But the left side requires a variable of type Piece*, i.e. a pointer to a Piece object. In general, you can't assign a variable ... |
65,374,069 | 65,531,182 | SDL renders blackscreen c++ | I follow the tutorial but rendering black screen.Cant set a bg color.
#include <SDL2/SDL.h>
#include <iostream>
using namespace std;
int main() {
SDL_Window * window = nullptr;
SDL_Surface * window_surface = nullptr;
SDL_Surface * image_surface = nullptr;
SDL_Init(SDL_INIT_VIDEO);
window = SDL... | Its because you clear your renderer before you set your draw colour. Every time in the loop add SDL_SetRenderDrawColor(renderer, 255,255,255,255);
SDL_RenderClear(renderer);
|
65,374,106 | 65,374,211 | thread arguments must be invocable after conversion to rvalues | I'm currently trying to learn to use threads and I have a problem with passing arguments to a function executed in another thread.
void Class::foo(const string& a, size_t b, Obj& c);
(the thread executing this function is declared inside the class Class)
for the last agument I use std::ref() as mentioned in the docume... | If you're using invoke on non-static member, you have to pass instance of Class, otherwise you will take another overload which won't identify first argument as invokable.
std::invoke(&Class::foo, instance_of_class, cref(charSet), b, ref(c) );
Same situation with std::thread, which even is shown in examples of its u... |
65,374,249 | 65,374,304 | How to handle pointing types with templates, and const keywords? | I wanted to do a simple thing with templates and got surprised how not simple it is.
I have got :
An array which size is 9, let's say type const int *
I want it to pass it as an argument for an object construction, like so:
const int * myArray[9];
//filling array;
ObectType<int*> myObject(&myArray[0]);
With object c... | When you create myObject you are specifying the template parameter T with the argument int*. When substituted into the constructor argument T const *, this gives int * const *, which is incorrect.
You need T to be int const *, and you need to provide the correct template argument:
ObjectType<int const *> myObject(&myAr... |
65,374,455 | 65,375,616 | wxThread::Delete hangs forever | I'm trying to create a multithreaded wxWidgets application using the wxThreadHelper mixin. I'm working on Windows, but the whole idea was to be platform independent. I'm basically following the online examples, but there must be something I don't understand, since as soon as I call the Delete() function, the applicatio... | There are many issues here. To answer the main question of why this hangs your program, in the OnClose method you call Destroy() and then delete the frame (which includes m_text_time). Meanwhile, your thread is sleeping and when it wakes up, it will try change the label for m_text_time which no longer exists. I'm no... |
65,374,779 | 65,374,780 | Why does passing an anonymous stack-allocated array to a unique_ptr not cause a segfault? | I was experimenting with template specialisations by recreating a basic std::unique_ptr when I realised that the following code compiles and runs successfully:
namespace not_std {
template<typename T>
class unique_ptr
{
public:
unique_ptr(T *pointer)
: pointer_(pointer)
{ }
~unique_ptr()
{
... | Right as I was about to post this question, I figured out the the issue:
unique_ptr<char[]> buffer(char[64]) actually declares a function called buffer that takes a char[64] as an unnamed parameter and returns a unique_ptr<char[]>. So this is actually an instance of the most vexing parse as pointed out by @xaxxon.
Ar... |
65,374,857 | 65,375,034 | Can't use CRTP for inner class | I'm trying to use CRTP for common functionality of several iterators types. As stated here
Using inner class with CRTP it's impossible to use CRTP for inner class, so I move the base iterator class out of the container class and inherit it inside the container for the iterator. But I still got
error: invalid use of inc... | Your issue is that you misuse CRTP as you do a circular inheritance:
ConcreteIteratorBase
-> IteratorHelperMixin<ConcreteIteratorBase, ..> -> NotEqFromEqMixin<ConcreteIteratorBase>
-> ConcreteIteratorBase
You should drop the inheritance here
template <typename T>
class NotEqFromEqMixin //: public T
// ... |
65,375,096 | 65,375,148 | Variadic CRTP Base Class with Additional Template Parameters | I have a trait classes which are about to be used in variadic CRTP to extend the features of SmartPointer class.
This question is created as the followup of https://stackoverflow.com/a/65373058/5677080
An example trait class:
template<typename DERIVED, typename DELETER>
class Owning {
public:
using deleter_type = ... | Something along these lines, perhaps:
template <typename DELETER>
struct MakeOwningWithDeleter {
template <typename T>
using type = Owning<T, DELETER>
};
Now you can pass MakeOwningWithDeleter<DELETER>::type to make_traits. Same trick you already use for make_traits.
|
65,375,102 | 65,375,325 | Exit function after certain time in C++ | I have a function that has exponential complexity (the contents of which cannot be modified):
void exponential_func(int depth){
// recursively search a tree and extract best value
return value;
}
This function is called iteratively
void call_exponential_function(int max_depth){
for(int i = 1; i < max_depth; i++)... | You're going to need to make exponential_func cooperatively exit when it is told to do so, by passing in a time deadline.
If it's literally impossible to modify that function, then you can run it on a separate thread, and terminate the thread when the deadline is up. However, this risks leaving data that exponential_f... |
65,375,734 | 65,375,818 | Inferring type and class when passing a pointer to data member as a non-type template argument | I need to pass a pointer to data member, its type and the class it's a member of, to a template struct. The following works:
template<typename T, typename Cls, T Cls::*member> struct Member {};
struct Struct { int x; };
Member<int, Struct, &Struct::x>
But it requires to explicitly mention the type (T: int) and the cla... | You can use a helper to get the type of the class and the member from the type of a member pointer:
template <typename T> struct type_from_member;
template <typename Cls,typename M>
struct type_from_member<M Cls::*> {
using class_type = Cls;
using member_type = M;
};
Then you can use auto and inherit from the... |
65,376,074 | 65,376,410 | Creating generic (template) dispatcher for producer and consumer | I am trying to create a templated dispatcher to handle the registering of consumers, and pushing of data from producers. The goals are:
When a user calls push(myData) a static (singleton-ish) dispatcher is used.
When a user registers a callback interested in data of type T, they register their callback to the dispatch... | If anyone comes across this, I found the answer. The culprit:
auto d = Get<Dispatcher<T>>();
Replacing both calls (reg and push) with
Dispatcher<T>& d = Get<Dispatcher<T>>();
If anyone knows why, would like to know. I solved it by implementing all the constructors (move/copy) in private: and got compile errors. Which... |
65,376,122 | 65,376,264 | cannot access properly after getting pointer of a member of struct | In the following example, I basically tried to get the pointer of the element of the vector in the data. For me, those three methods seems to do the same thing, but the result is different :
123
9.88131e-324
5.61658e+259
and only via first method, the element is accessed properly. Could you point out my mistake and ex... | The primary problem you have in get_ptr2, e.g.:
void get_ptr2(int idx, double* ptr){
ptr = &a[idx];
}
is that ptr will be a copy of the pointer from main(). When you change the value of ptr in your function, you are changing the value of the local copy of ptr and the results are never seen back in main().
(not... |
65,376,868 | 65,379,282 | Make second template functional of a unary_function | I'm a CS student, and the I have a task where I need some help. The task is to create a vectors_predicate_view class that gets a T type as the first template parameter and a predicate as the second template parameter. In its constructor the class should get 2 std::vectors as parameters.
Here is the class:
#pragma once
... | You can define a predicate that always returns true no matter what the argument is:
struct always_true {
template <typename T>
constexpr bool operator()(T&&) const noexcept {
return true;
}
};
Then, set this predicate to be the default argument for the template parameter Predicate:
template <typena... |
65,377,048 | 65,377,828 | How to mask multiple objects using stencil masking | I am drawing two different stencil masks at the same location and would want my mask 1 to only affect shape1 and Mask 2 to affect shape 2.
This is the code.
glClearStencil(0);
glStencilMask(~0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// Render all stencil masks
// First geometry M... | After rendering the masks, the stencil buffer has 4 possible values:
0 where noting is drawn
1 where mask 1 is drawn
2 where mask 2 is drawn
3 where both masks are drawn
When you draw the shapes, you just want take into account the masks of the shape. However, this means that you need to draw Shape 1 where the stenci... |
65,377,051 | 65,377,707 | Is the C++ ostream at the start of a line? | In C++, how do I detect if my std::ostream os is at the start of a line, in other words (I think) the most recent thing written to os is either os<<'\n' or os<<std::endl(), or else nothing has yet been written to os?
At first glance, this sounds unnecessary, because I can just keep track of the state myself. But a com... | At least as I'm reading things, what you really want isn't the ability to get the position in the current line. Rather, what you really want is to be able to print something that is guaranteed to be at the start of a line--the current line if the immediately previous character was a newline (and, I'd guess also if it w... |
65,377,120 | 65,377,163 | Using C++ discrete distribution with weights taken from a data structure | I am trying to use discrete distribution (here too. However as you see in the examples you do this by writing:
std::discrete_distribution<int> distribution {2,2,1,1,2,2,1,1,2,2};
or
std::discrete_distribution<> d({40, 10, 10, 40});
which is fine if you have 10 or four elements with weights. (also I don't know if the... | You may put your all weights into std::vector<double> weights;, then you can initialize your discrete distribution as std::discrete_distribution<> distr(weights.begin(), weights.end());. Code:
std::vector<double> weights;
for (auto const & p: particles)
weights.push_back(p.weight);
std::discrete_distribution<> dist... |
65,377,277 | 65,377,346 | What is being defined in this class definition | I am learning unreal engine and I know a little about C++. However, I am not entirely sure what is going on in this line of code. Can someone explain to me like i'm 5?
class ESCAPEROOM_API UWorldPosition : public UActorComponent
We are defining the function as UActorComponent which is understood, but not sure what is... |
We are defining the function as UActorComponent
Not true, you are defining a class UWorldPosition which is publically derived from another class UActorComponent.
The ESCAPEROOM_API part is not standard C++ but it is likely to be a macro whose purpose is to export that class from a shared library. See here.
Since you ... |
65,377,448 | 65,377,464 | C++ copy constructor incorrectly takes argument | I have the following code that behaves weirdly. The flow I understood so far is, display(line); will call the copy constructor Line::Line(const Line &obj), and the reference of line will be passed in. However cout<<"[origin] *ptr="<<*obj.ptr<<endl; will print [origin] *ptr=32767 instead of [origin] *ptr=10.
The more we... | You program invokes undefined behavior (UB). When your constructor finishes:
Line::Line(int len)
{
ptr=&len;
cout<<"*ptr="<<(*ptr)<<endl;
} // ptr is dangling
the pointer ptr is pointing to a local variable len, which no longer exists. ptr is now dangling, and any attempt at dereferencing it invokes UB.
Your p... |
65,377,535 | 65,377,814 | Why there is something wrong when invoking ctor in another ctor? | Here is a demo code snippet(https://godbolt.org/z/31Tq3r):
#include<iostream>
class Ctx
{
public:
enum RUN_MOD
{
MOD_RT,
MOD_NRT,
};
Ctx(RUN_MOD runType)
{
if(runType == MOD_RT)
{
Ctx();
}
}
Ctx()
{
m_L = malloc(100);
... | Constructor delegation can only be used from inside a constructor’s member initialization list, NOT inside a constructor’s body. This answer shows how to avoid the need to use constructor delegation at all, by creating a common initialization function that multiple constructors can then call as needed.
However, if you... |
65,377,603 | 65,377,703 | Is slicing a vector faster than copying each element into a new vector? | Let's say I have a vector of 10 ints and I want to create 2 subvectors each of 5 elements.
Is it faster if I slice the vector like this:
vector<int> vec({0,1,2,3,4,5,6,7,8,9});
auto x = vec.begin();
vector<int> vec2(x, x+5);
x += 5;
vector<int> vec3(x, x+5);
As opposed to this?
vector<int> vec({0,1,2,3,4,5,6,7,8,9});
... | First will be faster, because in the first way std::vector will allocate all needed memory in first construction, but in second way with std::vector<T>::push_back need to allocate memory and increase the underlying array size which is painful.
Here is a little benchmark: https://quick-bench.com/q/dXoWJhTzYDgNnIPFj-vla4... |
65,377,711 | 65,377,822 | Find the number of steps transforming a/b into c/d so that 0<a<b<100000 and 0<c<d<100000, or none if there is no ways |
Original problem. Given two valid fractions a/b and c/d. Each transformation is adding 1 to a and b, then optimizing a/b. Find the number of steps transforming a/b into c/d so that 0<a<b<100000 and 0<c<d<100000, or none if there is no ways.
#include <iostream>
#include <math.h>
using namespace std;
int gcd(int x, in... | The first problem is while (b<d). In your example 6<3 is wrong so the while loop is completely skipped.
The next problem is
a/=gcd(a, b);
b/=gcd(a, b);
You are changing a and calculating two different gcd for a and b.
You can fix it with
const auto g = gcd(a, b);
a/=g;
b/=g;
|
65,377,927 | 65,377,966 | Problem generating a random sequence of binary numbers | #include <iostream>
#include <random>
#include <string>
#include <chrono>
using namespace std;
string string_maker5000(int length)
{
unsigned seed = std::chrono::steady_clock::now().time_since_epoch().count();
default_random_engine e(seed);
string stringcheese;
for (int i = 1; i <= length; i++)
{
... | Integers 0 and 1 are not the same as the digits (characters) '0' and '1'. Try this instead
stringcheese += n + '0';
By adding the integer to the zero digit you convert the integer to the required character.
|
65,377,971 | 65,378,164 | Occurrence Manipulation? | I was going over an interesting problem that seems really simple to understand logically and it is, but I can't think of an approach for it.
Example:
Array = [1, 2, 3, 3, 2]
So we traverse from the beginning to the end and find the first index spot where it's a duplicate and then do the absolute difference of it.
The... | I'd run over the array and build a map from the value to a pair of indexes (first occurrence and last occurrence). The first time a value if met, I'd create a pair where both values are the same index, and in any subsequent occurrence, update the last index.
Then, when the map is ready, I'd run over it and sum the diff... |
65,378,413 | 65,378,497 | Real "object-functions" only in header files? | First let me say I'm coming from Java.
So I dug in C++ OO programming yesterday and I'm a bit confused about the functions in the header file.
To me it seems, the object is defined there, as well as all the functions which only belong to the object, not the static class.
But since I'm used to initialize an object which... | Here are two alternatives for defining class methods, the first is within a header file, the second is split between a header file and a cpp file.
// *** in the header file only ***
class X
{
void some_function() { /* some code */ }
};
// *** split between the header file and a cpp file ***
// header file
class X... |
65,378,690 | 65,378,715 | How can the strcpy function copy a large string into a smaller string? | In the following code it seems that I can copy an entire large string into a small string.
So my question, how does that work? I only allocated 2 characters to str1, but it was able to store a longer string.
Does this mean that strcpy is modifying memory on the stack that doesn't belong to us?
Can arrays on the stack ... |
So my question, how does that work?
Poorly. It doesn't do any checks whatsoever to confirm that the operation you're doing makes sense. You're the one responsible for checking that (which obviously leads to bugs).
strcpy is generally just byte-copying loop. It will write the data into increasing addresses. As long as... |
65,378,953 | 65,379,396 | How can I judge whether the contents of the variable have been macro-defined? | #ifdef can be used to determine whether a string is a macro definition. But I have several macro definitions, how do I judge whether the content of the variable has been macro defined.
for example,
char *str = "Macro"
#ifdef (*str)
Is there a way to achieve similar functionality?
| char *str = "Macro"
#ifdef (*str)
That will never work, as str is no macro! The syntax for *str will not be accepted by the preprocessor. BTW: In C++ char *str = "Macro" is also wrong, as you must use const char*!
In general: Avoid macros as they are error prone. They have no type and they are part of some text repl... |
65,379,119 | 65,379,226 | C++ std::vector::emplace_back doesn't compile with string-value class | /* Item.h */
struct Item {
std::string name;
Item(std::string _name) : name( std::move(_name) ) { }
};
/* main.cpp */
/* ... */
const int amount_of_items = val.size();
std::vector<Item> items(amount_of_items);
for( Json::Value::const_iterator itr = val.begin() ; itr != val.end() ; ++itr ) {
items.emplace... | The issue is that you need a default constructor of Item for this sequence of code. The default constructor is disabled because you have a custom constructor for Item.
You can enable it by adding Item()=default;.
Besides that, you have a logical bug: std::vector<Item> items(amount_of_items); initiates items to amount_... |
65,379,191 | 65,379,217 | Confusion about destructor's calling | Does a destructor gets called before an object is destroyed or after an object is destroyed?
I think that it is called before an object is destroyed because after an object is destroyed we cant access that memory to free any resource in there but if I am wrong then please correct me so I can understand it well
#include... |
Does a destructor gets called before an object is destroyed or after an object is destroyed?
The lifetime of the object has ended when the destructor is called. The object is destroyed by the destructor.
// does destructor gets called here
} // or does destructor gets called herecode here
There's really no pract... |
65,379,575 | 65,379,670 | Setting linker subsystem with CMake and clang++ in windows | I'm trying to make a windowed application with SDL in windows, using ninja to build. When I try to build, I get the error:
lld-link: error: subsystem must be defined
It seems I need to set the /SUBSYSTEM:WINDOWS linker flag for it to work. How can I set that in CMake?
I tried using the WIN32 flag mentioned in add_exec... | You can try to use
target_link_options(your_target_name PRIVATE "/SUBSYSTEM:WINDOWS")
See cmake documentation: https://cmake.org/cmake/help/git-stage/command/target_link_options.html
|
65,379,740 | 65,379,829 | string_view to const reference string gets invalidated | I came across this simple code today.
#include <iostream>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
int main(int argc, char* argv[]) {
std::unordered_map<std::string, int> m = {
{"asdf", 123},
{"dsdfesjfdaslkfjasljlasfjlasjfakdlsfjasklfajsklfjaskljlf", 123},
... | Using make_pair you generate a temporary object of type std::pair<std::string, int>. I would expect the conversion to std::pair<std::string_view, int> to throw an error, but apparently it works.
Anyhow, std::string_view is non-owning, so as soon as the temporary object is destroyed (at the end of the line ;) it become... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.