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 |
|---|---|---|---|---|
66,252,397 | 66,252,445 | C++ out of range exception not firing | It's been a while since I've worked in C++ and I'm having some issues understanding why an out-of-range exception is not firing.
See the try below. I'm intentionally tripping it but in debug mode, it's breaking on that line, rather than falling into the catch as I would expect.
Nothing I've read over the last hour has ... | By design, a debugger sees all exceptions before the executable code does. This allows you to analyze and potentially fix any problems related to the exception before continuing, or to just end execution, etc.
To let the catch work inside a debugger, simply tell the debugger to continue execution once it breaks on an e... |
66,252,776 | 66,252,887 | It it UB to read some contiguous array cells as a larger type? | char foo[n] = /*init here*/; // n = 4*k + 4.
int i = 0;
while (i < n) {
int four_bytes = *reinterpret_cast<const int*>(foo + i); // is this UB?
bar(four_bytes);
i += 4;
}
In this snippet of code (assuming all data is initted properly, and that the array's length is a multiple of ... | Alignment
It is UB when the char foo[n] is not sufficiently aligned as an int array.
Size1
When 0 < n < sizeof(int), *reinterpret_cast<const int*>(foo + i); attempts to refence outside foo[].
1 Did not see "array's length is a multiple of 4" until later. Yet this still applies on unusual platforms where the sizeof in... |
66,252,783 | 66,253,387 | Starting VS2019 and either starting profiler or skipping welcome screen | I often use VS 2019 (16.8.5) to profile applications developed with Qt on Windows (10). I've got it configured as an external tool in Qt Creator.
However, every time I open it by just running devenv.exe, I have to go through the same process of clicking "Continue with No Code" on the startup welcome screen, then select... | You can start VS and open the profiler like this:
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\devenv.exe" /Command Debug.DiagnosticsHub.Launch
|
66,252,868 | 66,253,154 | Can you check if an F key (F1, F2, etc) is being pressed with a standard C++ function? | I'm trying to develop for both Windows and Linux (Ubuntu/Debian specifically) in C++, and I need to detect when an F key is pressed by another application. I want to change as little code as possible to migrate it across OS's, so can I check if an F key (F1, for example) is pressed with a std function? Can I use std::c... | No, there is no such API in the std library.
|
66,252,878 | 66,252,940 | C++ wrong result in multiplication of two unsigned long long integers | Consider the multiplication of the following unsigned long long integers:
unsigned long long a=4294967297;
unsigned long long b=4294967297;
cout<<a*b<<endl;
8589934593
I did not expect this answer. Instead I was expecting to get:
18446744065119617025
Note that, according to this source, the largest integer that ca... | I think you're doing your math wrong:
slowpy3.8> 4294967297 * 4294967297
18446744082299486209
slowpy3.8> hex(_)
'0x10000000200000001'
slowpy3.8> 0xffffffffffffffff > 0x10000000200000001
False
slowpy3.8> math.log2(18446744082299486209)
64.0000000006718
slowpy3.8>
|
66,253,655 | 66,253,920 | Why is my window resized to smaller than its minimum size by a wxBoxSizer | I create the main window of my application with
Main::Main() : wxFrame(nullptr, wxID_ANY, "Test", wxPoint(64, 64), wxSize(1024, 768))
In this window I place another window of type View whose constructor looks like this:
View::View(wxWindow* parent) : wxHVScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSiz... | Just call SetSizer instead of SetSizerAndFit. The documentation for SetSizerAndFit says this:
This method calls SetSizer() and then wxSizer::SetSizeHints() which sets the initial window size to the size needed to accommodate all sizer elements and sets the minimal size to the same size
However a scrolled window won'... |
66,253,660 | 66,253,910 | Implementing an alphabet in C++ | I'm making a code for cipher that reads alphabet in it's binary code. Is there a way to implement custom alphabet (not using ASCII)? For example alphabet={a,b,c,d,e,...,z,],[,.,..., ,-} and for each character there's a number 0,1,...,63. So, the bijetion will be from element of alphabet to 6 bit number.
How to make thi... | I made a simple class Alphabet achieving your task. It uses std::unordered_map to store mapping between characters and binary representation, and uses this mapping to convert between those two representations. Also it computes binary representation. Class can be given any alphabet.
For testing I do two conversions betw... |
66,253,869 | 66,253,924 | Multiplying string by a const int C++ | #include <iostream>
#include <string>
using namespace std;
int main() {
//declaring cin inputs
string userName;
string userMiles;
string userSteps;
//declaring constant for number of steps/mile
const int stepsPerMile = 2000;
//getting user's name
cout << "What is th... | Read in userMiles and userSteps as integers, not as strings. operator>> can read in many different types, not just std::string. Try using int instead, to match your stepsPerMile constant, eg:
#include <iostream>
#include <string>
using namespace std;
int main() {
//declaring cin inputs
string userName;
in... |
66,254,082 | 66,254,139 | Passing a template's template member type as a template template argument | A class WithTTMember has a template member type named TT.
struct WithTTMember {
template<typename> using TT = void;
};
Another class ExpectTT takes a template template parameter:
template< template<typename> typename TT >
struct ExpectTT {};
ExpectTT<WithTTMember::TT> can be successfully instantiated.
A third cla... | You should use template keyword to tell that T::TT is a template.
template<typename T>
struct ExpectTWithTT {
using X = ExpectTT<T::template TT>;
// ^^^^^^^^
};
|
66,254,480 | 66,266,334 | LLDB: restart an appliation in the same session (and keeping all memory/context) upon hitting a signal? | Say I'm in the middle of a function and LLDB stopped on a segfault (bad memory access).
Is it possible to clear the signal, and return to main, and re-execute everything? (If the code has made any stateful changes, i would expect those to be kept).
I'm not asking to kill and restart the process in a new session.
(Not s... | lldb has a thread return command that pops frames off the stack. That will return to a point just after the call that was active in the stack frame you returned to, so you have to use thread jump to put the pc back on the call site.
Doing this will leave the memory state intact, so anything accessed from a global or s... |
66,254,530 | 66,254,575 | How to pass a string iterator to other functions | I have this code which tries calling count with a std::string iterator but it fails with a compilation error.
#include <iostream>
#include <algorithm>
int count(std::string::iterator iter, char ch)
{
int n = 0;
while (*iter == ch) {
n++;
iter++;
}
return n;
}
void search(std::string co... | str is marked as const, then the iterator taken from it, i.e. the type of iter is std::string::const_iterator, which can't be converted to std::string::iterator implicitly and passed to count.
Since count won't modify element pointed by iter, you can make count taking const_iterator too.
int count(std::string::const_it... |
66,254,795 | 66,254,825 | What is different between two codes of for loop? | #include <vector>
#include <iostream>
using namespace std;
int main(void)
{
vector<int> a = {1, 2, 3, 4, 5};
for (auto &x : a)
cout << x << endl;
}
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
vector<int> a = {1, 2, 3, 4, 5};
for (auto x : a)
cout << x <... | There is no difference in the output for the code you wrote. However, if you tried to change the value of x when in the loop, there would be a difference.
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
vector<int> a = {1, 2, 3, 4, 5};
for (auto x : a)
x = 0;
for (auto x... |
66,254,907 | 66,255,219 | Parameterize of tuple with repeated type | I want to declare template:
template <size_t N, class Type> my_tuple
{
using type = ... //something here
};
So that this my_typle<3, std::string>::type,for example, will be the same as this std::tuple<std::string, std::string, std::string>
Please, show, how it can be done in one line, maybe, using std::index_sequen... | This is fun. Here's a "pure" meta-programming approach to expand the sequence:
template<typename T, typename Seq>
struct expander;
template<typename T, std::size_t... Is>
struct expander<T, std::index_sequence<Is...>> {
template<typename E, std::size_t>
using elem = E;
using type = std::tuple<elem<T, Is>.... |
66,254,948 | 66,255,140 | c++ is there any possibility that `map.end()` can change during the life time of a `std::map` | just wondering if I have a map declared like this,
map<int, int> my_map;
and assign end() iterator to a variable, and never change,
auto end_it = my_map.end()
Then later I will change my_map by having many erase and insert of my_map,
will the below always stays true during the life time of my_map?
end_it == my_map.en... | std::map::insert guarantees:
No iterators or references are invalidated.
std::map::erase guarantees:
References and iterators to the erased elements are invalidated. Other references and iterators are not affected.
Therefore the end iterator should stay valid. If you use any other operation, you should check whethe... |
66,256,167 | 66,256,497 | Is there a way to swap 2 structs? | In c++ you can swap 2 numbers without 3rd variable:
int x = 10;
int y = 5;
x ^= y;
y ^= x;
x ^= y; //x = 5, y = 10
So I wonder if there is a similar way to swap 2 structs without 3rd variable:
struct Position{int x, y;};
int main()
{
Position firstPose{x = 10, y = 5;};
Position secPose{x = 5, y = 10;};
//No... | There is no a standard way to swap two structure without an intermediate copy. Arguably, one of the main benefit of swap "is" the intermediate copy, this wonderful article explain how swap is a crucial part to achieve "strong exception guarantee". https://www.stroustrup.com/except.pdf
Furthermore, if the goal is to not... |
66,256,199 | 66,256,305 | Is the syntax used in Arduino entirely C++ or is there some special syntax occassionally | // the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); ... | Because in the main function there is
int main(void)
{
/* .... */
setup();
/*.......*/
for(;;) loop();
The main is hidden from you. There is no magic, setup and loop are normal functions called from 'main'. Everything is very simple.
Arduino is just C++ and g++
The main function in arduino is declared a... |
66,256,583 | 66,256,922 | how to sort A CLASS (not a struct) of objects by its different attributes? | Edit here is my code:
class Book{
private:
int Serialnumber;
string Author; // I also have getters and setters for them
}
class Library{
vector<Book> inventory; // I added some books in the vector Inventory
}
I also have 2 header and 2 .cpp files for both classes. included both the headers in each .cpp files and decla... | in c++ there is no significant difference between class and structure. Basically, all the difference is in the perception of the programmer and the default access rights, so you can sort them simply by the function std::sort and writing for it 2 different comparators
so my implementation would looks like this(NOTE: you... |
66,257,117 | 66,257,795 | Parallel Selection sort with multithreading | I have Selection sort function
inline void selection_sort(double* arrayPtr, int length_array)
{
for (auto i = 0; i < length_array; i++)
{
for (auto j = i + 1; j < length_array; j++)
{
if (arrayPtr[i] > arrayPtr[j])
{
std::swap(arrayPtr[i], arrayPtr[j]);
... |
How to optimize it with multithreading? I found solutions only for
quick sort but but these solutions did not help me.
You cannot find much information about it because it is not a good idea to do so. It will not be efficient, the parallelization of the selection sort has some of the same issues as the parallelizatio... |
66,257,473 | 66,258,450 | Cpp swapping dimensions within multidimensional vector | Hey I´m sorry if this question was already asked or other answers could be combined to approach what I´m looking for. But I´m fairly new to Cpp and the STL stuff can be quite overwhelming, so don´t be too judgy please and link me to the corresponding answers please. I´m glad if someone can help me:
I have a multidimens... | As said in comment, you could use 1 flat vector to store all your data, and specific sorting functions to access it in the order you want. Here's an example with unrelated (but clearer) data structure to illustrate:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <numeric>
struct ... |
66,257,638 | 66,257,724 | program print out numbers with an interval (5500) that are divisible by 2 and 3 (c++) | I am stuck on how to do this I am also required to use for loop
I'm not asking you guys to write this whole programming but please tell me where to start from
this is one idea I had but it doesn't really work
#include <iostream>
using namespace std;
int main()
{
int i, n;
cout<<"enter a number";
cin>>n;... | Your loop condition seems to be wrong:
for (i=0; i<=n; i+=5500)
This loop starts at 0, stops at n, and increments i by 5500 after each iteration.
To iterate all numbers starting at 0 till n :
for (i=0; i <=n ; ++i)
Its not clear where the 5500 comes into play. Either you loop until n or until 5500, not both.
|
66,257,718 | 66,257,785 | Is is valid to use a variable previously void casted? | It looks like this code is acceptable with gcc even though the standard states that the value of the expression is discarded in case of a void cast.
#include <iostream>
int f(int i) {
int a = i*2;
(void)a;
a++; // looks OK even after void cast
return a; // looks OK even after void cast
}
int main() {
... | The result of the expression is discarded, which, in your case, means that the result of (void)a is discarded. This is usually used to avoid unused variable (or unused return value) warnings. It is perfectly fine to use a after (void)a, but there's no point to do the (void)a in the first place.
EDIT: To address some co... |
66,257,871 | 66,258,035 | push_back using the move constructor does not call the destructor? | The following code creates a temporary object A and pushes it into a vector.
The copy constructor is deleted and the move constructor is called during the push_back. I am not sure the design of this code is correct, and surely there is a memory leak.
#include<iostream>
#include<vector>
using namespace std;
class A
{
p... | As pointed out in a comment, your problem lies here:
~A()
{
cout << ptr << " Destructor\n";
delete[] ptr;
ptr = nullptr;
}
By the time you reach the destructor the object has already been moved from and ptr == nullptr. The char* overload of << expects a null-terminated string. If ptr does not point to a null-ter... |
66,258,554 | 66,258,684 | Basic Class Inheritance in C++ | I am typing the following code and I am getting the following error at line-1
[Error] no matching function for call to 'int_adder::add()
#include <iostream>
using namespace std;
class adder{
public:
void add(){ cout <<"adder::add() "; }
};
class int_adder : public adder{
public:
int add(int a, int b)... | As pointed by others in the comment, I have corrected it:-
#include <iostream>
using namespace std;
class adder{
public:
void add(){ cout <<"adder::add() "; }
};
class int_adder : public adder{
public:
int add(int a, int b){
return (a + b);
}
};
int main(){
int_adder ia;
ia... |
66,259,549 | 66,259,809 | I am trying to understand these 2 blocks of code, could someone help please? | I am trying to understand some code and I was hoping someone could give me a basic overview of what this code means. The first bit of code I don't understand is this:
// loading file path
static string resourceRoot;
#define RESOURCE_PATH(p) (char*)((resourceRoot+"/"+string(p)).c_str())
The second bit of code I am try... | The first part is a macro which helps you to create a path for a specified resource, relative yo some root resource path, you can set in your code.
You basically would use it like this:
static string resourceRoot;
#define RESOURCE_PATH(p) (resourceRoot+"/"+string(p))
void load(cMesh* mesh)
{
// Probably set somewh... |
66,259,831 | 66,260,466 | Building an infinite range with range-v3 | I am trying to build a range which produces infinite random points in a triangle. To do that, I am using CGAL, which already provides the functionality to generate the random points in a triangle.
Triangle coarseTriangle = {v[0], v[1], v[2]};
CGAL::Random_points_in_triangle_2<Point> randomSamplesGenerat... | You can use std::unreachable_sentinel (Or ranges::unreachable from <range/v3/iterator/unreachable_sentinel.hpp>):
ranges::subrange randomSamplesRange(randomSamplesGenerator, ranges::unreachable);
|
66,260,257 | 66,260,345 | Cant get my head around why this code works | This is a basic c++ code that lets the user have 3 chances to guess a secret number.
#include <iostream>
int main() {
int secretnumber(5);
int guess;
int guessamount(0);
int guesslimit(3);
bool outofguesses = false;
while (guess != secretnumber && !outofguesses) {
if (guessamount < g... |
To me, ! here switches the value from false to true right? So that's saying, "while outofguesses = true, run this loop. But wouldn't that be wrong?
What is wrong is your interpretation. Take only this part of the condition:
while ( !outofguesses)
The loop continues as long as the condition is true. Because the condi... |
66,260,457 | 67,467,951 | How to inherit constructors out-of-line? | Is it possible to inherit constructors out-of-line in C++ so that they don't (say) get codegened in every translation unit? If so, how?
| Apparently this isn't possible.
|
66,260,575 | 66,260,809 | Best way to remove string prefix from std::string_view? | As of C++20 string_view has remove_prefix but it is "wrong"(wrong for my usecase) thing.
It takes as an argument number of chars, instead of a prefix(string like thing).
I have this code, but I wonder if there is some nicer way to do what I want(note that my code cares about if prefix was removed so I return boolean):
... |
I mostly care about having something like nonexistant
bool /*prefix removed*/string_view::remove_prefix(string_view prefix);
Indeed, such function is not in standard library. But you've now written such function, and your function is thus a nicer way to do something like what you want.
If you're open for a differen... |
66,260,666 | 66,260,815 | run function in a interval while also running main code | Basically I am trying to run 2 pieces of code concurrently without freezing eachother, and one of the requires some delay.
so, initial code looks like this:
int main() {
cout << "Hello World!";
std::this_thread::sleep_for(std::chrono::milliseconds(166)); // this freezes the whole program for 166 ms
// do ot... | Your second example seems to be what you want. If you do not want to detach the thread, then don't do it. However, then you must join it and you can only join a thread when it finishes its work at some point.
For this simple example I suggest the following (otherwise you need a condition variable or similar to signal t... |
66,261,570 | 66,261,991 | C++ SFINAE not failing | Code:
#include <iostream>
using std::nullptr_t;
template<typename... T>
using nullptr_vt = nullptr_t;
struct not_addable{};
template<
typename T,
nullptr_vt<decltype(std::declval<T>() + std::declval<T>())> TSfinae = nullptr>
bool test_addable(int)
{ return true; }
template<typename>
bool test_addable(...)
{... |
I thought that nullptr_vt<decltype(std::declval<T>() + std::declval<T>())> from the first overload would be an error for not_addable and it would discard it from the overload set, thus choosing the second overload.
The idea is actually fine, the problem is just with GCC and nullptr_vt
This line:
nullptr_vt<decltype(s... |
66,261,711 | 66,261,785 | Trying to assign an object to an object of different type in C++ | I'm trying to understand the behaviour of this code:
class A {
public:
int a;
A(int x = 0): a(x) {cout << "A-ctor" << endl;}
~A() {cout << "A-dtor" << endl;}
};
class B {
public:
int b;
B(int x = 0): b(x) {cout << "B-ctor" << endl;}
~B() {cout << "B-dtor" << endl;}
};
int main() {
A a;
... | This assignment
a = b.b;
works, because there is a user defined (implicit) conversion from int to A via this constructor:
A(int x = 0): a(x) {cout << "A-ctor" << endl;}
Such constructors are called converting constructors (can be called with single argument and is not declared explicit). If you want to prevent the im... |
66,261,968 | 66,262,363 | How can we calculate, for every element in an array, the number of elements to the right that are greater than that element? | Given an array A with n values, let X of A be an array that holds in index i the number of elements which are bigger than A[i] and are to its right side in the original array A.
For example, if A was: [10,12,8,17,3,24,19], then X(A) is: [4,3,3,2,2,0,0]
How can I solve this in O(n log(n)) Time and O(n) Space complexity?... | Quick summary of the problem statement: Given an array A which contains N integers, construct an array X such that for every i, X[i] = the number of elements in A that have an index greater than i and are also greater than A[i].
One way to solve this problem would be to use a binary search tree. Start by iterating from... |
66,262,030 | 66,262,644 | Why doesn't the C++ STL implement more efficient std::set implementation? | Background
Im building a performance minded application and I came across a place where I have to use std::set. And it works like a charm. But then I started reading into the documentation (which you can find here) and the first thing I noticed was that
Search, removal, and insertion operations have logarithmic compl... | The standard set has some guarantees that you can't provide with your implementation:
inserting/erasing doesn't invalidate other iterators/references/pointers.
inserting/erasing elements has (at most) logarithmic complexity, as opposed to linear in your implementation.
If these don't matter to you, you're welcome to ... |
66,262,083 | 66,262,280 | Registering a Struct for use with Qt Queued Connections | I have an object in a worker thread that needs to pass data back to its controller in the main thread.
There's several fields to move, so I'd prefer to do this using a struct. The Qt docs make it clear that to use a custom type with Queued Connections, I need to use both Q_DECLARE_METATYPE and qRegisterMetaType.
The s... | As documentation states:
To use the type T in queued signal and slot connections,
qRegisterMetaType() must be called before the first connection is
established.
So if you put the register in constructor, you have to instance your class once and then make the connection.
A common way to register the type is in main or... |
66,262,132 | 66,262,303 | Can I retarget the chrono class to use microcontroller as tick generator? | I want to use the timer in my microcontroller as tick generator of the chrono class.
imagine that I have function that gets the tick from timer register in the MCU and I call it get_tcik() and this register is 32 bit unsigned integer which increments each 1 microsecond.
Now to use it with chrono I've created a class li... | It's not working because the chrono library detects suboptimal code formatting. :-)
Just kidding.
You're missing some nested types for clock that client code might expect to be there. Also you can use std::micro in place of std::ratio<1, 1000000>. Your choice isn't wrong. This is just a stylistic suggestion.
#includ... |
66,262,143 | 66,349,910 | Change tag value on file XML Xerces C++ Parser | I created an XML file and I don't know how can i change the tag text value on this file.
also i can get the node text value and I can change it, but how can i write this modification on a file?
xercesc_3_2::XMLPlatformUtils::Initialize();
parser = new xercesc_3_2::XercesDOMParser();
parser->parse(xmlFile)... | void changeXMLNodevalue(std::string fileName, std::string node, std::string value) {
xercesc_3_2::XMLPlatformUtils::Initialize();
// create the DOM parser
xercesc_3_2::XercesDOMParser* parser = new xercesc_3_2::XercesDOMParser;
parser->setValidationScheme(xercesc_3_2::XercesDOMParser::Val_Never);
parser->parse(fileN... |
66,262,352 | 66,262,650 | Make clang ignore empty wildcard | I would like to make clang compile both C and C++ files in the directory (if any). To achieve this, I run clang as follows: clang *.c *.cpp. My issue is that it refuses to run if there's no files of one type: clang: error: no such file or directory: '/mnt/c/test/*.c'
Is there a way to make clang ignore wildcards that d... | The problem seems to be with the built in shell globbing in bash, not with clang. You can't make clang ignore what you feed it and a non-matching globbing will send the result unexpanded (since there's nothing to expand). To turn off the default globbing so that no matches results in an empty match:
shopt -s nullglob
... |
66,262,441 | 66,262,554 | Access violation in Mat queue | I'm writing a producer/consumer code that receives frame date from an external library.
Each frame is read in a callback function from an external library that runs in a parallel thread and is pushed into a Mat queue. I created another function that runs in a different thread that reads and pops each frame.
The problem... | You should try to clone the frame immediately when receiving it:
frame = Mat(size, CV_8UC3, rgbData, Mat::AUTO_STEP).clone();
instead of there:
frame = matQ.front()/*.clone()*/;
|
66,262,461 | 66,262,546 | How can I extract 12 bits from a 2 byte char array? | I am working on extracting data from binary files. One of the data values is packed into two bytes, but only 12 of the 16 bits contain the relevant information:
Does anyone have a method to extract the 12 bits seen in this image? Let the two bits be stored in an unsigned char buffer[2].
| > does with respect to a char the same thing it does with any other type - it returns 1 if the left side is greater than the right side, and 0 if it isn't.
It doesn't make sense here.
If you copied this from the Internet, I suspect the author wrote >> but the formatting got messed up by the website at some point.
|
66,262,480 | 66,262,510 | is auto type detection only looking at one statement | For the two for loop below, are they equivalent? Basically does the auto look over "=0" assignment and see iter is compared with s.size() and so decides iter is of type decltype(s.size())?
string s;
for(auto iter=0; iter<s.size();iter++)
string s;
for(decltype(s.size()) iter=0; iter<s.size();iter++)
|
and see iter is compared with s.size() and so decides iter is of type decltype(s.size())?
No. auto only deduces type from the initializer, given auto iter=0;, the type is deduced from 0 then it'll be int.
in the type specifier of a variable: auto x = expr;. The type is deduced from the initializer.
And you can spec... |
66,262,735 | 66,262,831 | Executable "C:\Windows\System32\Fodhelper.exe" not found | I am trying to start the above builtin Windows executable from within a C++ program. Firstly I can confirm that the program does exist, at the path "C:\Windows\System32\fodhelper.exe"
I have tried 3 different methods for running this program:
System()
ShellExecuteW()
CreateProcessW()
None of these methods work. The ... | 32-bit applications running on WOW64 will be put under file system redirection. Therefore if your app is a 32-bit one, the path C:\Windows\System32\fodhelper.exe will be redirected to C:\Windows\SysWOW64\fodhelper.exe which doesn't exist. You have some solutions:
Use SysNative to access the real system32 folder, which... |
66,262,741 | 66,262,820 | Why is the copy constructor invoked in a lambda while moving a `unique_ptr`? | Why does this code fail to compile?
#include <memory>
#include <utility>
int foo() {
auto num = std::make_unique<int>(1);
auto func = [s = std::move(num)] {
auto u = std::move(s); <-- ERROR!
return *u;
};
return func();
}
The error is:
<source>:8:14: error: call to deleted constructor ... | It is because you are trying to move a data member in a const member function.
The type and category of std::move(s) is const unique_ptr&&. There is no overload unique_ptr(const unique_ptr&&), the only one that is viable is unique_ptr(const unique_ptr&).
I think this would fail to compile because the move(s) would cha... |
66,262,970 | 66,264,338 | G++ flag to protect against use of uninitialized inherited properties | How can I make g++ to protect me against the use of uninitialized parent properties into child constructor ?
struct A {
A(int typ): type{typ} {}
const int type;
};
struct B : public A {
B(int typ): A(type) {}
};
int main() {
B b{3};
return 0;
}
Can you see the bug here, how tricky it is ?
Here we... | The flag to use is -Wuninitialized, it is already embedded with -Wextra and -Wall.
But in my case, I use gcc-6.4 in c++14 mode.
With this gcc version you have to use the flag, enable optimization and use the variable that have been initialized with an uninitialized variable.
Only if all of these condition have been don... |
66,263,129 | 66,263,199 | Add constructor to std::vector via friend | I'm not sure if my question is possible or if it might already have an answer somewhere but I'm not sure how to search for it.
I have made some sort of custom container (MyCollection). The most important thing is that is has begin() and end() function that return iterators. I want to convert a object of my custom conta... | No, you can't. In C++ you cannot extend class without modifying its definition (the header file).
But in your case - you can add "cast operator":
template <typename T> MyContainer {
public:
operator std::vector<T>() const
{ return std::vector<T>(begin(), end()); }
};
|
66,263,173 | 66,263,480 | Different OpenGL behaviour on different hardware | I have an application that uses OpenGL to draw output images. For testing purposes I'm trying to create reference images and then use precision hash to compare them to program output. While it works flawlessly within a context of a single computer I've encountered strange problems when using the same approach with comp... |
Could this possibly be due to differences in OpenGL implementation
from different hardware manufacturers? Is it a valid approach to
compare images generated on different GPUs with phash for testing
purposes?
No, it is not. Quoting the OpenGL 4.6 core profile specification, Appendix A "Invariance" (emphaisis mine):
T... |
66,263,426 | 66,263,899 | getting segmentation fault on this code for deletion of node in linked list | I'm trying to write a function for the deletion of a node in a linked list , given a double pointer to the head and a pointer to the node to be deleted. (the node to be deleted will not be the tail node)
this is what I have tried:-
public:
int value;
Node* next;
};
/*
headPtr is a reference to the head no... | I can see multiple things:
1 - In your while condition you are not checking that current is valid:
while(current->next!=deleteNodePtr){
prev = current;
current=current->next;
}
2- What probably is happening to you now: the deleteNodePtr points to the second element in the list, so you n... |
66,263,495 | 66,263,601 | Why is my class constructor being called twice? | I've got a base class Container with a derived class Player_Inventory. There can only be one Player_Inventory so my code throws an exception if for some reason a second one is created.
The problem I'm having is that my code is failing my test as it throws the exception even on what is supposed to be the very first cons... | Not sure if related, but that's how you should call the Base constructor:
Player_Inventory(std::string n, std::string desc) : Container(n, desc) {
}
|
66,263,573 | 66,264,598 | Like std::function but with more varied argument and return types | I'm in search of a way to set up and call functions with arbitrary arguments and return types. One use case would be high level scripting. Something like this:
// universal function
using dynfunction = std::any (*)(std::vector<std::any> args);
I made a simplified example:
#include <any>
#include <vector>
#include <map... | Here is my design:
#include <any>
#include <cstddef>
#include <cstdio>
#include <functional>
#include <stdexcept>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
class Dyn_fun final {
public:
using arg_type = std::vector<std::any>;
using return_type = std::any;
Dyn_fun() = default;... |
66,263,653 | 66,263,942 | Any way to get split_regex to accept a const string as input? | Following code compilation implodes with deep template error stack if I try to make string input const, but I do not understand why it should be mutable.
From thinking about algorithm const should be fine, also I checked that the argument is not modified after function call.
#include <string>
#include <iostream>
#inclu... | As per the comment, if the std::string being searched is const then the iterator type used in the results must be the associated const_iterator type for the container being searched. Hence if the string being searched is...
const std::string str("helloABboostABworld");
Then the results container should be...
std::vec... |
66,263,800 | 66,267,493 | Deleting words from a string and printing their addresses | The task is to delete all repeating words from the string and then print the addresses of these words (meaning the addresses of the first letters) in the original string on the screen.
My code looks like this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string inputString = "cactus word... | Ended up rewriting the whole thing but this is what I came up with:
int main()
{
string inputString = "cactus. word programmer cat word dog cat. cat. cat mug words. words. abc abcde abba programmer";
inputString = inputString + ' ';
string copiedString = inputString;
string word;
int wordSize = 0;
... |
66,264,238 | 66,264,749 | How can I properly initialize C++ objects within an Arduino program? | In my simple Arduino project, in order to keep things tidy, I decided to create a "Mode Manager" that will handle passing between one mode and another. The basic concept is that each time I want to change the mode, then it will instantiate the next mode and replace the previous one.
Please note that I have 12+ years ex... | Here:
DummyMode cmode = DummyMode();
you are creating a DummyMode instance cmode with automatic lifetime (commonly referred to as on the stack).
You then take the address and assign that to another variable:
mode = & cmode; // I'm not sure how this should actually be done
Since cmode is an object with automatic lifet... |
66,264,267 | 66,264,627 | Loading external class c++ | I am trying to load a class defined in a .dll file. However there are two slightly different ways of defining the class in the dll. I'm not sure which is the more legit way to do it, and I don't know why the second way also works. Here is a simple example:
Method 1:
In main.cpp:
#include <iostream>
#include <windows.h>... | So you cast a function returning foo* as a function returning bar* and then invoking it.
The end result is that you have a pointer to foo which is a pointer to an unrelated type bar. Using it in any way will lead to undefined behavior.
It appears to work in this specific case because the position of the printmsg virtua... |
66,264,600 | 66,264,691 | Are static free functions thread safe? | I am writing a multithreaded program and have a function that will be called from multiple threads that is a static free function within a cpp file. This function will never be called from outside of the cpp file so I wanted to make it static so that it had internal linkage.
Googling around I found a lot of people sayi... | Any function that accesses no shared state is inherently thread safe. You only get a data race when you have unprotected read/writes to shared state. If there is no shared state, you can't have a data race.
This is why purely functional languages are naturally thread safe. If a function doesn't have side effects, th... |
66,265,216 | 66,412,561 | How is FreeType calculating advance? | I am trying to figure out how the FreeType Library is calculating the FT_GlyphSlotRec_'s advance variable. According to the comment blocks above this structure, this variable would be the same as the horiAdvance variable further explained here, which is contained within the FT_Glyph_Metrics_ structure.
In any case, tak... | As indicated on that Tutorial, Step 2 page you linked in your question, those metrics are usually reported for a 26.6 pixel format. You are modifying that by the way you're loading in the font. You can use the FT_LOAD_NO_SCALE to "[not] scale the loaded outline glyph but keep it in font units."
Your code generates a ... |
66,265,267 | 66,265,609 | C++ copy constructor for a class with an array attribute | I am creating a matrix template and ran into a problem writing the copy constructor. While data appears to be copied correctly from within the constructor, the object returned to the main program does not have the correct values (looks like its pointing to a different memory address). In my attempts to debug this I tri... | Short Version: Just use std::vector. It will will make your life easier, and has far less pitfalls than a manual approach.
Long Version: You have two major problems in your code:
You are using Flexible-Arrays incorrectly (and this is a compiler extension, not standard C++), and
You are using Variable-Length Arrays in... |
66,265,409 | 66,265,521 | Is it necessary to release memory for a string variable defined inside a function in C++? | Problem description:
It is needed in C to delete the allocated memory for a pointer to an array
char * (how we can define string in C).
My question:
I am wondering if it is also necessary for C++ string types.
For example:
Let's say I have a function which is responsible for converting all uppercase characters to lower... |
string type,defined as char *
char* is merely a pointer. It is not a string. It can point to a character within a string though.
I understand in C we need to delete any memory allocation for string type
You (usually) need to deallocate all memory that you allocate, regardless of what type you allocate the memory fo... |
66,265,613 | 66,272,395 | Store each character from a std::string into a std::string | I would like to know what method you would use to get each character from a std::string and store it in another std::string.
I find the problem when the std::string has special characters, such as "á". If I do:
std::string test = "márcos";
std::string char1 = std::string(1, test.at(0));
std::string char2 = std::string... | The number of bytes (between one and four) used to encode a codepoint in UTF-8 can be determined by looking at the high bits of the leading byte.
bytes codepoints byte 1 byte 2 byte 3 byte 4
1 U+0000 .. U+007F 0xxxxxxx
2 U+0080 .. U+07FF 110xxxxx 10xxxxxx ... |
66,265,652 | 66,265,703 | Wait for async file write to finish before exiting main thread | using experimental/filesystem and std::async is there a way to ensure filewrites finish before exiting the main thread?
code used to call the async function
std::vector<std::future<void>> img_Futures;
for (int i = 0; i < parsedResult.size(); i++)
{
img_Futures.push_back(std::async(std::launch::asyn... | You can call std::future::wait() on each of the futures. This will block until the future's result is available, i.e. until your downloadImage() function has finished.
|
66,265,959 | 66,266,311 | QML undefined variable from Qt | I try to implement cpp variables to qml using Q_PROPERTY. First, I have created Q_PROPERTY of float numbers xValue, yValue, and zValue in the header file.
fileio.h
...
Q_PROPERTY(int xValue
MEMBER xValue
NOTIFY xValueChanged)
Q_PROPERTY(int yValue
MEMBER yValue
... | Two things:
You need to emit the change such that the QML can become aware of the property change after you set the local variable
xValue = (line.split(',')[0]).toFloat();
emit xValueChanged();
Further, your C++ class, which derives from QObject needs to be exposed up to the QML as a named object and connected to it.
... |
66,266,046 | 66,266,526 | Unexpected end of file while looking for precompiled header | I've been trying to organize my code into sub-folders, and I've been careful to not do anything extra than that since my last commit. I am currently getting a bunch of C1010 errors saying:
unexpected end of file while looking for precompiled header. Did you forget to add #include "pch.h" to your source?
Each file does ... | So replacing the following code...
if (MSVC)
set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT Minecraft)
set_target_properties(Minecraft PROPERTIES COMPILE_FLAGS "/Yupch.h")
set_source_files_properties("src/pch.cpp" PROPERTIES COMPILE_FLAGS "/Ycpch.h")
target_compile_opti... |
66,266,079 | 66,283,919 | compiler problems with variable template | The following code (taken from Wikipedia) defines the variable template pi<>:
template<typename T=double>
constexpr T pi = T(3.14159265358979323846264338328);
template<>
constexpr const char* pi<const char*> = "π";
With the clang compiler (Apple clang version 12.0.0) (with C++14), this triggers a warning (with -Wevery... | The warning from (this old version of) Clang is partly misleading, but does indicate the real problem that you eventually encountered with the linker. The warning describes the good rule of thumb that a global variable ought to
appear with extern in a header and then without in a source file, or
appear with static in... |
66,266,259 | 66,314,619 | Python: How to write a script to compile and run a C++ program via CMake? | Assuming I have the following project structure,
| CMakeLists.txt
| run_experiments.py
+---libs
\---src
main.cpp
main.h
how to make run_experiments.py compile the program via CMake and run it multiple times with different command-line arguments? What I've tried:
# run_experiments.py
import os
os.... | Python's subprocess module will enable you to run external programs like CMake and the binary that you build with it. The executable name, however, will be different on Windows and Linux (with Windows having a .exe extension). You should be able to specify ./test_tokenizing to run your program and the system should fin... |
66,266,315 | 66,286,794 | C++ program behavior | Was demonstrating the failure of C++ to detect input issues in floating point numbers when additional characters follow the input.
E.G. 234.5 when using cin works fine, but 234.t (demonstrating a finger slip on input) would read the 234. and leave the t.
Imagine my surprise when some input fails and others did not. Not... | This seems to be one of the inconsistencies in parsing floating point numbers that occasionaly surface in the implementations of the standard library (see e.g. 1169, 2381).
Consider the following modified snippet
#include <iostream>
#include <sstream>
#include <string>
int main()
{
float number{};
std::string ... |
66,266,584 | 66,266,828 | Cant find the values I stored into a map | I'm basically reading a file character by character, and when I encounter a new number I store it in a std::map as a key with the element equal to 1. The more times I encounter the same number, I increment that key's element:
if(intMap.count(singleCharacter)){
//keyexist just increment count else
//cout<<"exis... | You get those "random" numbers because you are using std::map<int,int> instead of std::map<char,int>. What you get printed are the ASCII numeric codes for character symbols, and their counts.
So, you need to either change the map's type, or cast the keys back to char:
for (auto& p : intMap ) {
cout << static_cast<c... |
66,266,683 | 66,266,800 | How to extract the arguments of a function pointer as type parameter pack? | I would like to support calls like this
class BaseClass {
public:
virtual void print2(float arg1, float arg2) = 0;
};
int main() {
invoke(subclass, &BaseClass::print2, 1, 2);
}
where
subclass is automatically upcasted to BaseClass
the arguments are automatically converted from int to float
calls with wrong... | Both the manual upcast and extracting the parameter types should be
unnecessary.
You can just do this:
template <typename T, typename M, typename ...P>
void invoke(T &&object, M member, P &&... params)
{
(std::forward<T>(object).*member)(std::forward<P>(params)...);
}
|
66,267,151 | 66,267,313 | How to measure the remaining bytes on std::fstream? | This is how I open my std::fstream:
f.open(filePath, std::ios_base::binary | std::ios_base::in |
std::ios_base::out);
After calling some reads, how can I know how much bytes are left to be read?
I think f.tellg() (or tellp?) will tell the current position.
I tried doing some tests:... | After you've opened the file, you can seekg to the end with f.seekg(0, f.end), then get current position with tellg. This will equal to the total number of bytes in a file.
Then, you seekg to beginning again, do some reads, and use tellg to get current position. Then, having current position and total file size is easy... |
66,267,398 | 66,267,950 | Take the sum of two integers and add another integer to the sum continuously | I would like to make a C++ program that takes the sum of two integers and adds another integer to the sum continuously. Please help, I'm a beginner. My code looks like this, except it doesn't update the next sum:
#include <iostream>
using namespace std;
int main() {
int x;
while (cin>>x){
int y=100;
in... | Your sum variable is declared inside the loop body, so it will be wiped out on each iteration. You need to move that variable outside of the loop, eg:
#include <iostream>
using namespace std;
int main() {
int sum = 100, x;
while (cin >> x){
sum += x;
cout << sum << endl;
}
return 0;
}
|
66,267,674 | 66,294,761 | Is it okay to have a SDL_Surface and SDL_Texture for each sprite? | I'm trying to build a gameengine in SDL2 with cpp. I have a class called 'entity' which has some data for movement and also some pointers to a surface and a texture. A function "render" is called inmass to render each sprite based on the g_entities vector.
class entity {
...
SDL_Surface* image;
SDL_Texture*... | Yes but actually, no. If the same sprite will be used many times without modification, its most efficient for those objects to have pointers to the same SDL_Texture. Additionally, the image can be freed after the texture is generated. Furthermore, loading these in the constructor may be a bad idea since objects made on... |
66,267,753 | 66,267,851 | Manually calculating norm | I have this code shown below which is supposed to manually calculate the norm of a randomlly generated vector. However, I keep getting the output being printed to the terminal as 0. Why is the case?
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <ctime>
using namespace std;
double... | double result = result + a*a;
This declares a new variable inside the loop, so the other result variable doesn't change, which is why 0 is returned.
To fix it just do result = result + a*a or result += a*a:
double ComputeNorm(const vector<double>& x) {
double result = 0.0;
for (auto a : x) {
re... |
66,268,072 | 66,271,415 | using boost::geometry to convert from Latitude and longitude to UTM | boost::geometry seems to have support to convert from lat/lon to UTM. Unfortunately I couldn't find any example on how exactly to do that.
Does someone have an example they are willing to share?
| I just spent an embarrassing amount of time looking for this (multiple hours).
It seems like everything spherical (SRS) is just ... not documented at all. Perhaps there's something broken with the documentation generator.
Regardless, several tedious searches through test code further I stumbled on a working answer.
Her... |
66,268,136 | 66,268,284 | How to replace the deprecated function `QWheelEvent::delta()` in the zoom in / zoom out function? | I was using the delta() function from the QWheelEvent class to achieve the zoom in, zoom out. now it is deprecated, and they advise in the documentation to use pixelDelta() or angleDelta() instead, but they are QPoint objects!
can anybody please tell me how to replace this deprecated function with another ones?
void Ma... | The documentation of angleDelta says that angleDelta().y() will return the angle by which the vertical mouse wheel was rotated and angleDelta().x() will return the angle by which the horizontal mouse wheel was rotated.
For zooming I'm assuming you will want to use vertical scrolling, so changing the conditions accordin... |
66,268,224 | 66,268,572 | How would I separate a std::string with more than 1 character I'm looking for? | I'm writing a program that can take in multiple names separated by a space, like "John Paul Andrew" and turns the names into keys for a std::map.
It works fine with two names, but three names or more separate the string into:
Andrew
John
John Paul
Here's how I'm splitting the strings:
for (int i = 0; i < names.size() ... | You are looping through each character of names (except the last character!), using the current loop position as the starting position to find() a space character. That is not the logic you should be using.
Let's follow the logic, using your example of "John Paul Andrew" as the names to split.
On the 1st-5th loop ite... |
66,268,516 | 66,268,811 | Convert a void* back into an array | I have a char* array which gets converted to void*, but I am having difficulty accessing the original array. See the args array:
void run_async(char* src, char* dest) {
char* args[] = {src, dest};
_beginthreadex(NULL, 0, copyFile, args, NULL, 0);
}
unsigned __stdcall copyFile(void* args) {
char* src = (char*)((c... | You must cast args to char **, because args is a pointer to the first element, which itself is a char *. So you have a so-called "double pointer", i.e. a pointer to a pointer. After that, you can use the [] subscript operator on it, and the second type cast is unnecessary.
The reason why the code you linked to in the c... |
66,268,993 | 66,277,058 | How to get torch::Tensor shape | If we << a torch::Tensor
#include <torch/script.h>
int main()
{
torch::Tensor input_torch = torch::zeros({2, 3, 4});
std::cout << input_torch << std::endl;
return 0;
}
we see
(1,.,.) =
0 0 0 0
0 0 0 0
0 0 0 0
(2,.,.) =
0 0 0 0
0 0 0 0
0 0 0 0
[ CPUFloatType{2,3,4} ]
How to... | You can use torch::sizes() method
IntArrayRef sizes()
It's equivalent of shape in python. Furthermore you can access specific size at given ax (dimension) by invoking torch::size(dim). Both functions are in the API page you linked
|
66,269,655 | 66,269,919 | How to P/Invoke a function with an unknown struct in C#? | I know this sounds really strange, but I don't know how to even ask this properly. I've been trying to P/Invoke into NVidia's NVML library with limited success: I've managed to call a few of the APIs exported by that library
Now I am trying to call nvmlDeviceGetHandleByIndex_v2 but I've been stuck for a long while on t... | If you look at the source, that is just an internal pointer used by the SDK. The value it points to has no meaning to you. You use it to identify a device you are working with.
Think Handle or HWND in Windows. You call something like FindWindow(), it returns what seems to be a random value back to you. You don't care w... |
66,269,836 | 66,273,161 | How to read multiple lines from stdin until EOF? | How can I read multiple lines from stdin and advance until EOF in Rust? I'm trying to translate this C++ code to Rust but I'm failing.
#include <iostream>
int main()
{
try {
std::string line;
while (std::getline(std::cin, line)) {
int length = std::stoi(line);
... | The problem is you're calling stdin.lock() twice which immediately deadlocks. That and you'll need to use only a single .lines() call because its designed to consume the entire input. Fortunately, that just means we have to refactor the outer for loop into a while:
use std::io::{self, BufRead};
fn main() -> io::Result... |
66,269,865 | 66,270,303 | fill_n vs memset to set default value of an array | I wonder what is the ideal way if you want to fill an array with a default value n:
#include <cstring> // for memset
#include <algorithm> // for fill_n
static constexpr int N = 100;
int a[N];
static constexpr int defaultValue = -1;
void* memset( void* dest, int ch, std::size_t count );
memset(a, defaultValue, sizeof(... | Both functions do different things. Sure, they fill a block of memory, but the way they do it is completely different.
memset operates at the byte level. defaultValue is hacked down to an unsigned char, so a defaultValue greater than what can fit into a single byte gets cut down to size and information is lost. The now... |
66,270,039 | 66,270,260 | Need help utilizing two classes in one function, | So basically I created two classes for two vectors and got there norms. How would I approach using both classes to find the distance between both vectors in my main function ? I know I can use the friend function but we have not been taught that in class so I have to use the scope :: operator and constructor and destr... |
I know I can use the friend function but we have not been taught that in class [...]
You can always use getx(), gety() and getz() directly to calculate the distance. Since this gets a bit tiresome to write more than once you can write a little function that wraps the calculation:
float distance(Vector v1, Vectortwo v... |
66,270,259 | 66,270,305 | While loop not acting as expected in Dev C++ | I'm trying to get a while loop to accept the condition of looping until the values 1 or 2 are entered using the code below
while((choice != 1) || (choice != 2))
{
cout << "\nEnter 1 to read a file, Enter 2 to enter your own values: ";
cin >> choice;
}
As best as I can remember this has worked for me previously... | The issue with your loop is that this condition:
(choice != 1) || (choice != 2)
is guaranteed to be true for every value. If choice is 1, the second clause of the disjunction will be true; if it's 2, the first clause will be true; if it's any other number both will be true. If any of the clauses are true in a disjunct... |
66,270,575 | 66,270,639 | Multidimensional array prints hex numbers instead of the contents of the array | I was playing around with multidimensional arrays and was wondering what is happening in this bit of code that makes it print out hexadecimal rather than the actual contents of the array. I understand this might be a silly question but hopefully someone can explain it this is my first year programming.
#include <iostre... | If you have a 2 dimensional array like int arr[4][3], then arr is essentially just a memory address pointing to the entire 2D array.
Similarly, arr[X] is also an address pointing to one row of the 2D array. So printing either:
std::cout << arr;
std::cout << arr[1];
will print a memory address, which just shows on the ... |
66,270,616 | 66,270,953 | More than one instance of overloaded function matches the argument list and I can't find where the error happens | I get the above error when I use this code.
//Programming Assignment 1
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//Function Prototypes
void getname(ofstream);
//void Evaluate_holesterol(ofstream);
//void Evaluate_BMI(ofstream);
//void Evaluate_bloodpressure(ofstream);
int main... | As the comments by cigien and Peter already pointed out: The declaration and the definition of getname() have mismatched parameters. To fix that, change the line
void getname(ofstream);
to
void getname(ofstream&);
Note the & after ofstream.
Furthermore, any function that gets an ofstream as parameter should get that ... |
66,270,770 | 66,272,615 | How can I get the latest changes in a file using ifstream? | It's a real-time capture system, I need to get the latest changes from a file which is occasionally edited(mostly add content) by other applications.
In other words, how can I get content that added in the period when I open it without reopening the file?
#include <iostream>
#include <fstream>
#include <string>
using ... | C++ / C Solution
If you are looking for a c++ solution you can use the following functions that I had created a while back:
#include <iostream>
#include <string>
// For sleep function
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
using namespace std;
void watchLogs(const char *FILENAME) {
... |
66,271,298 | 66,271,419 | copy behavior in vector constructed with a initializer list | I realize that initializing a vector with a initializer_list relying on the copy constructor instead of the move constructor. For example, the following code print copy
class A {
public:
A(const string& ss): s(ss) {}
A(A&& other) {
cout << "move" << endl;
s = std::move(other.s);
}
A(co... | std::initializer_list makes copies of the values that are given to it. And those copies are const, so the vector can't even move them if it wanted to. So, initializing/assigning a vector using a braced-init-list will always perform a copy operation, never a move operation.
Even if you changed the code to use an A[] a... |
66,271,336 | 66,271,480 | How to build C++17 application in old linux distro with old stdlib and libc? | I need to build a C++17 application with distro having libstdc++ 6.0.22 (GLIBCXX 3.4.22) and libc 2.24. These versions of libraries don't allow me to build modern c++ and I cannot update system's versions. In fact, I need a correct working application (may be carrying compiled stdlib from sources with it) that I could ... | libstdc++ is a part of the C++ compiler (gcc or llvm). You need not only the current libstdc++ but also the compiler that goes with it. The current version of each compiler (which is needed for support C++17) requires the current version of libstdc++ for programs that are compiled with it. I haven't double-checked the ... |
66,271,587 | 66,272,164 | Recursive Standard C++ Library Container Types? | Is it possible to define Standard C++ Library Container Types UM, OM and L such that:
UM is an std::unordered_map with key_type int and mapped_type iterator to OM
OM is an std::map with key_type int and mapped_type L
L is an std::list of iterators to UM
?
| Something like this:
#include <unordered_map>
#include <map>
#include <list>
struct Container{
struct List;
using OM = std::map<int, List>;
using UM = std::unordered_map<int, typename OM::iterator>;
using L = std::list<typename UM::iterator>;
struct List{
L l;
};
UM um;
OM om;
L l;
};
int main()... |
66,271,885 | 66,284,026 | Use zlib inflate() in c++ to decompress via PHP ZLIB_ENCODING_RAW encoded data | When I compress a string in PHP with encoding ZLIB_ENCODING_DEFLATE and output the hex data, I can convert this back to the original string using zlib deflate() in a c++ project.
Per the example here ( https://www.php.net/manual/en/function.zlib-encode.php ) :
<?php
$str = 'hello world';
$enc = zlib_encode($str, ZLIB_E... | The PHP designations are (as usual) confusing. I will assume that ZLIB_ENCODING_RAW means raw deflate data (per RFC 1951), and it appears that ZLIB_ENCODING_DEFLATE actually means zlib-wrapped deflate data (per RFC 1950).
If that's correct, they should have called them ZLIB_ENCODING_DEFLATE and ZLIB_ENCODING_ZLIB, resp... |
66,272,066 | 66,272,171 | Is there any similar class available in C++ and Java as "pyautogui"? | Python has a class named "pyautogui" to perform some task automatically on system interfere(Control mouse and keyboard strokes by method of that class). Is there any similar class available in C++ and Java? Help me out dudes by writing down names of this class. Thanks in advance, ❤.
| Your question: Is there any similar class available in Java?
Answer: Yes.
More info: Read the java documentation of java.awt.Robot
|
66,272,441 | 66,274,030 | about the using of template | I'm trying to overload the operator for matrix multiplication.
But I receive the error message:
<source>:29:16: error: invalid operands to binary expression ('matrix<3, 3>' (aka 'array<array<int, 3>, 3>') and 'matrix<3, 2>' (aka 'array<array<int, 2>, 3>'))
auto c = a * b;
~ ^ ~
<source>:12:6: note: can... | The dimensions of std::array are specified to be of type size_t. Even though you have defined your matrix alias with int template arguments you still end up with a std::array with size_t dimensions. The compiler is unable to automatically deduce your template argument as their types don't match, if you look at the full... |
66,272,469 | 66,272,510 | C++: Can I define vector within another vector? | In C/C++ pure array, you can define an array within another array, for example:
int a[5];
int *p = &a[1];
So that if you change p[0] it would affect a[1] so on and so forth. Is there similar mechanism in vector?
vector<int> a(5, 0);
?
| Your first example
int a[5];
int *p = &a[1];
does not define an array within another array, it only creates a pointer to an element inside the exisiting array. For standard containers like std::vector the same can be achieved by using iterators:
vector<int> a(5, 0); // a = [0, 0, 0, 0, 0]
auto iterator = a.... |
66,272,736 | 66,272,790 | Mapping an enum to a template type | I have a type ValueWrapper, which can store one of several value types, identified by an enum:
enum class Type : uint32_t
{
Float = 0,
String,
// etc
};
struct ValueWrapper
{
ValueWrapper(float f)
: type{Type::Float},data{std::make_shared<float>(f)}
{}
ValueWrapper(std::string str)
... | Use a using ValueWrapper=std::variant<double,std::string,...> instead.
void print(const ValueWrapper &v)
{
std::visit([](auto const& val){ std::cout<<val; }, v );
}
if you want shared ownership logic, make it either a variant of shared ptr, or a shared ptr to a variant.
I mean, you can reinvent the wheel, but why?
I... |
66,273,011 | 66,273,321 | How can I return a local created object in C++? | I am Trying to make an overload in "+" operator. The problem is I have to create a brand new object that will contain the sum, but when I try to return it, it gets deleted.(I think its because the object is locally created, so the system makes a shallow copy, and when it gets out of scope its content is deleted) How ca... | An object returned by a function will always be an rvalue. This object will be deleted when it goes out of use, which is usualy immediately. Your expression three = one + two takes that returned rvalue, and move-assigns it to three. After that, the rvalue is deleted.
The problem with your code is that the rvalue delete... |
66,273,536 | 66,280,743 | undefined reference to `cuCtxGetCurrent` while getting CUDA context for OptiX | I'm trying to learn how to implement OptiX into my C++ project. One of the first steps is to get the current CUDA context with cuCtxGetCurrent(&some_CUcontext_variable), however I'm getting a compile time error saying that I've made an undefined reference to cuCtxGetCurrent.
Here's what I have:
I'm following code from... | As @talonmies notes, CUDA has two (official) host-side APIs: The "CUDA Runtime API" and the "CUDA Driver API"; you can read about the difference between them here.
You have mentioned files and CMake identifiers relating to the Runtime API: cuda_runtime.h, CUDA::cudart. But - "CUDA Contexts" are concepts of the Driver A... |
66,273,890 | 66,273,993 | How to update array items by multiplying with other items in c++ | The result I want to get is Multiply the index value with other index value. e.g in the code below:
i want to update arr[0] value by arr[0]*arr[1], arr[9] value by arr[9]*arr[9-8] and for remaining indexes it'll be arr[i-1] * arr[i] * arr[i+1]. It is working fine on first index but at other indexes I am getting unexpec... | You need to store the results in a separate array or else you overwrite the values in the same array you use for future calculations.
In your case, when j == 0 you do:
arr[0] = arr[0] * arr[1]; // 1 * 2 = 2
So arr[0] is now 2. You then do
arr[1] = arr[0] * arr[1] * arr[2]; // 2 * 2 * 3 = 12, not 1 * 2 * 3 = 6
...and ... |
66,274,314 | 66,274,434 | using sort in C++ to sort a string starting from 2nd character to last character | I want to sort a string starting from the 2nd character to the last character. Currently I am able to sort the string as per my requirement but I want to utilize sort function in C++ to achieve the same
Sample input:
san test van best
Sample output:
san van test best
My current program
for (int i1 = 0; i1 < n; ++i1) ... | std::sort(std::begin(arr), std::end(arr),
[](std::string_view const & l, std::string_view const & r){
return l.substr(1) < r.substr(1);
}
);
Full working example:
Try it online!
#include <string_view>
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
int main() {
std::... |
66,274,348 | 66,274,435 | Why in C++ cout<<8*7/2 is giving 28? | We know BODMAS rule or firstly according to priority, division will occur first. So 7/2 = 3, as we are dividing (int)/(int). then multiply by 8 , so 3*8 will be 24.
But cout<< is giving 28.
Why this is happening?
| In C++ we not follow BODMAS strictly, + - has less priority than * /. But + and - has same priority. It means one which will appear first from left to right will be evaluated first. Similary * / has same priority.
So cout << 8*7/2 ; is eqivalent to cout << 56/2 ;. Because * / both has same priority but * appeared fir... |
66,275,035 | 66,275,149 | understanding the operator<<() from std::cout | I have written this little code for one of my student coworker, in order to illustrate overloading in c++ :
#include <iostream>
int main() {
std::cout << "Hello World!";
std::cout.operator<<("Hello World!");
return 0;
}
I thought naively I will have two times "Hello World!". But the second line send me an... | According to cppreference (emphasis mine):
Character and character string arguments (e.g., of type char or const
char*) are handled by the non-member overloads of operator<<. [...]
Attempting to output a character string using the member function call syntax will call overload (7) and print the pointer value instead.
... |
66,275,219 | 66,276,137 | C++ Member function as a callback | I'm using a static class called websocket which listens on a websocket (hence the name) and calls a callback function once data is received. I created the following declarations
typedef int (*cb)(Json::Value &json);
static void websocket::init();
static void websocket::listen(cb callback, const char* address);
I also... | There are two problems:
std::mem_fn(&app::callback) takes an instance of app as the first parameter.
The most idiomatic alternative would be to use a capturing lambda such as
[this] (Json::Value& json) { return callback(json); }
but these cannot be converted to function pointers, which makes implementing generic cont... |
66,275,452 | 66,275,664 | C++ string assignment error. How to assign values to a string member of a struct pointer? | Why the output of codes below is an invalid string? If lines #1 to #3 cannot be changed, how can I assign the value of config.strConfig to data2->str?
// classA.h
#pragma once
#include <string>
class Config {
public:
int a;
std::string strConfig;
};
// structA.h
#pragma once
#include <string>
struct Data {
... | You do not need (and shouldn't use) memset (line // #2). This clears the memory bytes without taking into account the container type you are using. Better to write a constructor for Data which sets test[0] and test[1] to zero (if that's what you want) and (optionally) initialises str.
|
66,275,694 | 66,279,856 | Find circular symlinks with boost filesystem | My program is recursively traversing a project directory, where circular symlinks may occur which raise an exception (too many levels of symbolic links) in another step of the algorithm. I'd like to find circular symlinks to avoid such exceptions. (Fixing the project by removing circular symlinks is not an option unfor... | You should be able to use boost::filesystem::canonical or weakly_canonical (in case the file need not exist).
Note that there can be performance overhead with many symlinks with many path elements, because path elements are stat-ed, building a new path instance.
Live On Coliru
#include <boost/filesystem.hpp>
#include <... |
66,275,717 | 66,277,735 | clang-tidy treats namespace as global variable when using readability-identifier-naming | I am using clang-tidy to lint source code. In the file .clang-tidy i defined:
Checks: '-*,readability-identifier-naming'
CheckOptions:
...
- { key: readability-identifier-naming.NamespacePrefix, value: n1_ },
- { key: readability-identifier-naming.GlobalVariablePrefix, value: g1_ ... | can't use clang-tidy directly on header files. Instead i have to check the cpp file and have to add -header-filter=.* to also check the headers:
clang-tidy-11.1.0 -header-filter=.* -export-fixes=fixes.txt /tmp/clangTest/mylib/source/main.cpp -- -I/tmp/clangTest/myLib/source
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.