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
68,406,846
68,409,016
What is the proper way to process milliseconds in C++11
I'm trying to update the basic dev library of my project from C++98 to C++11. In the dev library, there are many functions about time, such as uint64_t getCurrentMSTime() { struct timeval stv; gettimeofday(&stv, NULL); uint64_t ms = stv.tv_sec ; ms = ms * 1000 + stv.tv_usec / 1000; return ms; } I'm...
I agree with the currently accepted answer that you should value type-safety, and not return an integral type. However I disagree that returning milliseconds is best. Type safety applies to the difference between time points and time durations as well. For example it makes perfect sense to add two time durations. Bu...
68,407,390
68,408,017
Are concepts with only a boolean literal value ill-formed, no diagnostic required?
I was playing around with C++ concepts and function overloading in a context completely removed from any templates, and stumbled upon this: struct S { int mult(int x) requires (true) { return x; } int mult(int x) requires (false) { return x * 2; } }; int main() { std::cout << S{}.mult(5) << std::endl; } ...
These are the two first examples in the "trailing requires-clause" section of the standard: void f1(int a) requires true; // error: non-templated function template<typename T> auto f2(T a) -> bool requires true; // OK Although examples given in the standard are explicitly non-normative, these ma...
68,407,559
68,408,128
LNK2001 error occurs when building but not by Debugging
I have written a programm using Allegro 5 and wanted to build it in Visual Studio 19 but the build log states that there are some LNK2001 errors when I try to initialize the allegro addons I am using. The Log: Backend.obj : error LNK2001: unresolved external symbol __imp__al_init_image_addon Backend.obj : error LNK2001...
In Visual Studio most of the project configuration is separate for Debug and Release mode. You probably added the Allegro library (.lib file) in Debug mode but forgot to also add it in Release mode.
68,407,921
68,408,252
Why are parameters allocated below the frame pointer instead of above?
I have tried to understand this basing on a square function in c++ at godbolt.org . Clearly, return, parameters and local variables use “rbp - alignment” for this function. Could someone please explain how this is possible? What then would rbp + alignment do in this case? int square(int num){ int n = 5;// just to t...
This is one of those cases where it’s handy to distinguish between parameters and arguments. In short: arguments are the values given by the caller, while parameters are the variables holding them. When square is called, the caller places the argument in the rdi register, in accordance with the standard x86-64 calling...
68,408,027
68,465,065
How to count the times a key has been pressed in c++
I am making a game in Visual studious 2017 (visual c++), where you have to repeatedly press the space bar to earn money. But I have run into a problem, the compiler can't keep up when you press the spacebar really fast and so It miscounts. I tried doing some research, but all I got was this and as I said earlier it can...
I have found an answer to my own question, for those that have the same problem. This code here will do the same thing but is more responsive and will keep up to the button mashing. int click_systm() { char spacebar; while (1) { spacebar = _getch(); if (spacebar == 32) ...
68,408,078
68,408,377
What is expected lifetime of std::intializer_list object in C++14?
Please consider this simplified c++14 program: #include <iostream> struct A { A() { std::cout << "A() "; } ~A() { std::cout << "~A() "; } }; int main() { auto l = std::initializer_list<A>{A()}; std::cout << ". "; } https://gcc.godbolt.org/z/1GWvGfxne GCC prints here A() . ~A() Meaning that std::init...
It's subtle. A std::initializer_list is backed by an underlying array (produced by the compiler). This array is a like a temporary object, and the std::initializer_list is a sort of reference type that binds to it. So it will extend the temporary array's lifetime so long as the "reference" exist. In C++14, we do not ha...
68,408,584
68,440,201
C/C++ Threading in Linux (Raspbian) using VS2019 on Windows 10 -pthread - Can't compile
I'm trying to do my first bit of threading but no matter what I've tried I can't get this to compile. I've gone back to trying to compile some demo code and I'm getting the same problem as in my program. If I run a simple print hello world it compiles and deploys the program fine and I can simply navigate to and run it...
OK both code examples now compile and run. As I originally thought, I needed to add -pthread somewhere in VS2019 and I was putting it in the wrong section. Go to Project Properties > Configuration Properties > Linker > Command Line Add -pthread to Additional Options box and Apply. I hope that saves someone else the 3 d...
68,408,812
68,409,226
How can I sort only some parts of the array in a specific order in c++?
So let's assume I have an array array{12, 10, 10, 9, 8, 8, 8} in descending order. I want to sort the numbers that can be divided by 2 but not with 4 in ascending order at the end of the array, the numbers that are divided by 4 sorted at the start of the array in descending order and the rest in the middle(no specific ...
Let's organize the requirement. The required order is: Numbers that are divided by 4 Others Numbers that can be divided by 2 but not with 4 Among the numbers with same priority according to the above rule, the numbers should be Descending order No specific order Ascending order Let's implement this: #include <iostr...
68,408,842
68,408,946
Why PHP built-in standard functions have empty body?
How is this possible to have an empty body for a function ? Is this related to C/C++ (that PHP is written with ) ? Or is it related to CGI mechanism or something like that ? I want to know how functions work under the hood. What if I want to add a simple function that returns "Hello world" written in C++ to PHP ? Tha...
These are just dummy files (implemented by the IDE) that serve documentation & autocomplete purposes for the builtin functions / classes. If you want to see how PHP works under the hood, take a look at its source code: https://github.com/php/php-src. If you want to extend PHP with custom functions, you can write an ext...
68,409,391
68,410,012
True meaning of word "overloading" in programming
I'm learning C++ and I'm confused about true meaning of overloaded operators and functions. In local literature I've used, there is a translation of overloaded functions with "load" as a noun, not as a verb - so it has the meaning of "an excessive load or burden" although in this case, as I understood it, nothing is "o...
The term overloading in programming stems from semantic overloading - i.e. assigning multiple meanings to a certain word or phrase. In case of C++, the same function or operator can be overloaded - meaning there can be multiple versions of it for different argument types. Which of the overloads is invoked is then deter...
68,409,476
68,409,751
Generate consecutive substring from the string using recursion
I am having a string let say ABCD I want to create all the subsets in such a way that they are consecutive like this: `A` ,`AB`, `ABC`, `ABCD`, `B`, `BC`, `BCD`, `C`, `CD`, `D` AC, AD, BD etc should not be generated as they are not next to each other. I tried to write the logic but now I am getting: See the highligh...
With recursion, you might do: void print_seq(std::string_view s) { if (s.size() > 1) print_seq(s.substr(0, s.size() - 1)); std::cout << s << std::endl; } void print_all(std::string_view s) { print_seq(s); if (s.size() > 1) print_all(s.substr(1)); } int main() { print_all("ABCD"); } Demo
68,410,083
68,410,308
How to prevent unwanted behavior when a data member of a derived class inherits from a data member of its base class?
I have an issue with the following class structure, class Base { int a; }; class Derived : public Base { int b; }; class OtherBase { Base c; }; class OtherDerived : public OtherBase { Derived d; }; The issue is that OtherDerived stores two instances of Base, one through the inheritance to OtherBase and one from the in...
If OtherDerived needs a Derived member, but not its Base part then there is something wrong with your design. It means that Derived is doing more than it should. Either it needs to have Base as base to be fully functional or not. It cannot be both. Use this instead: class Base { int a; }; class Foo { int b;} class Othe...
68,410,523
68,410,577
What does a pointer in the header mean? I couln't find the exact term to google
class Solution { public: ListNode *detectCycle(ListNode *head) { } }; I am learning C++. I don't have much experience with it so I don't know the term which I can google to get the meaning of the pointer in the function header. What is *detectCycle? What is the use for it? It can be a basic question b...
detectCycle is defined here to be a function that accepts a ListNode pointer (the * means pointer here) and returns a ListNode pointer. Since the code block you have shown is empty, the function does nothing. Since it declares a return value and does not return anything, using this function will result in undefined beh...
68,410,706
68,411,063
Throw a derived class in catch scope
I would like to understand what going wrong in the program that cause that PE which is a derived class, is not catching by the second catch and display the error like I want. In the same way, what I have to correct in order to run this simple example class myEx { int errNum; public: myEx(int e) : errNum(e) {} ...
A try block can throw only 1 exception object at a time. It can have multiple catch blocks to specify different types of exceptions it wants to catch, but only 1 of them will actually be executed at most, the one that most closely matches the type of exception actually thrown. If no catch blocks match, the exception pr...
68,410,865
68,411,309
Reference to global variable cause SEGV error when I add an empty constructor to the factory class
I have the following code to provide a factory to create an encoder/decoder for a given data type and encoding scheme (BITPACK, PLAIN, etc), and the code works. class Encoding { public: virtual std::unique_ptr<Encoder> encoder() = 0; virtual std::unique_ptr<Decoder> decoder() = 0; }; template <class E, class D> ...
The typical solution to this is the Singleton pattern, since that defers initialization to the first time the object is needed. Since you have a factory already, you can use a function-local static variable: Encoding& EncodingFactory::Get(EncodingType encoding) { static EncodingTemplate<PlainEncoder, PlainDecoder> pl...
68,411,533
68,412,309
is there a function or way to find common key value pair in a map?
This problem requires me to find the intersection of two linked list. I created two maps with <int,ListNode*> pair. I want to check for common key value pair. The list is not sorted. ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { unordered_map <int,ListNode*> mp; unordered_map <int,Li...
Using map will cause you an O(n) space complexity, it's better to get the lengths of both the lists and then move the head of the list which is longer by the amount of its extra longness. The time complexity for the following approach is O(n + m) and space complexity is O(1). int getLengthLL(ListNode* head){ int cn...
68,411,905
68,413,029
Correct way to overload the multiplication operator in C++ (both directions)
I managed to understand how to implement the overloaded operator as a member function. This way considers the object (instance) is always passed rhs to the operator. In order to get it working, I defined my overloaded operator outside the class. It only works if I define it in the header file (.hpp). Why the compiler i...
C++ requires declaration of a function in a header (typically .h/.hpp) to use it from different source file (.cpp). So you have to put declaration template<class T> point<T> operator*(T& lambda,point<T>& P); in your inluded header (point.hpp). By the way, your implementation of the operator is wrong, since computing X...
68,412,241
68,412,590
OPCClient memory leak in AddItems c++
I am tring to write OPCClient, but the problem is in memory leak. This is my function to read values from OPCServer VARIANT COPCClient::ReadValue(LPWSTR szItemID) { IOPCItemMgt* pItemMgt = NULL; tagOPCITEMDEF* pItems; tagOPCITEMRESULT* pResult = NULL; HRESULT* pErrors = NULL; tagOPCITEMSTATE* pItemV...
It may not be the full answer (it depends on the kind of data inside the value), but before doing CoTaskMemFree(pItemValue), you should also do VariantClear(pItemValue->vDataValue). That's a possible leak in the Read part, but it will only show itself with strings or other kinds of VARIANTs that have additional pointer...
68,412,447
68,412,594
OOP - How to call child method at parent class
I am trying to call virtual method at the constructer of parent class and I want to that of child methods. Let me explain: I need to read words from line by line from a text file and insert them a search tree one by one. I have tree child classes: DictionaryBST,DictionaryAVLTree,Dictionary23Tree. I implemented their ow...
Don't call virtual functions in a constructor or destructor. The reason for this is that during the constructor of DictionarySearchTree, the runtime type of the current object this is always DictionarySearchTree and never any more derived type. This means that virtual function calls made during the constructor will alw...
68,412,472
68,415,210
Do rvalues decay silently?
std::vector foo( std::vector && rval ) { return std::move( rval ); } If a function expects an rvalue reference but gets something else - e.g. a const reference or a temporary or whatever different from std::move(vec), will it silently make a copy instead of throwing an error or even a warning?
Try it yourself: #include <iostream> struct S { S() { } S(const S& other) { std::cout << "copy ctor" << std::endl; } S(S&& other) { std::cout << "move ctor" << std::endl; } }; int foo( S && rval ) { return 1; } int main() { S s1; foo (s1); } Copying S'es is not silent. So, what happens when...
68,412,755
68,421,922
Why does "Q_FUNC_INFO "/" __FILE__" fail in Qt Creator/macOS?
This compiles fine in Qt Creator/Windows: foo(Q_FUNC_INFO "/" __FILE__); But on the Mac, using Qt Creator as IDE/compiler, I get error: error: expected ')' These also fail on the Mac: foo(Q_FUNC_INFO ## "/" ## __FILE__); foo(Q_FUNC_INFO __FILE__); Is there a way of concatenating function name and file name?
I don't know how OP defined foo() but (for the sake of simplicity) I will assume that it might be: void foo(std::string_view text); I must admit that I don't have experience with Mac OS but I heard the common compilers are clang or gcc. I had a look on woboq.org to see how Q_FUNC_INFO is defined. There are a lot of ne...
68,413,302
68,414,980
SWIG Attribute Error: module has no attribute 'delete_...'
I have been trying to get this to work for a while now. I am trying to wrap a LOT of c++ classes in swig, but I can't even get the first one to work. The error is at the bottom. Here is my interface file, setup.py, and class file. Interface //This file is automatically generated from "build_swig_files.py //Makes change...
So I saw the answer in the link below before but didn't understand what it was saying. Basically, my process to build swig didn't include making a new _jcm.so. So pretty much the first time I ran it was it, and after that all the changes I made to the .i or the code or setup.py didn't mean anything because the _jcm.so ...
68,413,332
68,413,403
difference in static vs anonymous namespace for second pass name lookup during template instantiation
I've long since stopped using static for helper functions in favor of an anonymous namespace, which has the advantage of working with types, variables, and templates as well as for functions. However, I was surprised when a function was not found when I replaced a call to it with a wrapper template. See code at https:...
Because the anonymous namespace is, believe it or not, another namespace entirely. And not the global namespace. foo is found by ADL when you use static. Because now foo is properly in the associated namespace of C (the global namespace). It will work however for an inline anonymous namespace, i.e. inline namespace { }...
68,413,439
68,413,623
How can I get a method to return a pointer to a const array
Consider the following code. class SomeClass{}; class AnotherClass { public: SomeClass c1; SomeClass c2; SomeClass c3; const SomeClass* someClassArray[3] = { &c1, &c2, &c3 }; const SomeClass** GetSomeClassArray () { return someClassArray; } }; int main () { AnotherClass ano...
Your interpretation of what is const is wrong. The term const binds left (unless it is on the very left then in binds right). // so This const SomeClass* someClassArray[3] = { &c1, &c2, &c3 }; // Equivelent to this: SomeClass const * someClassArray[3] = { &c1, &c2, &c3 }; So now we can read the type easier. Types are...
68,414,370
68,414,449
Store char arrays address in new array
I have an included file in an Arduino program. MCU is ESP32. included file is: const char bitmap_1587[] PROGMEM = {248,254,254,230,241,231,247,199}; const char bitmap_1604[] PROGMEM = {249,254,254,254,0,191}; const char bitmap_1575[] PROGMEM = {7}; const char* char_addr[] = {&bitmap_1587,&bitmap_1604,&bitmap_1575}; Wh...
This would be correct: const unsigned char bitmap_1587[] PROGMEM = { 248,254,254,230,241,231,247,199 }; const unsigned char bitmap_1604[] PROGMEM = { 249,254,254,254,0,191 }; const unsigned char bitmap_1575[] PROGMEM = { 7 }; const unsigned char* char_addr[] = { bitmap_1587,bitmap_1604,bitmap_1575,bitmap_1605,bitmap_32...
68,415,194
68,415,271
How do I sort a vector of pairs based on both first and second element in a pair?
if i have a vector of pairs vector<pair<int, int>> arr; and passes elements like 4 5 3 7 10 5 5 7 1 5 how can i make the pair to sort the elements depend on the first and second element in a pair like this in descending order 5 7 3 7 10 5 4 5 1 5 or in ascending order 1 5 4 5 10 5 3 7 5 7 Edit: what i want sort th...
You can simply use the std::sort to sort it in ascending order std::vector<std::pair<int, int>> arr; arr.push_back({ 4, 5 }); arr.push_back({ 3, 7 }); arr.push_back({ 10, 5 }); arr.push_back({ 5, 7 }); arr.push_back({ 1, 5 }); std::sort(arr.begin(), arr.end()); In addition you can sort in descending order using std::g...
68,415,439
68,416,553
Weird behavior of vector.size() while printing to std output
I was solving a question when I encountered this behaviour and wasn't able to understand why it happened, any help would be appreciated. vector<int> v1; v1.push_back(0); int no = v1.size() - 3; // this prints output as expected -> -2 cout << no << endl; // this prints -> 18446744073709551614 cout << v1.size(...
The size of standard containers is represented as an unsigned integer (when using the default allocator such as in the example). Unsigned integer can represent only non-negative numbers. When one operand of binary arithmetic operation (subtraction in this case) is unsigned (and at least as ranked as int) and the other ...
68,416,630
68,416,641
typescript equivalent of C++ class reference member variable
class B; class A { A(B b_) : b{b_} {} B &b; }; C++ can have a reference member variable b. Can I do this in typescript? Or is there any niche way to achieve this?
JavaScript (thus TypeScript) doesn't have a reference mechanism like C or C++. You pass values by value and objects are passed by reference. But you can't modify the underlying reference like in C or C++: // This does not work in JavaScript let x = 27; let y = &x; *y = 28; assert(x === 28); You can however do somethin...
68,416,681
68,416,706
Why can't you specify template argument for constructor template
A while back I wanted to write a class that could return a pointer to a type, that was initialised with the same parameters all the time. As this only returns pointers, if I wanted to create an object returning A*, but generating B*, which is a child of A, there would not be an issue, as B* is castable to A*. I wanted ...
This is the explanation from the standard, [temp.arg.explicit]/8: [Note 4: Because the explicit template argument list follows the function template name, and because constructor templates ([class.ctor]) are named without using a function name ([class.qual]), there is no way to provide an explicit template argument li...
68,416,819
68,416,903
Hacker Rank Segmentation Fault
I'm trying to solve a Hacker Rank problem. It's not a difficult problem at all, but for some reason I've been stuck on it all day. Every solution I come up with just doesn't work. I'm certain that all the solutions I came up with were plausible, but the compiler says otherwise. I've narrowed down the problem, and it se...
In your code, space is always equal to n, so (spaces == n) is always true that makes cout << letters[n] << "\n"; is always to be executed. In the case that b >= length of the array letters. cout << letters[n] << "\n"; is completely not safe. The segmentation fault may come from here. To avoid that, add a condition to t...
68,417,073
68,420,753
How to use one map to store different function
My colleague wrote a very long switch-case function as below: void func(int type, int a, int b) { std::string str = "hello"; switch (type) { case 1: { func1(a, b); break; } case 2: { func2(a, b, str); break; } // hundreds of...
std::any will be your friend. Together with some wrapper class and a template function within the wrapper class, to hide the any cast, it will be some how more intuitive. And it will give you additional possibilities. Please see: #include <iostream> #include <map> #include <string> #include <any> #include <utility> cl...
68,417,205
68,417,277
C++ Template - no matching overloaded function found, could not deduce template argument for 'T'
I am trying to implement a "compare" function. Depends on the input argument, the compare targets can be one of the 2 classes. That is why I am thinking to use template for easier code maintenance. I am new to template, can't figure out what is going on. class Compare_Output { public: static Directory* empty_dir; ...
Templates don't work the way you think they do. To have the interface you want, you need two functions (the helper can be private if you want), like this: template<class T> void Compare_Output::compare_helper(std::vector<T*> t1, std::vector<T*> t2, int level) { int i = 0, j = 0; while (!(i == t1.size() && j == ...
68,417,288
68,462,795
Rendering issue regarding imagery versus functionality
As I understand rendering textures in SDL2, everything is waiting behind the scenes and a texture appears after using the SDL_RenderPresent() function and vanishes with SDL_RenderClear(), which you use before advancing to the next frame. I understand that as far as it goes for imagery, but what about functionality? I h...
I solved this one with some tinkering and a more experienced programmer named mbozzi's help to clue me in the right direction as to what was going on. The underlying issue was due to my completely decoupling the GUI logic and GUI rendering. Which is what we are always told to do: decouple everything, right? But I neede...
68,418,033
68,426,452
How to prepare message before Assertion?
I'm new to the testing, just started with "CppUnitTest.h" (Visual Studio2019). Assert static functions are performing well, example: static void Assert::IsTrue( bool condition, const wchar_t* message = NULL, const __LineInfo* pLineInfo = NULL) but i found that when such a function finally find mistake - it...
First of all: Your code has undefined behavior. Arrays don't automagically grow, so wcscat(msg, iter) will always write out of bounds and _itow(i, iter, 10) for i > 99. I'd go for std::wstring and/or std::wstringstream. But it's also apparent that the code you are testing takes almost no time in comparison to the time...
68,418,690
68,419,039
OpenGL data types for non-Graphics C/C++ code?
Has anybody ever used the custom, "portable" data types defined in OpenGL (C API) header files for non-Graphics related C/C++ programs? (That is, to ensure their data types remained of the same size across compilers/platforms) If anyone has, did you encounter any problems in doing so? Also, would you consider it a viab...
POSIX standard introduces stdint.h header that provides standard fixed width integer types. C99 introduced the same header as a C language standard see cppreference. C++ provides those types as part of std namespace in cstdint This covers integer types. Float types are slightly trickier since both C and C++ language st...
68,418,870
68,418,988
Can 'auto' be used as a subtype of lambda argument in C++?
C++ code with auto as a part of lambda argument type is accepted by GCC, e.g.: #include <vector> #include <iostream> int main() { auto make_vector = []( std::initializer_list<auto> v ) { return std::vector<typename decltype(v)::value_type>{v}; }; auto v = make_vector( {1,2} ); std::cout << v[0] <<...
It looks like it's a bug in GCC. Altough it says it's solved in the version of GCC you're using... You can read here more on why you can't use auto in this context. It was correctly pointed out to me that this case is for a function parameter. It's still not allowed in C++20, see this answer.
68,418,940
68,418,982
Data type error with strings when generating random ipv4 addresses
So, i’m trying to create a loop that generates random ipv4 addresses and it works well except that i’m trying to skip the localhost loopback address "127.0.0.1". I’m assuming it’s a problem with comparing 2 different data types in if (Output == "127.0.0.1") {. Data types are my weakest point in programming and I’ve tri...
You probably want to compare Output.str() As a side note, any address starting with 127. is localhost, so you probably want to filter all of them; and possibly various others, like multicast
68,419,014
68,419,304
Comparison function in c++ error: invalid comparator
I made a simple comaprison function that looks like this: bool function(int a, int b){ if (a % 2 == 0) { return (a > b); } if (a % 2 == 1) { return (a < b); } return false; } My main function looks like this: int main() { vector<int> vector = {8, 4, 4, 8, 4, 1, 4, 4, 6, 10, 12 }...
I'm assuming that you used this comparator in std::sort. Then it must satisfy the requirement Compare: For all a, comp(a,a)==false Ok, your comparator will always return false for equal values. If comp(a,b)==true then comp(b,a)==false That one fails: function(1, 2) == true, so 1 should come before 2, but ... funct...
68,419,027
68,419,506
Is it necessary to implement move constructor for a class without dynamic resources?
I have a container class like the following. As you can see that all the resources that the class use is allocated statically. There are no dynamically allocated resources in the class. Does such a class need a move constructor or move assignment operator? template<class T, std::size_t SIZE> class Stack{ static_ass...
Here's the thing. Your class isn't movable, because it doesn't have dynamically allocated resources. But the resources it contains might. A T, for instance, might be a std::vector in some instantiation. That can surely be moved, so you have to make sure that by providing a copy constructor (you forgot to = default; it ...
68,419,030
68,419,121
How to pass std::optional struct that contains std::unique_ptr to a function?
I am learning how to use std::optional, and I am having trouble passing a std::optional<Type> parameter to a function, since Type contains within it a std::unique_ptr, which prevents the call. What is the correct way to pass such a variable (std::optional<Type>) to a function? Here is a code snippet that easily reprodu...
Your myStruct is indirectly only movable (non-copyable), because of the member std::unique_ptr<int> a;, which is also by default non-copyable (only move is allowed). Therefore the optional variable opt (which contains the struct myStruct) is also indirectly only movable. However, in your function func you are trying to...
68,419,864
68,420,014
runtime error: reference binding to misaligned address 0xbebebebebebec0ba for type 'int', which requires 4 byte alignment
Line 171: Char 16: runtime error: reference binding to misaligned address 0xbebebebebebec0ba for type 'int', which requires 4 byte alignment (stl_deque.h) 0xbebebebebebec0ba: note: pointer points here SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c+...
You are trying to access s2 instead of s1 in this part: while(!s1.empty()) { j=s2.top()+carry; // here if(j<10) { ans.push_back(j); carry=0; } else { j=j%10; ans.push_back(j); carry=1; } ...
68,420,059
68,420,238
std::list push_back unrelated types
Is it possible to push_back to a list of userClass a variable with different type? list<MyClass*>* myList list<int>* NewData // -- ..some population of NewDat.. -- myList->push_back(NewData);
No. What you are asking for is not possible. myList stores MyClass*s, not ints or lists of ints. If you want a generic list, you can use std::list<std::any>, or, in case you know the types in advance, std::list<std::variant<(types here)>>.
68,420,072
68,420,742
Singly Linked List Reversal using Double pointer and Recursion
I tried reversing a linked list using a pointer-to-pointer to the head node being used as a parameter in the function below : void reverseLLRec(Node** start) { Node* curr; // Empty list if (*start == NULL) { return; } curr = *start; if (curr->link == NULL) { *start = curr; ...
Because you alter curr->link by passing its address to the recursive call, the next use of curr->link is no longer referencing the node you intended. You should not let the recursive call alter curr->link. On the other hand, you should alter *start, since that has to refer to the new head (after reversal). So pass that...
68,420,173
68,421,793
Sorting columns of a matrix according to a particular row in c++
Is there a simple way to sort matrix in c++ according to eg. first row, so that all elements rearrange accordingly? Example: int matrix[3][3] = { {5,2,4}, {1,7,8}, {9,2,6} }; After sorting by first row it would look like this: {2,4,5}, {7,8,1}, {2,6,9} Preferably, I'd like to...
As the comments said, it's easier to sort a matrix by a column than by a row, since std::sort with the use of a lambda function will do the job for the former. My recommendation is to sort the column indices by the row, then use the sorted indices to rebuild the matrix: #include <algorithm> using namespace std; const i...
68,420,794
68,421,122
The problem of the definition of transform_view​::iterator's iterator_category?
The standard defines a variety of range adaptors in [range.adaptors], and some of them have their own iterator types. In order to standardize the iterator_category of these iterators, the standard also specifies how they are defined. For example, in [range.transform.iterator-2], the iterator_category of transform_view​...
According to C++20, the iterator category for a transform_view is determined as follows: iterator​::​iterator_­category is defined as follows: Let C denote the type iterator_­traits<iterator_­t<Base>>​::​iterator_category. If is_­lvalue_­reference_­v<invoke_­result_­t<F&, range_reference_­t<Base>>> is true, then if ...
68,420,876
68,425,841
Can't use vcpkg on linux
Here is my CMakelists.txt: cmake_minimum_required(VERSION 3.0) SET(CMAKE_TOOLCHAIN_FILE "/home/xxx/vcpkg/scripts/buildsystems/vcpkg.cmake") project(test) find_package(unofficial-sqlite3 CONFIG REQUIRED) add_executable(main main.cpp) target_link_libraries(main PRIVATE unofficial::sqlite3::sqlite3) I'm trying to use ...
I could not reproduce your issue using the following basic CMakeLists.txt cmake_minimum_required(VERSION 3.21) project(test) find_package(unofficial-sqlite3 REQUIRED) add_executable(main main.cpp) target_link_libraries(main PRIVATE unofficial::sqlite3::sqlite3) I installed sqlite3 via vcpkg install sqlite3 and ran t...
68,420,953
68,421,105
Trie structure, lock-free inserting
I tried to implement lock free Trie structure, but I am stuck on inserting nodes. At first I believed it was easy (my trie structure would not have any delete methods) but even swapping one pointer atomically can be tricky. I want to swap pointer to point to structure(TrieNode) atomically only when it was nullptr so as...
CAS pattern should be something like: auto expected = p->child; while( !expected ){ if (success at CAS(&p->child, &expected, make_null_replace() )) break; } if you aren't paying attention to the return value/expected and testing that you are replacing null, stored locally, you are in trouble. On failure, you nee...
68,421,760
68,423,402
Getting "error LNK2019: unresolved external symbol referenced in function _main" on VScode
I was practising a LinkedList implementation in Visual Studio and the code runs fine in Visual Studio. But since I use vscode most of the time I followed this tutorial from official vscode website. the demo code form the given link builds and runs successfully without any error or warning. but when I try to build my Li...
As neither of the current "Answers" are applicable (One is wrong and the other is very bad practice leading to similar errors later on), here is a solution. Disclaimer: I generally use CMake to create the builds for me meaning I am unfamiliar as to how to do this in VSCode, so this is an unoptimal way of doing it. (The...
68,421,772
68,421,877
Use of undeclared identifier 'kDefaultNative'
I am trying to generate an audio plugin using the ASPIK SDK. I keep hitting the same stumbling block. Every time I build I get the error "Use of undeclared identifier 'kDefaultNative'" on this line in the plugingui.h file. const PlatformType& platformType = kDefaultNative, If I jump to definition of PlatformType, I see...
The kDefaultNative identifier is one of the values of a scoped enumeration (i.e. it's in a class enum { ... }). So, in order to use it, you need to include that class 'scope'. So, use a line like the following: const PlatformType& platformType = PlatformType::kDefaultNative;
68,421,937
68,422,376
GetQueuedCompletionStatus - how to identify the “type” of the finished task?
Can you please tell me, when a ready task appears in the completion port queue, then retrieving it using the GetQueuedCompletionStatus function, how do you know if this ready task is for reading or writing?
A common approach is to write a struct that either derives from the Win32 (WSA)OVERLAPPED struct, or has a (WSA)OVERLAPPED as its 1st data member. Then you can add other data members to your struct to identify its task, track its status, etc as needed. You can then allocate an instance of your struct for each I/O opera...
68,422,115
68,422,175
how to delay a function that is called in a while loop without delaying the loop
imagine I have something like this void color(int a) { if (a > 10) { return; } square[a].red(); sleep(1second); color(a+1); } while (programIsRunning()) { color(1); updateProgram(); } but with something that actually requires a recursive function. how can I call this recursive function to col...
sleep() will cause the current thread to stop. That makes it a bad candidate for human-perceptible delays from the main thread. You "could" have a thread that only handles that process, but threads are expensive, and creating/managing one just to color squares in a sequence is completely overkill. Instead, you could do...
68,422,156
68,422,626
When can the problem actually be fixed by catching an exception?
Here's the thing. There's something I don't quite understand about exceptions, and to me they seem like a construct that almost works, but can't be used cleanly. I have a simple question. When has catching an exception been a useful or necessary component of solving the root cause of the problem? I.e. when have you bee...
I think your problem is that you equate "solve the problem" with "make the program keep going correctly". That is the wrong way to think of exceptions, or error handling in general. Error handling code of any kind should not be something that is internally fixable by the program. That is, error handling logic (like cat...
68,422,262
68,422,600
cmake: setting how a specific file is compiled
In my YOMM2 library, I have a file called lab.cpp (declared in the CMakeLists.txt here), to experiment with new features. Since the library uses complex macro techniques, I would like that specific file to be compiled in two steps: preprocess with -E, sending the output, filtered though clang-format, to an intermediat...
I would like that specific file to be compiled in two steps: How to do that A simple solution would be to add a add_custom_command with the preprocessor, then feed the output to the compiler. cmake_minimum_required(VERSION 3.11) project(test) add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/file.c DEPENDS...
68,422,422
68,422,563
Vector of unique pointers: Finding and then rotating an element to the front of a vector by pointer
Suppose I have a std::vector of unique pointers to an object. #include <memory> struct MyObject { }; std::vector<std::unique_ptr<MyObject> myObjects; Now suppose that vector is populated with some objects, and I would like to rotate a specific pointer to the front. I attempted using the find_if function like this t...
For std::find_if() to compile, the parameter of the lambda must match the object type in the std::vector, which is std::unique_ptr<MyObject> not MyObject, or be implicitly convertible to the argument type, which is not possible in this case. So, the proper way would be: auto pivot = std::find_if(std::begin(myObjects),...
68,422,565
68,422,662
Write a C++ program which capitalizes the first letter of each word in a sentence entered by the user
I wrote the following C++ program to capitalize the first letter of each word in a sentence entered by the user: #include <iostream> #include <string> using namespace std; int main() { char Intstr[255]; char Outstr[255]; fgets(Intstr,255,stdin); int i = 0; Outstr[0] = toupper(Intstr[0]); for (i = 1; In...
The Intstr[i]; condition of the for loop stops the loop before it copies the null terminator (AKA: '\0', or just 0). So, add this one line after the for loop to copy the null terminator to the output C-string too. } // end of for loop Outstr[i] = Instr[i]; // copy the null-terminator too <== ADD THIS LINE cout <...
68,423,399
68,432,396
How to set validation layers from within program rather than env var?
The official vulkan documentation claims: Applications may programmatically activate layers via the vkCreateInstance() entry point. And this is given as alternative to setting an environment variable. However, nothing else is said in this section about how to set them. We can read the official docs of VkCreateInstanc...
Simply VkInstanceCreateInfo::ppEnabledLayerNames enables layers. Layers have to be available before they can be enabled. That can be determined by vkEnumerateInstanceLayerProperties. Obviously, Vulkan is not magic and the Loader needs to know where to look for extensions. That system is outlined in LoaderAndLayerInterf...
68,423,471
68,424,286
MPI & OpenMP: omp_get_max_threads returns half of the true thread capacity
For an unknown reason, when I compile with MPI omp_get_max_threads(), the number of threads returned (12) is half of the capacity my computer has (24 threads, 12 cores). This strange behaviour appeared without reason for two days now, while everything was working well before. I have installed MPI from source. I tried t...
You're misunderstanding what a thread is. A thread is a software construct, having nothing to do with hardware. Try writing a program that prints out the number of threads, and do OMP_NUM_THREADS=321 ./yourprogram It will report both the max and actual number of threads to be 321. If you want something relating to the ...
68,423,609
68,428,624
Kernel Driver: Failed to register callbacks (status=C0000022)
I recently read the book "Windows Kernel Programming" by Pavel Yosifovich. In Chapter 9 - "Object and Registry Notifications" there is a project called "The Process Protector Driver", after I finish the book I try to create this project from 0 and add my upgrades. Every time I was trying to run my driver I got the same...
my mistake was I put the /INTEGRITYCHECK in the Configuration Properties -> C/C++ -> Command Line instead of in the Configuration Properties -> Linker -> Command Line The problem solved.
68,423,757
68,423,850
C++ overloaded delete operator for array of pointers not being called
The delete operator is not being called. Any direction would be helpful. I am using Visual studio 2019. I did look at the link overload delete[] for array of pointers, but was not able to resolve my issue. Thank you for any help! #include <cstdio> #include <cstdlib> #include <new> // replacement of a minimal set of fun...
You're not providing an overload for operator new[](size_t sz), so you're lucky that your operator new(size_t sz) is being called at all. The compiler is calling the unsized versions delete[], so you need to provide a operator delete[](void *ptr) noexcept function. Note that the standard requires the non-size version t...
68,423,775
68,423,882
Intellij Rider: How to configure your run / debug configuration to execute another app exe with your dll
Trying to setup rider to execute a compiled .exe program to run with my dll. My dll is a proxy dll. I know how the compiled dll looks like and it works fine when added to the project directory. But now I want to debug it and it needs debug configuration so that it will be pointing to external exe, which will load my dl...
Apparently it is .NET Executable configuraiton for C++ projects. Simply specifying the path to an external exe file and specifying working directory to be the same directory where exe (and compiled dll) is, makes it work.
68,424,195
68,424,209
Is there a way to get the return value of the overloaded operator-> rather than its member value?
Let's say I have a class with an overloaded operator-> which returns a pointer. However, the usage of -> requires member after it, but can I not provide the member? Is there a way to get the return value directly? Here is a code snippet to demonstrate my question: I am wondering if there is a way to get the value of pt...
Yes there is. You can simply do, for example: cout << wrapper.operator->();
68,424,270
68,424,329
Passing array through constructor of class to set as instance variable
I have done some Java programming before where you can pass an array through the constructor of a class to initialize it. public class Student { int age; String name; int[] classIds; public Student(int age, String name, int[] classIds) { this.age = age; this.name = name; this.cl...
So I think your question actually has a deeper answer in that, C++ does not have arrays as first class objects. This means that an array is a series of memory addresses of some size and type, that either exists on the stack, on the heap, or in the data segment of an executable. So in your Java code: int[] classIds = {1...
68,424,309
68,424,421
Make type of vector arbitrary
I'm currently implementing a simple stack in c++17, which has to have a toString-Method, that can deal among other types with std::vector as the template type. My original problem was, that std::to_string can't accept vector's to I added a specialized implementation for vector's on top of my normal implementation: temp...
Something along these lines, perhaps: template <typename T> std::string MyToString(const T& val) { return std::to_string(val); } template <typename T> std::string MyToString(const std::vector<T>& vec) { std::string vecAsString = "Vector{"; for (const auto& value : vec) { vecAsString += MyToString(value) + ",...
68,424,625
68,424,717
What happens when a thread is constructed, and how is the thread executed
I'm completely new to multithreading and have a little trouble understanding how multithreading actually works. Let's consider the following example of code. The program simply takes file names as input and counts the number of lowercase letters in them. #include <iostream> #include <thread> #include <mutex> #include <...
You seem to be under the impression that the program can only be running one thread at a time, and that it needs to interrupt whatever it's doing in order to execute the code of the thread. That's not the case. You can think of a thread as a completely separate program that happens to share memory and resources with th...
68,424,925
68,425,008
How to get the current time and date C++ UTC time not local
I would like to know how I can get the UTC time or any other timezone (NOT just local time) in C++ Linux. I would like to do something like: int Minutes = time.now(Minutes) to get and store the year, month, day, hour, minute and second at that exact time. How I can do so? I will need to repeat this process many time; I...
You are looking for the gmtime function in the time.h library, which give you UTC time. Here's an example: #include <stdio.h> /* printf */ #include <time.h> /* time_t, struct tm, time, gmtime */ int main () { time_t rawtime; struct tm * ptm; // Get number of seconds since 00:00 UTC Jan, 1, 1970 and st...
68,425,143
68,425,218
C++ template specialization with CMake
I've read through a bit of the ISO (https://isocpp.org/wiki/faq/templates) but am having trouble understanding a simple template specialization example I've come up with that only fails to work when using CMake. Here is my example: // generic.h #pragma once #include <iostream> using namespace std; template <typename...
You have to tell the compiler there is a specialization. Otherwise, it chooses the first one linker finds. // generic.h #pragma once #include <iostream> using namespace std; template <typename T> void f() { cout << "Generic" << endl; } template<> void f<int>(); // when int, use this I've read through a bit of...
68,425,402
70,136,535
How to get Raspberry Pi CPU temperature in C++
I would like to know if there is a way to get the raspberry pi's CPU temperature in C++ code, I'm using a Raspberry Pi 4b. Any help is really appreciated!
something like this, .... ... td::string fileName = "/sys/class/thermal/thermal_zone0/temp"; std::ifstream piCpuTempFile; float piCpuTemp = 0.0; std::stringstream buffer; piCpuTempFile.open(fileName); buffer << piCpuTempFile.rdbuf(); piCpuTempFile.close(); piCpuTemp = std::stof(buffer.str()); // convert string to float...
68,425,608
68,434,035
Xcode can't find files that exist (using c++ fopen)
I've been running into this strange problem lately where in my Cocoa app project in Xcode I get the error that the file was not found when using "fopen" (errno 2), called from a C++ file. I made sure to copy these files into the project's directory, then I dragged them from the Finder directory into the Xcode project t...
Cocoa apps do not work with files the same way as command-line C++ apps. Cocoa apps create an app bundle, which is where the files you want to read should be. If you have files you want to read in a Cocoa app, add them to the project. When you add the files to the project, they will get copied to the app bundle. Make s...
68,425,726
68,431,689
Alternatives to templating the whole class
struct S { S(int); S(std::string); void foo(int); void foo(std::string) }; So my problem is that foo() should be invokable only with the type the ctor was. Solutions I can think of and problems with them: Template the whole class. However this brings all the implementation details to the header, poll...
Morally, your class is a template, but will only be instantiated with a type from a finite, known set of types. Your question is how to avoid some disadvantages of templates you identified: implementation details leaked, larger translation units, unintelligible API, and worse error messages. The most straightforward wa...
68,425,760
68,426,067
How to make functions variables public, they are not in a class C++
I would like to know how I can make a function's variable public to other functions. Example: void InHere { int one = 1; // I want to be public } int main() { InHere(); // This will set int one = 1 one = 2; // If the variable is public, I should be able to do this return 0; } Does anyone know how to do...
A variable defined locally to a function is generally inaccessible outside that function unless the function explicitly supplies a reference/pointer to that variable. One option is for the function to explicitly return a reference or pointer to that variable to the caller. That gives undefined behaviour if the varia...
68,425,833
68,430,402
Implementation of Bottom Up Merge Sort
I've learned that Merge Sort is a sorting algorithm which follows the principle of Divide and Conquer and it have average time complexity as n(log n). Here I've divided the array of size n in sub array (initializing with length 2) and conquered it by sorting the sub arrays. Then we proceed the range with multiple of 2 ...
A pure bottom up merge sort divides an array of n elements into n runs of size 1, then each pass merges even and odd runs. Link to wiki example: https://en.wikipedia.org/wiki/Merge_sort#Bottom-up_implementation As suggested in the Wiki example comments, the direction of merge can be changed with each pass. To end up wi...
68,425,972
68,425,987
define an array based on constexpr array transform
Is there a way to define a new array by transforming from an existing array, where both arrays are compile time known constexpr arrays, like this: constexpr array<string_view, 3> arr{"foo", "bar", "alpha"}; for (auto o : arr) { std::cout << ' ' << o; } std::cout << '\n'; constexpr array<size_t, arr.size()> arr2{0}; ...
You can write a function that returns an array and use that to initialise the constexpr variable. Example: constexpr auto make_the_array = [=] { std::array<std::size_t, arr.size()> temp_arr{0}; auto get_size = [](auto e) { return e.size(); }; std::transform(arr.begin(), arr.end(), temp_arr.begin(),...
68,426,339
68,426,427
How does the logic OR operator work inside of a while loop in C++?
I have a while loop using a logical OR operator, but I can only ever get one of the conditions to close the loop. while (hourTime <= 23 || input != 4) What I mean by that is the condition checking the 'hourTime' variable works by itself and so does the condition checking the 'input'. But when I combine them using the ...
The operator is working just fine. The loop continues if either condition is met. It exits if both conditions are violated. (That's just paraphrasing DeMorgan's Theorem). If you want it to exit if any one condition is violated, then you should be using the "logical AND" (&&) operator.
68,427,029
68,427,127
What is the need for a library in C++?
Header files contain only the declaration of the function and the actual implementation of the function is in the library. If they don't want to share source code they can share the obj file. Why do we use a Library when the implementation of a function can also be done in another C++ file?
Usually, a library is a collection of several translation units. A library archive is simply a convenient way to bundle the separate object files into one blob. Besides that, shared libraries add the ability of dynamic loading and sharing of commonly used libraries between multiple dependents which isn't possible with ...
68,427,246
68,427,294
Vectors to Priority_queue in STL c++
How to convert a vector v to priority_queue pq? Like we can do as- for(int i=0;i<(int)v.size();i++) pq.push(v[i]); But is it possible to keep it more short and concise?
priority_queue<int>pq(begin(stones),end(stones));
68,427,602
68,434,649
Inserting a Smart Pointer in a Unordered Map calls destructor
I'm making an engine and to handle materials stuff I have a static renderer class storing a static std::unordered_map<uint, Ref<Material>> m_Materials; (a material and its ID), being Ref the a shared pointer using the next methods: template<typename T> using Ref = std::shared_ptr<T>; template<typename T, typename ... ...
Try calling insert_or_assign; if the key already exists, insert will simply destroy the object you are trying to insert. As an example m_Materials[0]; m_Materials.insert({0, std::make_shared<Material>(name)}); the shared_ptr will be discarded, because the first [0] created a nullptr value, and the insert later sees i...
68,427,709
68,427,987
Use of overloaded operator '<<' is ambiguous
I am writing a class float32x4_t that mimic the ARM NEON datatype on x86 platform. There are 4 elements in its object. I would like to cout an float32x4_t instance (print out comma separated 4 elements), but my overloaded function failed to compile. My code is: #include <iostream> struct float32x4_t { float val[4]...
Your template operator << is trying to provide overloads to everything; not just your types (and unintended matches are ambiguous as a result). There are many ways around this, but since you're already defining your own types and the whole goal of this is to minimize the number of operator << overloads you must write t...
68,427,785
68,433,046
Why are many curly brackets treated differently by C++ compilers?
In the following C++20 program I put by mistake one extra pair of curved braces {} in B{{{{A{}}}}}: #include <iostream> struct A { A() { std::cout << "A() "; } A( A&& ) = delete; ~A() { std::cout << "~A() "; } }; struct B { std::initializer_list<A> l; }; int main() { [[maybe_unused]] auto x = B{{{{A{...
B{…}, since the single element of the initializer list is not designated and is not of type B (as it has no type at all), is aggregate initialization ([dcl.init.list]/3.4). B::l is thus copy-initialized from {{{A{}}}}; it's a specialization of std::initializer_list, so /3.6 and /5 apply. An "array of 1 const A" is cr...
68,427,934
68,467,077
How to perform real time face detection in Windows 10 camera application?
I have been trying a long time to integrate Open Vino Face dectection ADAS model into the MFT pipeline so as to make my Windows 10 camera application detect faces at real time. But nothing worked out. I am using visual studio 2019 and trying to code in C++ to develop a driver for the camera that does the face detection...
You may use the Object Detection Demo application in the OpenVINO toolkit to run the face-detection-adas-0001 model. You need to download the model and convert it to OpenVINO Intermediate Representation format. Then, run the demo by using the following command: python object_detection_demo.py -i 0 -m "<INSTALL_DIR>\ope...
68,428,103
68,431,002
How to create a Makefile for a C++ project with multiple directories?
I want to create a Makefile for a project with the following layout: Source files (.cpp, potentially .c) in /src, with potential subdirectories Header files (.h, .hpp...) in /inc, with potential subdirectories Object files (.o) in /obj, with potential subdirectories External libraries in /lib Compiled program in /bin ...
As @JohnBollinger points out, you are attempting too much at once. I will suggest a few changes to get your makefile off the ground. I can't explain the error you get when you try to build the executable (you haven't given us enough information to reproduce the error), but it doesn't look like a Make problem. I suggest...
68,428,150
68,428,425
How to deal with base class methods that are incompatible with the derived class?
Imagine that you're making a GUI and have a DataViewList class that is a widget that displays rows of data (like this for example). You have methods AddRow(std::vector<std::string> row), DeleteRow(std::vector<std::string> row) and AddColumn(std::string name), DeleteColumn(std::string name). Now lets say you want to mak...
Let's step back and look at your design again: class DataViewList { using Col = std::string; using Row = std::vector<std::string>; virtual void addRow(Row) = 0; virtual void deleteRow(Row) = 0; virtual void addColumn(Col) = 0; virtual void deleteColumn(Col) = 0; virtual void draw(Context) = ...
68,428,283
68,428,513
Can a class definition from one .lib supplant or extend a definition from another .lib?
I have a Commons.lib project I stick a lot of my reused code in, that has gotten too big for it's own good (breaking a parser in it would halt work in 20 unrelated projects, stuff like that). I'm splitting it up to better isolate it's components but have ran into many small ... I guess "coupling" problems? For example...
Barring extension, would it be possible to instead supplant the definition of Color in CommonsCore.lib with the definition of Color in CommonsSDL.lib? You could change the sources of CommonsCore.lib to use the new definition of Color and recompile the library. Other than that no, it wouldn't be possible. And that cha...
68,428,749
68,428,819
Why does the following result in segmentation fault?
const int* additional(int* s, int* f){ const int* ts = reinterpret_cast<const int*>(*s + *f); return ts; } int main() { int a = 10, b = 20; const int* oc = additional(&a, &b); std::cout << *oc; return 0; } I've tried using static, although it produces the same error
There are many things wrong with your code. *s + *f is an int, not a pointer (you add the dereferenced values). you are doing a reinterpret cast which isn't needed at all. Just pass the int's directly without pointers and you are good to go. const int additional(int s, int f){ return s + f; } int main() { int a...
68,429,008
68,429,043
Polymorphism in child class
My goal is to create a method use(string) in the child class which has the same name as in the parent class use(int). But the compiler throws the error below: error: no viable conversion from 'int' to 'std::string' (aka 'basic_string') My code: #include <iostream> #include <string> using namespace std; class Parent...
Inside Child add: using Parent::use; Class member lookup in overload resolution halts when it finds one. A using statement pulls it down into Child.
68,429,096
68,429,391
How to pass a 2-D array whose size is user-defined
so this is my function it basically takes the 2 indexes and the 2D array and adds the weight to the intended place. void AddEdge(int Vertex1Index, int Vertex2Index, int weight, int Edge) { if (Vertex1Index==-1 || Vertex2Index==-1) // in case of invalid vertex { return ; } Edge [Vertex1Index][Ver...
That would probably be better in a comment but I don't have the reputation for it.. Do you really need your array to be physically 2D? What I mean is: you can define a matrix with fixed size (A[ROWS][COLS]) and access in the A[i][j] fashion or define a big array (single dimension) with size ROWS*COLS, even dynamically,...
68,429,122
68,429,174
Copy conversion to standard containers in C++
This question is a continuation of How to convert an array into a vector in C++?, where I was suggested to use very tricky technique with a few sizeof() manipulations. Actually I expected to find some function in standard library to convert an array into any container. I tried to write one by myself and it does not loo...
You can use range-v3's ranges::to: #include <range/v3/range/conversion.hpp> #include <list> int main() { int myArray[2] = {1, 2}; auto myVector = ranges::to<std::vector>(myArray); auto myList = ranges::to<std::list>(myVector); return myList.size(); } Demo.
68,429,159
68,429,180
Unable to execute a file in linux
I have created a program in which fopen() is being used. For Ex:- int main() { FILE* check=NULL; check=fopen("C:\\Files\\open.txt","rb"); if(check==NULL) { cout<<"Error"; } else { //do something } } Now, in the above program windows path is working properly i.e. "C:...
Try adding perror("fopen") to the main function and please share the output. It is difficult to answer this question without the output. I think the problem may be: You don't have permission to access /mnt or no such file or that file doesn't have read permission... etc.
68,429,342
68,430,622
Is it exception-safe that return the right value which is return of function in c++?
Is it exception-safe that to return the right value which is return of function in c++? For example, template<typename Iterator, typename T> T my_accumulate(Iterator first, Iterator last) { return std::accumulate(first, last, T()); }; At above code, std::accumulate can throw. What happen if std::accumulate throws?...
What happen if std::accumulate throws? The temporary T is destroyed (just like if returned normally) and the exception is propagated to the caller. T() can make memory leak? Not unless the class T itself is horribly broken. or is it safe for some reason? The function is exception safe.
68,429,360
68,429,417
How to store the text from a .txt file into a variable
I want to save the text from a .txt file as a char variable on C++. I have tried: char fileData; fstream myFile; myFile.open("file name"); fileData = myFile; myFile.close(); cout<<fileData; But it is wrong, I get an error invalid user-defined conversion from 'std::fstream {aka std::basic_fstream<char>}' to 'int' [-fpe...
After opening a file, you also need to read it in order to obtain its data in a variable. Also, I noticed that you didn't specify if you were reading a file, or writing to a file. You can obtain the contents of the file in this manner: myfile>>fileData; You can specify whether the file is to be opened in read mode or ...
68,429,406
68,429,629
Why does the "GetDeviceCaps" Function always return exactly half of the size of my screen?
I've been trying to get the screen size with <Windows.h>'s GetDeviceCaps(GetDC(NULL), HORZRES) function, but whenever I run the code, it always returns exactly half of my screen resolution. Does anyone know why this may happen to my computer? It works fine on most other monitors. My screen resolution is (2736x1824) (su...
Your program is almost certainly 'suffering' from DPI Awareness issues. Running your code on my system presents similar issues; however, adding a call to the SetThreadDpiAwarenessContext function resolves the problem: #include <Windows.h> #include <iostream> int main() { SetThreadDpiAwarenessContext(DPI_AWARENESS_C...
68,429,472
68,429,541
Why are malloc-allocated memory values assigned with i++ instead of i+4 (in the case of an int being 4 bytes large)?
My mind is confused and blown right now and hopefully someone can help me deconfuse it /put me on the right path again. Correct me if I'm wrong but in C, you use malloc to 'reserve' / get a certain amount of space in memory in bytes. So int* ptr = malloc(10 * sizeof(int)); would allocate 40 Bytes of memory / assign a p...
Pointer arithmetic, and memory allocation, are two different things. Pointer arithmetic is always done based on the type of the pointed-to object. That is, pointer arithmetic always incorporates an automatic, implicit multiplication by that size. So int *p; /* ... */ p++; is always going to increment the address in ...
68,429,546
68,429,612
How to declare a string from multiple string variables C++
I want to know how I can declare a string from multiple string variables. Example code: std::string one = "one1"; std::string two = "two2"; std::string three = "three3"; std::string OneTwoThree = (one, " ", two, " ", three); // Here I want to save it as "one1 two2 three3" std::cout << OneTwoThree; Any help is really ...
You can do it by adding all three strings as std::string OneTwoThree = one+" "+two+" "+three;
68,429,634
68,430,167
Rendering single thing without having to clear entire screen in sdl
Are there layers to sdl or something? by layers I mean like in photoshop we have multiple layer and can draw on one without effecting the other, for example if I had a main_layer , a background_layer & an enemy_layer where the main player reandering (like moving the character by user), a static background rendering & e...
You can implement your own layer system using render targets. Create a texture render target for each layer. Draw to a layer's render target to update it. Every frame, draw each layer to the screen. You still need to clear the final frame beforehand. It's worth noting that there is a point of diminishing return here....
68,430,267
68,430,377
Does C++ memset only works for 0 and -1?
int a[2]; memset(a, 3, sizeof(a)); when I run this I am getting output as 0 1. Why not 3 3
Does C++ memset only works for 0 and -1? It does work for all byte values. int a[2]; memset(a, 3, sizeof(a)); when I run this I am getting output as 0 1. I doubt that. Either your system is broken, or you made a mistake. Why not 3 3 Because that's not what std::memset does. It sets every byte to the value that ...
68,430,644
68,430,677
using memset and freeaddrinfo causes the double free or corruption error
src.cpp #include <iostream> #include <cstring> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> int main(){ struct addrinfo hints, *servinfo; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; getaddrin...
freeaddrinfo(&hints); This is expected behaviour (in the way that it the behaviour is undefined; not in the way that you could rely on this behaviour). You may only pass structure created by getaddrinfo into freeaddrinfo. You didn't create &hints with getaddrinfo. Don't pass hints into freeaddrinfo. A fixed example:...
68,430,681
68,430,914
makefile for c++ compilation not running
I've made a makefile to compile program calc.cpp: SRCS=calc.cpp OBJS=$(subst .cpp,.o,$(SRCS)) FLGS=-std=c++17 all: calc clean calc: g++ $(SRCS) $(FLGS) -o $(OBJS) ./calc.o clean: rm -f $(OBJS) However, I'm getting some strange errors: when I make all, it only prints rm -f calc.o if I remove...
This rule: calc: ... tells make how a target calc can be built and that it has no prerequisites. This means that if the file exists, make considers it up to date (how else, since it doesn't depend on anything)? So presumably you have a file named calc already existing in your directory, so when you run make ...
68,430,825
68,431,578
What doest `vaddhn_high_s16` actually do?
There is vaddhn_high_s16 intrinsic for arm64. The official ARM documentation for this intrinsic is here. However, the given description, and pseudo code, all make me confusing. Can anyone using practical C/C++ code to explain what does vaddhn_high_s16 do? For example, assuming all datatypes are defined, and vmulq_f32 i...
The documentation of the underlying addhn2 instruction in the ARMv8 Architecture Reference Manual helps clarify things. This is usually a good resource for questions about intrinsics. The main purpose, of course, is to add 16-bit values and keep only the high 8 bits of each result. The addhn2 form writes the result t...
68,430,952
68,430,990
Why can't a++ (post-increment operator) be an Lvalue?
Code #include<iostream> int main() { int a=3; a++=5; std::cout<<a; } Output (as expected) [Error] lvalue required as left operand of assignment 1. The post increment operator (a++) has the highest priority in the table. So it will definitely execute before the assignment operator (=). And as per the rule ...
And As per rule of post increment the value of variable a will increment only after execution of that statement. That's a bit misleading. The variable is incremented immediately. But the result of the expression is the old value. This should make it easier to understand why it cannot be an lvalue. The modified object...
68,431,080
68,431,143
How to deep copy in initialization List incase of const variable
I know deep copy in constructor can be done in following way. class student{ public: int age; int rollno; char *name; student(int rollno,int age, char *name){ this->age=age; this->rollno=rollno; //deep copy this->name=new char[strlen(name)+1]; s...
You should be using std::string to store strings. With it, your class looks like this: class student{ public: const int age; int rollno; const std::string name; student(int age, int rollno, std::string name): rollno(rollno), age(age), name(std::move(name)) {} }; Not only does this give you exa...
68,431,212
68,431,732
While coding addition of two polynomials in c++ , I could compute the addition when no and order of terms are same . It shows error when its diff,why?
Here I have tried to code addition of two single variable polynomials in c++ . The code runs fine when both the inputs are in sync with the other . But when it ain't it shows some crazy stuff happening and prints complete gibberish . I am pasting my code here with the output . Any suggestions would be helpful . My Code...
The main mistake in your code is this line: sum->terms[k++].coeff = terms[i++].coeff +p2.terms[j++].coeff ; and, more precisely, its location in the whole routine. Namely, it is located past the if - else if - else construct. As a result, it is executed despite exponents satisfy the 'less-than', the 'greater-t...