question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
64,540,686 | 64,543,653 | C++, Why ++ operator on iterator doesn't work, if put after expression, *(v.begin() + i / 10)++? | This exercise is from Primer book (C++):
Let’s assume that we have a collection of grades that range from 0 through 100. We’d like to count how many grades fall into various clusters of 10. Between zero and 100 there are 101 possible grades. These grades can be represented by 11 clusters: 10 clusters of 10 grades each... | In the expression ++*(v.begin() + i / 10);, the begin() iterator is first incremented by i / 10, then the resulting iterator is dereferenced, and then the int being referred to is incremented.
But in the expression *(v.begin() + i / 10)++;, the begin() iterator is first incremented by i / 10, same as above. But due to ... |
64,540,778 | 64,541,804 | C++ function exits loop with exit code None | This is a problem that's part of a Coursera Algorithms course I am enrolled in. This is not to ask for an answer to the question, but I have been getting nowhere with solving it at all because my code (in the function) runs to the line before the for loop line and then it exits. This is the code:
#include <iostream>
#i... | Explicitly using push_back is one solution; just for variation though, I'll note that in this case, you could just as easily initialize the new vector from one of your existing vectors (type conversions from int to double work just fine), and then do your math in roughly the same way, rather than building element by el... |
64,541,268 | 64,541,721 | Complexity of function with array having even and odds numbers separate | So i have an array which has even and odds numbers in it.
I have to sort it with odd numbers first and then even numbers.
Here is my approach to it:
int key,val;
int odd = 0;
int index = 0;
for(int i=0;i<max;i++)
{
if(arr[i]%2!=0)
{
int temp = arr[index];
arr[index] = arr[i];
arr[i] = ... | I'm assuming you know the complexity of your partitioning (let's say A) and sorting algorithms (let's call this one B).
You first partition your n element array, then sort m element, and finally sort n - m elements. So the total complexity would be:
A(n) + B(m) + B(n - m)
Depending on what A and B actually are you sho... |
64,541,282 | 64,541,428 | Are class data members initialized before the copy constructor when using the copy constructor? | For example, if I have this class:
class Counter {
public:
int* j = new int[5];
}
A pointer variable is initialized as a data member. If in my copy constructor, I have something like
int* j = new int[7] OR int* j = new int[5](),
therefore initializing the the data member as well, will it create a memory leak for t... | A default member initializer for a non-static data member will be used in constructors where the same data member is not present in the member initializers list
[...] will it create a memory leak ... ?
Yes.
A default member initializer (DMI) as used in your example:
class Counter {
public:
int* j = new int[5]; ... |
64,541,345 | 64,541,591 | Wrapping Eigen::Vector type | I'm working on a Neural Network library and I want to use Eigen to handle the vector and matrix math behind the models but I've been told that I should't expose Eigen types in the final api so, since the network is basically going to get vectors as inputs and return vectors as outputs I was thinking about creating a cl... | The only reason I see to write a thin wrapper around the Eigen types is if you need the flexibility to change the implementation at a later point.
If you don't have this requirement, you should expose the Eigen types. It is an API your users will be familiar with and you will avoid any unnecessary conversions (copies) ... |
64,541,377 | 64,541,458 | invalid use of class::constroctor not sure what the problem is. However when using set method there's no problem | constructor of base class
Business::Business(const string& nName,const string& nAddress) { name
= nName; address = nAddress; }
constructor that i am trying to use from derived class
Restaurant::Restaurant(const float& nRating,const string& nName,const string& nAddress)
{
Business();
... | The placement of your base class construction off your derived class is wrong. It should look like this:
Restaurant::Restaurant(const float& nRating,const string& nName,const string& nAddress)
: Business(nName, nAddress) // base construction
, rating(nRating) // member initialization
{
}
By the looks... |
64,541,470 | 64,541,594 | Unresolved external symbol, array of object pointers | In my code, I want to create a dynamic array of objects. I don't know how many objects I want until the runtime, and the array's class has a dynamic variable array, so my objects can be of any size. Therefore, to make an array of them, I want to create an array of pointers as pointers are of a fixed size. Then, during ... | In olden times, it wasn't enough to declare a static variable in your class; you had to define it in exactly one source file. This is why uncommenting that line fixes your linker error.
But since C++17, you can get round this by declaring the variable as static inline in the class definition:
class Maintest {
private:
... |
64,542,421 | 64,543,777 | QuickFix c++ Unsupported message type | Im developing a bot in c++ using QuickFix, using Remarkets to test my app but my quickfix engine is rejecting almost all messages when I crack them.
Message recieved:
8=FIXT.1.1|9=116|35=h|34=3|49=ROFX|52=20201026-17:11:49.665|56=user|325=Y|335=NONE|336=[N/A]|340=2|1300=DDA|1301=ROFX|10=228|
Message sent from me (clie... | Thanks to Christoph John!!
I was overriding onMessage for FIX50, i needed to override it for FIX50SP2.
Original:
void onMessage( const FIX50::TradingSessionStatus& M, const FIX::SessionID& S)
throw( FIX::FieldNotFound,
FIX::IncorrectDataFormat,
FIX::IncorrectTagValue,
FIX::UnsupportedMessageTyp... |
64,542,433 | 64,544,500 | C++: How to properly use generator<>, task<>, and lazy<> classes available in #include<coroutine>? | I gather (from here) that the coroutine types is broadly classified into 3:
generator<> , task<>, and lazy<>
My question is: What is the difference between the three if I'm wanting to decide on the return type?
For example: What would be the return class for a co-routine that lazy-loads a set of file handlers? My imp... | I did some research and I believe the answer is as follows:
First, there is no lazy<> class in C++. The https://en.cppreference.com/w/cpp/language/coroutines has it wrong. (Refer the draft for confirmation)
So, it's a matter of distinction between the return type of generator<T> and task<T>.
TLDR;
The easiest way to re... |
64,542,624 | 64,545,052 | Lex program won't recognize word when using OR statement | I am running the following lex program which works fine to recognize the sentence about the cat:
%{
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
extern "C" int yylex();
%}
SP [ ]+
ARTICLE "le" /* Line I am trying to change */
COMMUN "chat"
V... | The flex -l flag is implemented so that it is possible to comtinue to process really old lex specifications which wouldn't otherwise work. For any newly-written scanner, you really don't want that flag. This particular issue is a common reason.
The problem comes from the handling of macro expansion: flex does the commo... |
64,542,634 | 64,542,771 | Warnings on sign conversion when assigning from the result of unsigned division | I compiled the following code with -Wsign-conversion :
int main()
{
unsigned int a = 8;
int b = a + 8u; // warning: implicit conversion changes signedness: 'unsigned int' to 'int'
int c = a - 8u; // warning: implicit conversion changes signedness: 'unsigned int' to 'int'
int d = a * 8u; // warning: implicit... | Clang is just being an extra bit clever: division of an unsigned integer by an unsigned integer larger or equal to 2 means the unsigned integer result will always fit in the signed integer counterpart (to that of the numerator type in the division expression). However, if you divide by an unsigned integer valued 1, the... |
64,543,180 | 64,543,227 | define function templated class outside of template | It's kind of hard to explain, but basically, I want to do something like this:
template <typename T>
class some{
int hello();
};
//The method needs to be defined outside of the template class declaration and be able to use T defined in the template
int some::hello(){
T* other = new T;
T->doSomething();
}
... | Here you go:
template <typename T>
class some{
int hello();
};
//The method needs to be defined outside of the template class declaration and be able to use T defined in the template
template<typename T>
int some<T>::hello(){
T* other = new T;
other->doSomething();
}
|
64,543,203 | 64,543,338 | Morse code in Arduino Mega 2560, using buttons and a buzzer | I'm trying to make a simple morse code in Arduino, using a breadboard, one buzzer and two buttons. When button1 is pushed, the output of the buzzer should be a sound signal for 200ms. If the other button (button2) is pushed, the output of the buzzer should be a sound signal for 400ms.
Also when button1 is pushed the pr... | buttonPin1 == true and buttonPin2 == true are compareing true with the pin number, not the status of pins.
You should use digitalRead() function to check status of pins.
void loop() {
// put your main code here, to run repeatedly:
noTone(buzzPin);
if (digitalRead(buttonPin1) == HIGH) { // check pin status instea... |
64,543,508 | 64,543,574 | C++ GMP equivalent of pow (a,b) using mpz_class | I'm trying to calculate a to the power of b where a and b are of mpz_class type. There aren't enough samples and explanations on the GMP manual. Here is my take with the comments:
#include <gmpxx.h>
#include <iostream>
int main(){
mpz_class r;
mpz_class a = 2;
mpz_class b = 3;
mpz_ui_pow_ui (r.get_mpz... | There is no function in GMP to raise one unbounded integer to the power of another. presumably because any such calculation would overflow with numbers that are too big to fit into fixed size integers.
The closest to what you want is mpz_pow_ui, which raises a unbounded integer to the power of a fixed size integer.
|
64,544,072 | 64,547,666 | How to force SFINAE to choose the second definition of structure? | Before that I want to tell that I have tried to implement is_assignable on my own. There is no need to show me another examples - I have already seen some implementation.
I would like to fix my solution thanks to you (if it's possible, of course) that'll work out.
So, here is my code:
#include <iostream>
#include <type... | as @Brian said, you should put the requirements at the primary template if the requirements are for all specializations, and put other requirements for each specialization at their own declarations:
template<typename T, typename = std::void_t</* global requirements */>>
struct S;
template<typename T>
struct S<T, std::v... |
64,544,196 | 64,544,267 | Where are template functions instantiated? | I believe that there are 4 situations where my question may have different answers. These situations are sorted by member vs. non-member functions and within vs. without a library.
Non-member function within a library
Suppose that I have defined a template function func in header func.h.
// func.h
template <typename T... |
In what object file is func<int> instantiated?
In every object file (aka translation unit) that invokes it or takes an address of it when the template definition is available.
Why will the One Definition Rule not be violated?
Because the standard says so in [basic.def.odr].13.
Also see https://en.cppreference.com/... |
64,544,392 | 64,544,455 | How To Run Google test from terminal on C code? | I am testing C code using googleTest.
My test.cpp file look like that
#include <gtest/gtest.h>
extern "C" {
#include "list.h"
#include "list.c"
}
TEST(ListTest, singleInsertion) {
// some tests
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
However tryi... |
However trying to run the test from the terminal using g++ test.cpp -lgtest gives Errors and warning as if the code being tested is C++ not C.
That's because you are compiling it as C++ by using the g++ compiler. Use gcc to compile as C.
Unfortunately, this code won't compile as C - it'll choke on the google::Init... |
64,544,602 | 64,544,759 | Execute Code From Memory on Windows 10 c++ x64? | I'm trying to figure out how to execute arbitrary code on Windows 10. I feel like this code should work, but it's giving me an Access violation writing location error.
#include <iostream>
#include <vector>
#include <Windows.h>
// x64 assembly
#define ret (uint8_t)(0xc3)
#define nop (uint8_t)(0x90)
int main() {
s... | Well, for one thing MEM_RESERVE means the memory isn't allocated, so trying to dereference the pointer will cause an access violation (as you saw for yourself). Don't be cute and just allocate your memory as normal, using MEM_COMMIT | MEM_RESERVE.
You also aren't setting your memory to be executable, you need to use PA... |
64,544,804 | 64,544,916 | How can I erase first and last character in string? | This function returns an array of strings with a list of files in a folder. It looks like this:
"folder//xyz.txt"
How can I make it look like this?
folder//xyz.txt
Its the same but without "".
vector<string> list_of_files(string folder_name)
{
vector<string> files;
string path = folde... | Erasing the first and last characters of a string is easy:
if (str.size() >= 1)
str.erase(0, 1); // from 1st char (#0), len 1; bit verbose as not designed for this
if (str.size() >= 1)
str.pop_back(); // chop off the end
Your quotes have come from inserting the path to a stream (quoted is used to help prev... |
64,544,862 | 64,546,807 | Constexpr check if static_cast of pointers between two hierarchically related types changes the pointer value | For some specialised allocator-like thing I'm implementing, I would like to require that all objects that are going to be stored share a common base class as their first subobject. This allows me to keep a single pointer the common base class as both an indicator of the start of the object as well as to regain access t... | You are asking about is pointer interconvertibility. There is a related trait std::is_pointer_interconvertible_base_of which isn't implemented yet in gcc and clang. See also the paper and issue. Pointer interconvertible types have the same address and their pointers can be casted between with reinterpret_cast.
I assum... |
64,544,890 | 64,544,898 | how can i fix the error: 'std::vector' has not been declared | using std::vector;
vector<int> d1(n);
for (int i = 0, l = 0, r = -1; i < n; i++) {
int k = (i > r) ? 1 : min(d1[l + r - i], r - i + 1);
while (0 <= i - k && i + k < n && s[i - k] == s[i + k]) {
k++;
}
d1[i] = k--;
if (i + k > r) {
l = i - k;
r = i + k;
}
}
I was learning... | You need to add #include <vector> above using std::vector;
|
64,544,936 | 64,545,074 | Comparing polymorphic types in c++20 | I have code that is somewhere between c++17 and c++20. Specifically, we have c++20 enabled on GCC-9 and clang-9, where it is only partially implemented.
In code we have quite big hierarchy of polymorphic types like this:
struct Identifier {
virtual bool operator==(const Identifier&other) const = 0;
};
struct UserI... | As an intermediate solution you could re-factor your polymorphic equality operator== to a non-virtual operator== defined in the base class, which polymorphically dispatches to a non-operator virtual member function:
struct Identifier {
bool operator==(const Identifier& other) const {
return isEqual(othe... |
64,546,285 | 64,546,366 | Are dynamic arrays allocated contiguously in memory? | int* arr = new int[5];
Are the values of the array pointed by arr allocated contiguously in the heap?
Thanks.
| The right syntax for a dynamic array is int* arr = new int[5];. Yes, it will be allocated contiguously.
This is not a recommended way of using an array. If you know array size at compile time and it is not too large, make it local: int arr[5]; or std::array<int,5> arr;. Otherwise, use std::vector<int> arr(5);. new shou... |
64,546,376 | 64,546,458 | Why is my vector not returning the last stored value? | I'm trying to store two different values with the same key in an unordered_map. To do so I used a vector to hold the values.
I want to recall a previously store value if the index is specified when I call with store->get() or else it returns just the latest value.
When I run my test code, it always returns the first va... | The problem is in the set function where you do this:
auto vec = container[key];
Here you create a copy of the vector, and only add the value to the copy. The original vector remains unmodified.
You can use references to get a reference to the original vector instead:
auto& vec = container[key];
// ^
// Note ampersan... |
64,546,908 | 64,547,098 | Properties of the stride in a glTF file? | The Khronos docs define the stride as:
When a buffer view is used for vertex attribute data, it may have a byteStride property. This property defines the stride in bytes between each vertex.
I am somewhat confused as, many of the examples I have tried already (3 of them) had a stride of 0 so I merely ignored the attr... | Yes, accessors (in glTF) are like vertex attributes in OpenGL/WebGL, and are allowed to interleave. The stride is on the bufferView, to force accessors that share that bufferView to all have the same stride. A value of zero means "tightly packed".
Note that you may interleave components of different sizes, such as ve... |
64,547,131 | 64,551,426 | Destruction of local static objects | Consider a situation like this:
#include <iostream>
int foo() {
static struct S {
int value;
S(int a): value(a) {}~S() {
std::cout << "End is nigh";
}
}
s(42);
return s.value;
}
int main() {
return foo();
}
In implementations of compilers, I researched these re... | This is a known problem with a known solution, which unfortunately is rather complex. The best approach I know is the Phoenix Singleton from Modern C++ Design. In short, you can rely on the values of non-class singletons, and you can reuse the memory of s to recreate an S object in the same location.
An alternative app... |
64,547,478 | 64,547,910 | How do I fix my program that calls a template function using parameters of different types? | I cannot figure out how I would call a template function that is suppose to take a string and College object as the parameters in my main.cpp.
This is my template in LinkedListADT.h:
#ifndef LINKED_LIST_H
#define LINKED_LIST_H
#include "ListNodeADT.h"
template <class T>
class LinkedList
{
private:
ListNode<T> *he... |
How would I define a template class that could be one or two
parameters? (from a comment)
You could do this by using variadic templates, but that's not what you need here. Instead, you need a template member function of the single-argument template class, like this:
template <class T>
class LinkedList
{
//...
pub... |
64,548,031 | 64,551,166 | C++ bubble sort on vector using callback switch | I have been trying to bubble sort a vector of int data which has been taken from a multi line text file. I have managed to seperate the data from the vector so that I have only the elements I need to sort, however I am having an issue getting the code to run using a vector. I am reusing code I have made earlier when so... | Your compilation error is because you have called the comparison function with no arguments, and not passed it as a parameter.
You also have the issue that a non-static member function requires a Sorter (which this will point to).
The parameters of the comparison function need to be elements of the vector.
I would advi... |
64,548,132 | 64,548,351 | How to cast double-pointers of a base class to double-pointer of derived class? | If I pass a double-pointer to a class or function how can I cast it to either a double-pointer of a derived type or a reference to a pointer of a derived type so that I can access its members?
class A
{
};
class B : public A
{
public:
void Method() {};
};
A *a_ptr = new B{};
void Function(A *const *a_ptr_ptr)
{... |
If I pass a double-pointer to a class or function how can I cast it to either a double-pointer of a derived type or a reference to a pointer of a derived type
You cannot.
so that I can access its members?
You don't need a pointer to pointer to access members. What you need is a pointer. You can get that by indirect... |
64,549,021 | 64,549,252 | converting data from matrix to array from opencv matrix frame | I want to extract the data from a frame of opencv matrix in 420 video format. 420 Format means read the first channel as it is i.e. full first channel. For the second and third channel in frame read in such a way that read alternate rows and columns i.e. for the second channel we will read pixel (0,0) then (0,2) then (... | Crash is caused by reading out of bounds
arr[arrInd++] = chr;
because by the line
uchar * arr = new uchar(arraySize);
you allocate only one byte. It should be: uchar * arr = new uchar[arraySize]; - the way of creating dynamic array.
|
64,549,262 | 64,555,614 | DirectX Index Buffer -> Start of Index Buffer | I am Currently Working on Direct11 Graphics API, I am Wondering Why Index buffer has This Formula?
Start of Index Buffer = Index Buffer Base Address + Offset (bytes) + StartIndexLocation * ElementSize (bytes);
I am Wondering What Does This Mean . Someone please Help Me With This
Full Reference Docs ->
https://learn.mic... | The indices you gonna fetch depend on the following pieces of data.
The content of the index buffer.
Offset that you have passed to IASetIndexBuffer. That value is in bytes.
StartIndexLocation that you have passed when you submit a draw call such as DrawIndexed. That one is in elements, not in bytes. Direct3D 11 onl... |
64,549,271 | 64,550,224 | How Does the Compound Modulo Work in C++? | I have been trying to create simple program which divides an input number into peso bills. The output I need is
Enter Amount: 7350
P1000: 7
P500: 0
P200: 1
P100: 1
P50: 1
P20:0
P10:0
P5:0
P1:0
and this was my initial code:
#include <iostream>
using namespace std;
int main()
{
int const P1000(1000);
int const P500... | Here is a small program to illustrate the difference:
#include <iostream>
int main()
{
int i = 256;
std::cout << "i: " << i << ", i % 100: " << (i % 100) << std::endl;
std::cout << "i: " << i << ", i % 12: " << (i % 12) << std::endl;
std::cout << "i: " << i << ", i % 3: " << (i % 3) << std::endl;
... |
64,549,581 | 64,567,710 | How to launch OneNote and bring it to the foreground using OLE automation? | I've been struggling bringing OneNote to the foreground using OLE automation. When I run the following code, OneNote loads in the background and I'm not able to bring it to the foreground. I haven't had any problems trying to launch and bring Word, Excel, PowerPoint and Edge to the foreground, however OneNote behaves d... | You can create a new windows with this call
piOneNote->NavigateTo(NULL, NULL, VARIANT_TRUE);
|
64,549,647 | 64,549,874 | C++ Updating values in a unordered_map, where the data type of key-value pair is int-unordered_set | I was solving a DSA question and observed a slightly strange behavior in the C++ standard template library:
vector<int> v = {1, 7, 8, 3, 12};
unordered_map<int, unordered_set<int>> ump;
for (int i=0; i<v.size(); i++) {
unordered_set<int> us;
us.insert(56);
ump.insert(mp(v[i], us));... | unordered_set<int> us = ump.find(v[i])->second;
Makes a copy of the set so your modifications don't change the value in ump. You need to use a reference instead:
unordered_set<int>& us = ump.find(v[i])->second;
Or using auto:
auto& us = ump.find(v[i])->second;
|
64,549,791 | 64,549,862 | How to configure clang-format to take UTF-8 character's length as shown rather than its real bytes length? | When I input some UTF-8 character rather than simple ASCII, I find that clang-format will take the character's length as how many bytes expressed, rather than as the length show in terminal.
For example:
测 is stored in 3 bytes, but it takes 2 ASCII space in vim or other editors.
The expected formatted code should be as... | clang-format already detects UTF-8. It doesn't need to be told to do it. So you're dealing with a bug here that you should report to their bug tracker:
https://bugs.llvm.org/
Make sure you have tested with the latest clang-format version though. 11.0.0 as of right now. You don't want to report a bug from an old version... |
64,550,165 | 64,550,220 | Issue while converting from const string to const u8_t * | I have the following code
In .hpp file
class A
{
private:
static std::string hello;
}
In .cpp file
const std::string hello= "hi";
B(hello, strlen(hello)); // where B(const u8_t* a, u8_t b)
Which cast should I use?
I want to convert const string to const u8_t * eventually.
u8_t is unsigned char
| u8_t is a non-standard type. I'll assume it's the same as the standard uint8_t.
Another unanswered question is whether the B type treats null bytes in any special way, I'll assume not.
So strlen(hello) doesn't compile. That should be replaced by hello.size(), which is the correct way to get the size of a C++ string.
Fi... |
64,550,908 | 64,551,328 | Vector of number to string in hexadecimal format | I created a vector std::vector<uint8_t> vec{ 0x0C, 0x14, 0x30 };
I want to return the values of the vector in a string "0CD430".
I created this simple code:
std::string vectorTostring(const std::vector<uint8_t>& vec)
{
std::string result;
for (const auto& v : vec)
{
result += std::to_string(v);
... | I would suggest using a std::stringstream and some output manipulators like so:
#include <sstream>
#include <iomanip>
#include <vector>
#include <string>
#include <iostream>
std::string vectorTostring(const std::vector<uint8_t>& vec)
{
std::stringstream result;
for (const auto& v : vec)
{
result
... |
64,551,003 | 64,551,247 | Does C++ exception framework require kernel support? | I am reading about exception support in C++, probably the result applies to other languages as well.
https://wiki.osdev.org/C%2B%2B_Exception_Support
http://www.ucw.cz/~hubicka/papers/abi/node25.html
There is lots of stuff going on, I am a bit overwhelmed. My question is during the unwinding process, does C++ require h... | No.
AFAIK this is all implemented in the C++ runtime library (for GCC this would be libgcc_s.so, at least on Linux). This requires code to walk the stack to look for catch blocks and some machine code to jump into such blocks if found. As already mentioned, setjmp/longjmp also do not require the kernel.
Update: don't m... |
64,551,392 | 64,570,505 | Boost log and dynamically loaded libraries | We are using Boost.Log v2 (1.70) in our application which is available for Windows and Linux. Recently I refactored a dynamically loaded dll to also use Boost.Log.
The dll exports C api functions to access dedicated hardware. It is used in various programming environments: C, C++, Python, Delphi and also Labview. (Most... | Thank you Andrey Semashev and Ulrich Eckhardt.
I now understand that the library implementation of Boost.Log restricts its usage.
Invalid usage: A application links boost log (as dll) and dynamically loads another api.dll (linked statically to boost log static with static runtime) by using dlopen(Linux) or LoadLibrary(... |
64,551,655 | 64,555,924 | C++ lock_guard vs mutex.lock() | I have a loop like this:
for (auto &i : elements)
{
std::lock_guard<std::mutex> lock(i.mutex);
some heavy writing to disk with i
}
Throwing an error:
tpp.c:62: __pthread_tpp_change_priority: Assertion `new_prio == -1 || (new_prio >= __sched_fifo_min_prio && new_prio <= __sched_fifo_max_prio)' failed.
Can someone ... | Okay, I guess I found my answer. Thanks everyone for sorting things out. @molbdnilo was closest to the problem. Indeed there was an undefined behaviour in the rest of my code. Running Valgrind showed me invalid read and write operations on the lock_guard. My mutex is stored in a shared pointer, which is being reset by ... |
64,551,723 | 64,551,915 | How to take screenshot of complete desktop Windows c# | Below code is taking screenshot of desktop window only. My expectation is to take screenshot with taskbar and everything visible to the user.
Any help would be appreciated
'''
{
//Creating a new Bitmap object
Bitmap captureBitmap = new Bitmap(1024, 768, PixelFormat.Format32bppArgb);
//Bitmap cap... | This should work fine for you, duplicate question here
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(bitmap as Image);
graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
|
64,552,003 | 64,552,216 | Addition of two numbers using constructor with only one parameter | Here I need to add two numbers, but my constructor has only one parameter. And it should be has one parameter. Using the addFunc I need to add my two different numbers.
int result = 0;
class Num{
private:
int a;
public:
Num(int a) {
a = a;
}
int getA(){
return a;
}
void setA(int a){
a = a;
... | Expanding on Bob__'s suggestion it seems likely that your code is supposed to look something a bit like this
class Num {
private:
int a;
public:
Num(int a) {
this->a = a;
}
int getA() {
return a;
}
void setA(int a) {
this->a = a;
}
int addFunc(Num other) {
... |
64,552,021 | 64,552,228 | How to cin edges to each vertex? | I am kinda new into object orinted programming. I am trying to input edges to each vertex but nothing seems to work out for me.
I want to write two numbers into console on 1 line. For example if n = 4 and m = 3, I can write into console something like:
1 1
2 4
3 4
#include <iostream>
#include <vector>
using namespace ... | You need to read two numbers from cin first:
int src, dst;
cin >> src >> dst;
And then update the neighbours of the corresponding objects:
auto srcP = &vertices[src-1];
auto dstP = &vertices[dst-1];
srcP->neighbours.push_back(dstP);
if (src != dst) dstP->neighbours.push_back(srcP);
|
64,552,024 | 64,552,289 | How can I find repeated words in a vector of strings in C++? | I have a std::vector<string> where each element is a word. I want to print the vector without repeated words!
I searched a lot on the web and I found lots of material, but I can't and I don't want to use hash maps, iterators and "advanced" (to me) stuff. I can only use plain string comparison == as I am still a beginne... | Minimalist approach to your existing code. The auto-increment of j is what is ultimately breaking your algorithm. Don't do that. Instead, only increment it when you do NOT remove an element.
I.e.
for (int i = 0; i < my_vec.size(); ++i) {
for (int j = i + 1; j < my_vec.size(); ) { // NOTE: no ++j
if (my_vec... |
64,552,853 | 64,553,561 | Creating trackbar changing brightness of image OpenCV | I've got a problem with creating a trackbar which would adjust brightness of the displayed picture.
This is my code (part which is involved with brightness):
int brightness_value = 25; //global values
const int max_value = 255;
int main()
{
Mat brightImage;
srcImage.copyTo(brightImage);
namedWindow("Bright Imag... | createTrackbar takes a pointer to callback function which is called when position of trackbar is being changed. In this callback you should redrawn your image with changed brightness level and refresh window by imshow. Such callback takes a pointer to void data - it enables you to pass any data you want to use when red... |
64,554,235 | 64,554,372 | Passing inline temporary class in c++ needs to be const. How to work around this | I want to write portable code in c++11 for different CPU's (actually MCU's). As some CPU's does not support reading program data directly through it's memory address space (such as Atmel AVR), I need a solution that calls a function either with a direct address, or with a custom made Stream pointer to read the data tro... | With C++11 you can simply take an rvalue reference as a parameter.
void PrintMessage(IStream && stream)
rvalue references will bind to temporaries, and will mostly be indistinguishable from lvalue references, in this context.
|
64,554,365 | 64,554,641 | c++ code behaves differently within Linux than Windows? | I recently moved from windows to linux i was used to learn c++ with Visual-studio,
now i try to write something in linux and it behaves different for example:
#include <iostream>
#include <iomainip>
int main(){
char a {'a'};
char* b { &a };
size_t count {16};
for(size_t i{};i < count;i++){
std::cout << std::hex;
... | You are probably trying to do some like:
#include <iostream>
#include <iomanip>
int main(){
char a {'a'};
char* b { &a };
std::cout << static_cast<void*>(b) << ": " << *b;
}
// Output: 0x7fff41d27787: a
You have to cast a char pointer otherwise cout will handle it as a C-string. Dereferencing *(b + i) ca... |
64,554,497 | 64,554,627 | Adding numbers from a struct to a variable in my code | struct estudiante {
string apellidos ;
string nombres ;
int anioIngreso ;
int anioActual ;
float promedio ;
} ;
struct recibido {
string apellidos ;
string nombres ;
int anioEgreso ;
float promedio ;
} ;
bool continuar () ;
bool tipoIngreso () ;
estudiante ingresoEstudiante () ;
re... | estudiante ingresoEstudiante () ;
The shown code declares ingresoEstudiante to be a function that takes no parameters and returns an estudinate object. That's what this declaration means in C++.
sumaPromedios += ingresoEstudiante.promedio ;
This line of course appears to access a member called promedio in some objec... |
64,554,835 | 64,557,035 | Writing read_jpeg and decode_jpeg functions for TensorFlow Lite C++ | TensorFlow Lite has a good C++ image classification example in their repo, here.
However, I'm working with .jpeg and this example is restricted to decoding .bmp images with bitmap_helpers.cc.
I'm trying to create my own jpeg decoder but I'm not well versed in image processing so could use some help. I'm reusing this jp... | Library you are using is already handling decoding for you, decoder.getImage() contains raw rgb data. You do not need to calculate any sizes whatsoever.
Stuff like row_size is something specific to BMP file format. BMP files may contain some padding bytes in addition to pixel color data, the code was handling that stuf... |
64,555,248 | 65,412,058 | Integrating C++ coverage with sonarqube | I am using Google test framework for C++ unit tests. We are building our projects using MsBuild (runs on teamcity). Now, I want sonarqube to parse the coverage info. We have cfamily plugin in sonarqube. The compatible reports with cfamily plugin are bullseye, vscoverage, gcov, llvm-cov. As per my knowledge, because we ... | I made the paths in coverage report generated by OpenCppCoverage using OCCSonarQube plugin. Now SonarQube is able to parse the report in generic format.
|
64,555,281 | 64,555,351 | How to validate pointer to std vector internal array | I would like to write to internal array of vector. I could write using data() if vector is initialised.
However if the vector is empty (but having enough storage), I am not able to write directly to internal array of vector.
#include <vector>
#include <iostream>
using namespace std;
void write_seq(int *v, size_t len)... | You cannot assign to an element that does not exist. Allocating memory is not sufficient, but your code is fine when you resize the vector (or create it with sufficient elements):
int main(void)
{
vector<int> v(10); // vector with 10 element
write_seq(v.data(), v.size()); // ... |
64,555,784 | 64,556,642 | How to write in-class function from non-class function c++? | I have merge function which is a non-class.
Merge.cpp
template <typename T>
vector<T> merge(vector<T> left, vector<T> right){
vector<T> result;
int left_current = 0, right_current = 0;
while(left_current < left.size() && right_current < right.size()){
if(left[left_current] <= right[right_current]){
... | So I'm going to spout some platitudes.
Functions that are pure -- that take explicit input and return explicit output -- are easier to reason about.
Be lazy, do less work.
Methods are, in general, impure; they operate on the object they are attached to, taking and returning its entire state implicitly. So if the f... |
64,555,841 | 64,555,997 | Can't get greyscaling right by multiplying RBG pixels with numbers? | I really went through everything I could find but image processing is still pretty confusing.
As the simplest of tasks, I want to greyscale 4 pixels. The problem that the output is not grey using either of the two sets of numbers I found. Thank you for your help!
My algorithm right now (sadly I can't use opencv only th... | You're falsely assuming that the pixels are stored R1G1B1R2G2B2R3G3B3.
In CImg the pixels are stored As R1R2R3....G1G2G3...B1B2B3....
see the docs
|
64,556,511 | 64,556,925 | What are the advantages and disadvantages of an ordered list? | I'm currently trying to figure out what the advantages from the disadvantages of having an ordered list are, but I'm over here struggling to find the importance. I know that ordered lists can allow for binary search which is much more efficient over sequential search. Otherwise I'm at a loss though.
| Ordering your data has many costs and benefits.
You are right in that it does enable a binary search. But there are many ways to structure data so that searching for an element is fast; in the C++ standard library, std::set maintains its elements in order, while std::unordered_set doesn't, and the second is usually fa... |
64,556,634 | 64,556,808 | Error when overloading operator<<, "cannot overload functions distinguished by return type alone" | I'm parsing two text files that describe tests. For that purpose, I have two structs to hold test instances:
struct testcase_xy {
public:
testcase_xy() = default;
testcase_xy(float x_, float y_, float yaw_, float pitch_) :x(x_), y(y_), yaw(yaw_), pitch(pitch_) {}
friend std::ifstream& operator>> (std::ifstr... | Inside the structure:
struct testcase_mat {
// [...]
friend std::ifstream& operator>> (std::ifstream& in, testcase_mat& m);
friend std::ofstream& operator<< (std::ostream& out, const testcase_mat& m);
^^^^^^^^^^^^^
};
Outside:
std::ostream& operator<< (std::ostream& out, const testcase_mat& m)... |
64,556,857 | 64,556,956 | Can I cast a unsigned long to size_t without loss of data? | size_t is a unsigned integer type, that is returned by (for example) sizeof. Can I therefore cast an unsigned long into it? What problems could occur? Should I use static_cast or reinterpret_cast, or another?
EDIT:
I want to convert a string into an unsigned long and then cast that to size_t:
size_t StringHandling::Con... | Can you safely cast a std::size_t to unsigned long?
Generally… no.
If unsigned long has the same width as std::size_t on your system, then you'd get away with it with a simple static_cast. But why take the chance? If it doesn't, and this is by no means unlikely on systems that exist today, you'll be potentially truncat... |
64,557,186 | 64,557,279 | Is there a way to display stacked text in QTextEdit | Is there a way to display stacked text in a QTextEdit? By stacked text, I mean fraction, or exponent
Is there a way to achieve this without table or html conversion?
| AFAIK, Qt is using Unicode, and UTF-8 does have glyphs like ½ (i.e. U+00BD VULGAR FRACTION ONE HALF).
However, I would indeed recommend switching to HTML.
You might also study the source code of Qt (it is open source) and subclass QTextEdit as wanted
|
64,557,292 | 64,560,687 | How can I use the MSVC compiler from Github Actions? | I want to have a pipeline which compiles my code with MSVC++ cl compiler, since my native project is done in Visual Studio. How can I import these tools, and on which Operating Systems are they available on?
| I found a GitHub repo that allows you to use MSVC++ tools. Just add this before your job:
- uses: ilammy/msvc-dev-cmd@v1
Here's my workflow file for reference:
https://github.com/satanic-santa/spark/blob/master/.github/workflows/compile.yml
|
64,557,294 | 64,559,611 | Is it possible to pass arguments to std::make_unique() when allocating an array? | In the code below, is there any way that I can pass an argument to the demo constructor when using std::make_unique() to allocate a demo[] array?
class demo{
public:
int info;
demo():info(-99){} // default value
demo(int info): info(info){}
};
int main(){
// ok below code creates default constructor, to... | std:::make_unique<T[]>() does not support passing arguments to the constructor of array elements. It always invokes the default constructor only. You would have to construct the array manually, eg:
std::unique_ptr<demo[]> pt3(new demo[5]{200,200,200,200,200});
Which is obviously not going to be useful if you have a ... |
64,557,407 | 64,557,624 | Simple constexpr - C26498 warning and C2131 error | I am trying to learn about const and constexpr and have run into the error C26498 on VS2019. However, my example is almost the same as described here:
constexpr int myInt();
constexpr int getMyValue();
void foo();
int main()
{
int val1 = myInt(); // C26498 warning (mark variable constexpr)
const int val2 = myI... | The error occurs because, at the point of use (in the constexpr int val3 = myInt(); line), the compiler does not have a definition of myInt(), and so cannot (safely) deduce a compile-time constant value.
The solution is to put that definition of the myInt function before its use (where you currently have its forward de... |
64,557,525 | 64,557,977 | How to solve LINK : fatal error LNK1181: cannot open input file 'vtkCommonCore-9.0.lib' | I use the library OpenCasCade for a C++ project on windows. I have updated it to 7.4.0 with conda. A new version of vtk (vtk-9.0.1) came with it
I build the project with CMake. There was no problem before the update and since, when I compile I have the message LINK : fatal error LNK1181: cannot open input file 'vtkComm... | As suggested on this link
vtk_link
I added the command in my CMakeLists.txt
find_package(VTK REQUIRED COMPONENTS CommonCore RenderingOpenGL2)
But nothing changed.
Finally,
I have solved the problem. From conda the package OCCT came with a vtk dependency. I have chosen the same OCCT version (7.4.0) but with a former ... |
64,557,560 | 64,557,754 | C++ lambda for sort algorithm | I'd like to sort a map<pair<string, int>, int> dbg; by value using lambda :
For this I have
void test()
{
map<pair<string, int>, int> dbg;
sort( dbg.begin(), dbg.end(),
[]( pair<pair<string, int>, int>& lht, pair<pair<string, int>, int>& rht) {
return lht.second > rht.second;
});
}
But compilat... | Sorting a map is nonsensical; it's already sorted, and you can't change the sort order after the fact by sorting it (the order can't be changed at all except by adding and removing elements, and they'll always fall into a fixed order). If you want to sort it in a different way, either:
Provide the alternate comparator... |
64,557,616 | 64,557,940 | How to call superclass method in multiple-inheritance? | I have a class C that inherits both from Ai and B. A and B are unrelated. This is all best explained with the code below. In main(), I have a variable a defined as std::unique_ptr<A>, but initialized with C. I cannot change this definition.
My question is, given a defined like this, how can I call functions defined in ... | You can static_cast to C*:
static_cast<C*>(a.get())->fun_b();
static_cast<C*>(a.get())->fun_c();
static_cast<C*>(a.get())->fun_ai();
or you could make it polymorphic:
class A {
public:
virtual ~A() = default;
void fun_a() { std::cout << "fun_a\n"; }
};
and then dynamic_cast:
dynamic_cast<B*>(a.get())->fun_b... |
64,558,184 | 64,559,433 | How to use aggregated initialization in derived class with CRTP pattern? | The standard that I use is c++17.
The problem is that I want to remake my code and reorganize the structure of my code with CRPT because it fits very well but the problem is that previous code uses aggregated initialization within classes like:
ClassWithNoParent get(const T_& unit) const {
return {.w = 1,
... | The problem is unrelated to CRTP. Aggregate initialization of derived classes was only introduced in C++17. To aggregate-initialize a derived class, the base class must be initialized as the first item, in its own initializer list. So to get this working, use a double-brace:
return {{.w = 1, .h = 1, .c = 1, .n = 1}};
... |
64,558,258 | 64,559,032 | C++ "Using" in Modules | One of the reasons "using namespace" in header files is considered bad practise (Why is "using namespace std;" considered bad practice?) is because it "leaks" the using-directive to everyone that includes your headerfile. Is this still the case for C++ modules or can I "safely" put e.g. using namespace std or using std... | The scope of any using declaration of this sort is the translation unit being compiled. All module files (a file that starts with some form of module declaration) is a separate translation unit. So it will be just like any other non-exported declaration in your module: local to it.
That having been said, this is only o... |
64,558,510 | 64,558,566 | why calling a variable as remove()'s argument gives an error? | I am new to c++ and I'm trying to create a class with a constructor that takes a name and creates a file "name.txt". But I want this class to have a method to remove the created file.
The problem is: if I use
#include <iostream>
using namespace std;
int main() {
remove("name.txt");
return 0;
}
it works per... | remove is an old-fashioned function that takes a const char* as an argument.
That's why it works for a string constant. ("name.txt" is a const char[9] type that decays to a const char* pointer.)
remove(filename.c_str());
will achieve this for a std::string.
Your ill-advised use of using namespace std; is bringing in a... |
64,558,622 | 64,558,962 | How can we find the element in a dataset, that satisfies the given condition and its sequential number in the dataset (C++)? | The first line of the standard input contains the number of elements(N) (1<=N<=100). The next lines contain a number (M) (1<=M<=300), as we know, there can be maximum 100 "M" elements.
We need to find the smallest number, that is larger than 120. In the first line of the standard output, we need to print the sequential... | This is what I thought of after reading your question and looking at the input. I think you made a small mistake in your question - it should be smallest number greater than 120. Check out the code given below:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, ans = INT_MAX, pos = -1;
cin >> n;
f... |
64,558,881 | 64,590,049 | Plain struct from protocol buffer message | Is there a way to obtain a simple struct from protocol buffers message in C++?
i.e.
struct PlainFoo {
int32_t bar;
float baz;
};
from
message Foo {
required int32 bar = 1;
required float baz = 2;
}
I obtain some data over network in a protocol buffer and I'd like to be able to add it to other similar data and... | I'm not aware of a C++ protobuf library that would generate plain structures, but there are C libraries that can be used in C++ code also. At least nanopb and pbtools generate simple structs:
/* nanopb */
typedef struct _Foo {
int32_t bar;
float baz;
} Foo;
/* pbtools */
struct Foo_t {
int32_t bar;
f... |
64,558,913 | 64,558,966 | syntax error: ']' was unexpected here, despite the fact that there is no extra ']' anywhere? | Visual Studio 2019 is saying that there is a syntax error on line 30, it is saying there is an unexpected ']' despite the fact that the only closing bracket is closing an opening bracket.
I don't know why this is occurring, this has never happened to me, I genuinely do not know what to do.
template <class T>
void Defin... | C++ isn't that clever yet.
You need new int[3] {255, 0, 0}; which will create an array of 3 ints with the values 255, 0, and 0.
I believe this will be fixed in later standards.
|
64,559,143 | 64,559,586 | Range queries on a binary string? | Binary-Decimal
We are given a binary string S of length n, in which each character is either '1' or '0'.
And we are asked to perform several queries on the string.
In each query we are given integers L and R.
And we have to tell the value of sub-string S[l..r], in decimal representation.
Sample testcase:
Input:
1011 ... | Define V[k] to be the value of the digits of S starting with the kth one.
Then the value of the substring S[l..r] = (V[l] - V[r+1]) / 2^(n - r - 1). (Something like that, I may have an off by one error. Play with small examples.)
Now the useful fact about 10^9 + 7 is that it is a prime. (The first 10 digit prime.) W... |
64,559,156 | 64,559,213 | Can't call the outOfBound function | I can't seem to call this no matter how I tried. It says Error: use of undeclared identifier "outOfBound". How do I call the outOfBound function to my hh function properly? Thanks
void hh(int var1, int var2, int var3, char char_a, char char_b, char array[10][10])
{
if(outOfBound(var1, var2, var3))
{
cou... | You declared the function after trying to use it, it has to be before:
bool outOfBound(int var1, int var2, int var3);
void hh(int var1, int var2, int var3, char char_a, char char_b, char array[10][10])
{
if(outOfBound(var1, var2, var3))
{
cout << "Error: image access out of bounds (0, 0)";
exit... |
64,559,278 | 64,559,347 | c++ program runs correctly, but the same python program not | My task is:
C2[9]. Given natural number N. Remove from the number the third digit (from left). Example #1. N = 1256; answer: 126. Example #2. N = 432; answer: 43. Example #3. N = 98; answer: 98.
I wrote the code in c++ and it works according to the task. I tried the same task in python but there the output is wrong...
... | Here x//10 changes the variable only in memory, not overwrites the variable, so try (x = x//10):
x = 10292989
xx = x
if x <= 99:
print(x)
else:
d=1
while x > 999:
x = x//10
d = d**10
x = x//10
fin = x * d + xx % d
print(fin)
|
64,559,346 | 64,559,529 | How to introduce a struct in the std namespace | We currently use C++11.
std::optional is missing from C++11 - it has been introduced in C++17.
Luckily, I found an implementation which has the same interface as std::optional and works in C++11 (https://github.com/TartanLlama/optional)
This defines optional in namespace tl.
So, I can use it like so:
#include "optional... |
How to introduce a struct in the std namespace
By writing a proposal to the standards committee. But in this case the class is already adopted, so what you need to do to get the class is start using the new version of the standard.
How can I create some sort of an alias in this header, so that when I call std::optio... |
64,559,925 | 64,564,249 | How pass Eigen matrix row reference (to be treated as a vector) to a func implemented in another .cpp? | Hope you can help me.
My question derives from another question answered here
Inside that page rhashimoto gives a good answer to a similar question:
#include <iostream>
#include <Eigen/Core>
template<typename V>
void set_row(V&& v) {
v = Eigen::Vector3f(4.0f, 5.0f, 6.0f);
}
int main() {
Eigen::Matrix3f m = Eige... | This is best done with templates in a header.
If you must put this in a CPP file, you can use a template function and explicit instantiation, as you suggested. The key is to use the Eigen Block type.
#include <Eigen/Dense>
template <int N, int M>
void set_row(Eigen::Block<Eigen::Matrix<float, N, M>, 1, M> row) {
//... |
64,560,467 | 64,593,667 | Reading Point Clouds from .las files | I'm working on a project that's using .las lidar files.
I googled and found that PDAL can be used to convert .las to .pcd files, so that I can use the PCL library.
I converted files from .las to .pcd using PDAL.
When I tried to read the pcd files using the following code:
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(n... | I would suggest that you take a close look at the PCD writer documentation for a number of helpful pointers for this particular conversion.
The issue here is that, while double precision floats are valid PCD, they are not supported by PCL's default point types. You could hand edit the PCD file you've already converted,... |
64,561,059 | 64,561,093 | the string variable acting strangely | I tried making a little program that checks if a string is a substring of another. I think got the logic down correctly, but i encountered a problem concerning data types. I declared 2 strings and gave them a value instantly and they worked fine, but the other one, the checker variable, works in a weird way. It can not... | checker is not a std::string, it's an array of std::string, and as a primitive type, does not have a .length() function.1
If you want that, you'll need to use this instead:
std::vector<std::string> checker;
Where then you can add as many as you see fit:
checker.push_back(text[i]);
And later:
cout << text << " " << ch... |
64,561,101 | 64,561,443 | How can I pass my class into its own constructor? | I have a class:
class ActivityClass{
public:
ActivityClass *from;
vector<ActivityClass> inside;
string name = "default";
vector<string> tags;
AcvitityClass(){} // def constructor
ActivityClass(string aName, ActivityClass aFrom){
name = aName;
from = &aFrom;
aFrom.... | This is probably a case for pointerizing all your arguments:
class ActivityClass {
public:
ActivityClass *from;
std::vector<ActivityClass*> inside;
std::string name = "default";
std::vector<std::string> tags;
ActivityClass() : from(nullptr) { }
ActivityClass(const std::string& aName, Acti... |
64,561,396 | 64,626,766 | Defining new POSIX-like character class names in C/C++ | I'm currently working on a project in c++ to use regex as HTTP FRC rules. In the RFC 1945, Chapter 2.2 - Basic Rules there are the following rules:
CHAR = <any US-ASCII character (octets 0 - 127)>
CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
CR = <US-ASCII CR, c... | You need a kind of a metalanguage and some compiler for it. It is not a task for just C++ preprocessor or/and compiler's constant folding or other compile-stage features.
With the metalanguage you will describe your variant of extended RE. Then your compiler will parse that and generate some input for the main projec... |
64,561,575 | 64,562,576 | How can you perform arithmetic on an element of a non-type parameter pack? | I want a method that returns an object with a modified parameter pack. For example, the Nth template parameter is increased by 1.
template<size_t... Ni>
struct Test
{
template<size_t Nth>
constexpr auto RunTest()
{
// What should be written here?
}
};
int main()
{
Test<2, 2, 2> t1;
Test... | If you can afford a helper method, the following way should work starting from C++14:
#include <utility>
#include <type_traits>
template <std::size_t... Ni>
struct PackHolder
{
template <std::size_t Nth, std::size_t ... Is>
constexpr auto IncrementHelper (std::index_sequence<Is...>)
-> PackHolder<(Ni + (N... |
64,561,994 | 64,562,229 | Undefined Reference to non-member operators from dll | For an assignment I created a fractions class that overloads many operators. I then converted it into a dll to be used by another program. The issue I am having is that when I try to use the non-member operators I get the error "undefined reference to 'operator+'".
I believe I have implemented the dll correctly as the ... | Short version: you need to properly export/import our library objects and code.
Long Version:
Somewhere in your header will be a macro definition similar to the following:
#ifdef MYDLL_EXPORTS
#define MYDLL_API __declspec(export)
#else
#define MYDLL_API __declspec(import)
#endif
This macro is later used in a variety ... |
64,562,174 | 64,562,236 | Why using string results in exit code 3 and using char[] doesnt | I'm practicing my coding skills and I was solving the following backtracking problem (the solution of the original guide is in there as well).
Summary of the problem:
Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them.
My solution is the following:
#... | std::string::reserve() doesn't do what you think it does, i.e. it doesn't increase the actual size of the string.
Use std::string::resize() instead.
|
64,562,257 | 64,648,457 | Avoid `delete[]` accepting an implicit pointer conversion? | I have a class with an implicit conversion operator to a pointer. Deallocating that pointer is not valid. Can I prevent the conversion to a pointer when used with the delete[] operator? I would like a compile time error. For the free function, I can delete an overload that takes the class as an argument.
void foobar(do... | As a workaround, you can prevent the conversion to a pointer when used with the delete[] operator by making the conversion ambiguous.
However, depending on the situation of the rest of the code, this may cause undesirable ambiguity for the desired use cases.
struct A {
operator double*() const { return nullptr; }
o... |
64,562,306 | 64,562,535 | Instantiate constructor with Class pointer as a parameter | a.hpp file:
namespace hello
{
class A : public hi::B
public:
A(C* my_hello);
private:
const C* p_hello;
};
a.cpp:
hello::A::A(C* my_hello)
: m_name(0);
{
}
In b.cpp file:
hello::A *random = new hello::A();
//-> Error in this line saying no instance of constructor
How to instantiate... | In your .hpp file, you aren't defining a constructor for A, you typed hello(...) instead.
Also, since you defined a constructor, your class doesn't have a default constructor anymore (i.e. one that doesn't need any arguments).
When calling the constructor of your class in the new expression, you must supply al needed a... |
64,562,876 | 64,563,161 | Ignore template parameter | Is there a way in the code below to say that I don't care what the V parameter is in void watch(event<T, _> &e)
#include <stdlib.h>
#include <stdio.h>
enum events_a {
A_1,
A_2,
};
enum events_b {
B_1,
B_2,
};
template<typename T, T V>
class event {
public:
T id(void) {
return V;
}
};
... | You could specify a default argument for V and static assert like the way below:
enum events_a {
A_1 = 1,
A_2,
};
enum events_b {
B_1 = 1,
B_2,
};
template<typename T, T V = {}>
class event {
static_assert(V != 0, "You should Define a V");
public:
T id() {
return V;
}
};
template... |
64,563,173 | 64,563,419 | State Machine Change State | I'm continuously running into the same problem, and can't fix it even when looking through tutorials.
I've "set up" my State machine, but I can't transition between states.
Here is my StateMachine:
class StateMachine
{
State* m_State;
public:
StateMachine();
~StateMachine();
void changeState(State* sta... |
But when I implement it I can't access the StateMachine from A::handleInput()
Well, that's a well known problem with the State Pattern, that there's no mention how to keep the state classes in track with an enclosing State Machine.
IMO, that's one of the valid use cases to consider the StateMachine class as being imp... |
64,563,430 | 64,563,786 | Why (or when) does a template bring in its namespace? | Here's an example:
#define MAKE_IT_WORK false
namespace Bob { // Bob's project namespace
struct DeviceFrequency {};
extern void debugf(const char* fmt, ...);
} // namespace Bob
namespace SSN { // Super-Secret Namespace
namespace debugging {
extern int ssn_debug;
extern void debugf(const char* fm... | For a template, ADL includes the namespaces and entities associated with the
types of the template arguments provided for template type parameters. Because the call to debugf includes this as a parameter, ADL will include namespace Bob because the template is instantiated with Bob::DeviceFrequency.
|
64,563,909 | 64,564,157 | Unable to discriminate template specialization with enable_if and is_base_of | I am trying to trade some run-time checks for compile-time checks to identify the base class of an object with template specializations.
The code compiles fine, but I can't figure out why the enable_if statement always end up invalid or equal to void because I'm always landing on the base template struct.
#include <ios... | The second parameter to enable_if doesn't need to be specified. If you do specify it, it needs to somehow resolve to void. Since you've specified the second parameter as T, this doesn't work.
Instead, just do this:
template<typename T>
struct get_category_impl<T, typename enable_if<is_base_of<BaseOne, T>::value>::type>... |
64,564,909 | 64,565,042 | Is disallowing accessing the elements of an array with a different type than usize a design choice? | I am trying to access an element of an array. I am sure that the type that I am trying to use is enough to index the whole array and a 64-bit index is overkill.
I have minor experience in C and C++ and I know that it's possible there.
I am unsure about several points and want to ask:
Is it a design choice?
Are C and C... |
Is it a design choice?
Yes, for reasons described below.
Are C and C++ converting the type to usize when trying to access an element of an array?
Yes. Indexing into an array is defined as arithmetic on a pointer, and pointers are usize-sized by definition (32 bits on 32-bit systems, etc.)
Can I convince / force Ru... |
64,564,963 | 64,565,123 | What happens when getline() reads a line that is larger than system memory? | Suppose C++ getline() reads from some file that has a single huge line that exceeds the memory capacity of the system (there's no newline before it exceeds memory capacity). What does a while(getline(cin, line)) loop do then?
And, if I need to handle this possible edge case by throwing an exception or something, how wo... | If std::getline() reads up to std::string::max_size() characters, it simply stops reading and sets the failbit flag on the input stream.
std::string is likely to throw a memory error like std::bad_alloc long before than happens, though.
|
64,565,151 | 64,565,768 | What's the C++ equivalent of C#'s decimal type? | I like decimal in many of my C# programs and I want to try it in other C languages.
I wrote this code in C#:
using System;
decimal get_pi();
int main() {
Console.WriteLine("Give a number ranging from 1-100: ");
decimal num = Console.ReadLine();
Console.Write("Algebraic Equivalent: ");
if (num >= get_p... | There is not, though I believe there's a proposal out there.
But if you navigate over to IBM Fellow Mike Cowlishaw's page General Decimal Arithmetic, you'll
Learn more than you ever wanted to know about the topic — he pretty much wrote the IEEE 754 specification for decimal floating point — and
Get a link to an ANSI C... |
64,565,160 | 64,565,678 | How to use variadic templates to proceed std::variant with std::visit? | I'm trying to write a logic, with usage of command and factory patterns. Based on a data inside the std::variant I want to create an object. It may look like a map of C++ types.
Here is the code: Wandbox
I can hardcode all used types but I want to automate it with variadic templates, how to do it?
#include <cassert>
#i... | This popular little "overloaded" class is always useful for passing lambdas to std::visit:
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
Then, instead of using a generic lambda and trying to deduce the right object type from ... |
64,565,539 | 64,565,596 | Program immediately shuts down after entering value | I am learning c++ and decided to make a program that estimates the value of sine and cosine using the Taylor series method.
There are no compiler errors, however when I run the program the moment the user enters a value the program just closes. I tried to use a hard value and the program shuts down right away as well. ... | The program is not crashing it is just reaching the end of its code. You can add
system("pause");
to the end of you int main to keep the app from closing
or If you are using visual studio 2019 hit f5 to run your program. It will not exit when It is done
|
64,565,863 | 64,618,049 | Rcpp not working on R 3.6.3 macOS Catalina 10.15.7 | Rcpp used to work on R, but no longer, and I do not know why.
library(Rcpp)
evalCpp("1+1")
A long list of errors is returned, beginning with
Error in sourceCpp(code = code, env = env, rebuild = rebuild, cacheDir = cacheDir, :
Error 1 occurred building shared library.
continuing with
/usr/local/clang7/include/c++/... | I found the answer to this question in a post by Christian Herz, here:
https://discourse.slicer.org/t/macos-catalina-10-15-5-compilation-error/12807/8
Header files on my Mac were disordered, with symlinked duplicates of the correct header files in /Library/Developer/CommandLineTools incorrectly placed in /usr/local/inc... |
64,566,851 | 74,412,218 | Error: libm.so.6 : version `GLIBC_2.29' not found. NodeJS | I've written a native library wrapper for SDL2 in C++ for NodeJS, which is in a working condition, but now I've come to a point where I've upgraded from NodeJS 10.19.0 to 15.0.1 LTS and have encountered the following error:
Error: /snap/core18/current/lib/x86_64-linux-gnu/libm.so.6: version `GLIBC_2.29' not found (requ... | Bit late to my own show, but I've since worked out the issue: On my system, snap packages cause issues with LibCs, especially for NodeJS installations. Since I'm working with lower-level system resources, Snap pushes obstacles in the way.
The solution was to use a straight nodejs install from APT.
|
64,567,127 | 64,567,334 | Writing to a JSON file using c++? | Suppose I have a JSON object as follows :
{
"Tickets": [
{
"Name" : "Alice Parker",
"Age" : "21",
}
]
}
The above text is from a Names.json file.
I want to append more objects into Tickets Array.
Suppose I have another Object as follows:
{
"Name" : "Tony Stark",
... | Looking at the documentation here, something like:
json theData;
// read from file to theData
theData["Tickets"] += R("
{
"Name" : "Tony Stark",
"Age" : "21",
}
)"_json;
// or .push_back()
Might work. Without sample code, though, I cannot test.
|
64,567,154 | 64,618,179 | Different behavior for qualified name lookup with using-directive when making namespace inline | I am learning using-directives, and trying to understand the name lookup rules for using-directive, but I encountered this problem and I cannot found any explanation.
The problem looks like this:
prog1: namespace C is outside of namespace A:
#include <iostream>
namespace C
{
namespace Detail
{
void func... |
[namespace.udir]/2 A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive. During unqualified name lookup (6.4.1), the names appear as if they were declared in the nearest enclosing namespace which contains both the ... |
64,567,188 | 64,600,592 | Linking CUDA with a project added as external project from subdirectory | I am working on a fork of a project here. As you can see the main project and other dependencies are all added with ExternalProject_Add() in the outer CMakeList.txt. I want to add a simple CUDA project that I had written here, to the main iris-distro project that I have forked. Simply put, I want to be able to call fun... | After spending a few more hours, it seems that I have found some way to fix it.
I copied funcs_cuda.cuh, funcs_cuda.cu and directory of helper functions cuda-matmul/inc into iris-distro/src/cxx.
In iris-distro/CMakeLists.txt: cmake variable for CUDA root was set:
set(CUDA_TOOLKIT_ROOT_DIR "/usr/local/cuda-8.0")
Also... |
64,567,607 | 64,567,931 | Why is there an error "no matching function for call to 'A(A<...auto...>)'"? | In C++20, we have better NTTPs, which allows literal class types:
template <typename T>
struct A{};
template <A> // note: it is a placeholder for NTTP A<T>
struct B{};
But when I try to specialize a template for B:
template <typename>
struct is_B{};
template <A x>
struct is_B<B<x>>{}; // error!!!
The compiler (GCC ... | It seems that GCC doesn't like placeholders for deduced class types as NTTP, which should be accepted as per [temp.param]/6 (emphasis mine):
A non-type template-parameter shall have one of the following
(possibly cv-qualified) types:
a structural type (see below),
a type that contains a placeholder type ([dcl.spec.au... |
64,567,646 | 64,567,714 | I am not able to typecast char to int in the indices | I am new to C++,this problems seems to be basic. I am using char in the indices of array, everything seems to be correct, I don't understand why I am not able to fetch the value from the array, please help me!. even after typecasting char is not converting to int. The code runs fine if I use menu[n-'0'].
#include<iostr... | So let's say that at the line cin >> n you type in "1" at the console. Then n holds the value '1', i.e. 49. If you cast this to an integer, it gives you the integer 49.
If you subtract '0', i.e. 48, from this, then it gives you a result of 1.
Also, even after subtracting '0', you should validate the input, because if... |
64,567,896 | 64,568,138 | The output value is a big integer that is incorrect and doesn't change with changing input | I am writing a code that the user will input three numbers and the output will be the sum of the numbers between and the first number that their sum of digit is between the second and the third number and when i try to test code the output is constant and incorrect with different inputs.
#include <iostream>
using nam... | You didn't initialize the variable sum, on some linux system, the variable will be initialized with arbitrary value. Please add this line
sum = 0;
before the if statement.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.