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 |
|---|---|---|---|---|
70,318,258 | 70,318,438 | Exclamation mark in C++/CLI | I was reading this article by Microsoft on how to marshal managed classes to native and the other way round, and I came across these lines:
this->!context_node();
protected:
!context_node()
{
// method definition
}
I searched on Google and StackOverflow for the meaning of exclamation mark (!) in the abov... | !classname() is the finalizer.
Since these are managed classes, their lifetime is controlled by the garbage collector.
If you implement a method ~classname(), that's the Dispose method because it's C++/CLI. It's not the destructor like in plain C++. If you implement it, the compiler automatically makes your class imple... |
70,318,806 | 70,318,807 | Avoiding repetitive copy-paste of static_cast<size_t>(enum_type) for casting an enum class to its underlying type | I have an enum type in my code, like this:
enum class GameConsts: size_t { NUM_GHOSTS = 4 };
I find myself repeating the required static_cast to get the enum value:
Ghost ghosts[static_cast<size_t>(GameConsts::NUM_GHOSTS)];
// and...
for(size_t i = 0; i < static_cast<size_t>(GameConsts::NUM_GHOSTS); ++i) { ... }
What... | Your first option is to use a constexpr instead of an enum:
constexpr size_t NUM_GHOSTS = 4;
You can put it inside a proper context, such as GameConsts struct:
struct GameConsts {
static constexpr size_t NUM_GHOSTS = 4;
};
Then there is no need for a casting:
Ghost ghosts[GameConsts::NUM_GHOSTS];
In case you ac... |
70,318,986 | 70,327,558 | wxWidgets/C++/Code::Blocks: Failed to import font from system library | I've been making a simple app in C++/wxWidgets that just has a catalog of Garfield comix from the Internet, without the annoying ads and offers. (Don't ask me how I got access to the PNG files of each comic in the first place, because my name already explains that)
Anyway, I'm trying to make a static text with a specif... | Turns out, I just made a silly mistake.
The real code I should have used is:
wxFont *CC_FONT_Tahoma_Bold = new wxFont(8, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Tahoma"), wxFONTENCODING_DEFAULT);
|
70,319,077 | 71,465,275 | Can special member functions be defaulted if they use typedefs? | Clang compiles this fine, but GCC and MSVC complain that operator= cannot be defaulted:
#include <type_traits>
template<class T>
struct S
{
typedef typename std::enable_if<!std::is_enum<T>::value, S>::type Me;
S &operator=(Me const &) = default;
};
int main()
{
S<int> s1, s2;
s1 = s2;
}
Is this code ... | Given the lack of any indications to the contrary, I'm going to answer my own question and say that, as far as I've been able to find relevant clauses in the standard, I think the code is legal and thus GCC and MSVC are complaining erroneously.
As someone pointed out above, there appears to be a bug report tracking thi... |
70,319,094 | 70,319,303 | How to automatically adjust width for text with SDL2_TTF | I'm working on a score display for my simple 2d SDL_2 Game.
This is the part of my code where I display the speed (basically just score):
void Renderer::renderText(const char* text, SDL_Rect* destR)
{
SDL_Surface* surfaceText = TTF_RenderText_Solid(Renderer::font, text, { 255,255,255 });
SDL_Texture* textureText... | (I only answered this because I found out how and nobody else answered)
You can do something like this.
SDL_Rect destR = { x, y, 0, 0 };
TTF_SizeText(font, text, &destR.w, &destR.h);
Basically, TTF_SizeText enables you to get the native width and height from the text with font. Then you can just multiply the height an... |
70,319,354 | 70,319,507 | Sum function in C++ with unknown number of arguments and types | The first part of question is create a function (Sum) with unknown number of arguments, i've done it . It works very nice. But i have the struggle in second part , argument with different type like: int, float, double ... in one function call . Any ideals i can fix my program ???
Thanks for your attention.
I think a l... | The problem is you assume double as arguments, see this line:
double el = va_arg( arguments, double );
the usual solution is to provide format of the arguments passed to function, like in printf - but I suppose you don't want to do it.
I can suggest you use variadic templates like in this example:
template<typename T>... |
70,320,031 | 70,320,160 | Variadic expansion to access multi-dimensional std::array | Suppose the following multi_array structure:
template <typename type, std::size_t... sizes>
struct multi_array
{
using storage_type = typename storage_type<type, sizes...>::type;
using value_type = type;
using size_type = std::array<std::size_t , sizeof...(sizes)>;
using difference_type = std::a... | Something along these lines, perhaps:
template <size_t level, size_t max_level>
struct Access {
template<typename Store>
static reference At(Store& store, const size_type& position) {
return Access<level + 1, max_level>::At(
store[position[level]], position);
}
};
template <size_t level>
struct Acces... |
70,320,941 | 70,322,279 | Can I use classic Borland & clang compiler for the same application | I'm looking for some advice on how to migrate a C++Builder 5 project to Embarcadero C++Builder 11.
Some of the DLLs can only be compiled with the 'classic' Borland compiler. The rest can be compile with the Clang-compiler.
Can I use 2 different compilers in the same application?
|
I'm looking for some advice on how to migrate a C++Builder 5 project to Embarcadero C++Builder 11.
That is a very massive upgrade. A LOT has changed over the decades between the two versions. I hope you are reading the docs in Embarcadero's Migration and Upgrade Center, for starters.
Some of the DLLs can only be com... |
70,321,047 | 70,343,177 | How CRC16 using bytes data is woking ? (for CAN bus implementation) | I have some trouble implementing a CRC16 for can message, I followed the instructions given by this website https://barrgroup.com/embedded-systems/how-to/crc-calculation-c-code and http://www.sunshine2k.de/articles/coding/crc/understanding_crc.html#ch5, plus other implention I have seen in here ( for example Function t... |
I don't understand how it is processed.
Maybe it will help to describe the bit by bit operations for 8 bits of data:
crc[bit15] ^= data[bit7]
if(crc[bit15] == 1) crc = (crc << 1) ^ poly
else crc = crc << 1
crc[bit15] ^= data[bit6]
if(crc[bit15] == 1) crc = (crc << 1) ^ poly
else crc = crc << 1
...
crc[bit15] ^= data[... |
70,322,230 | 70,322,382 | Why does extern template instantiation not work on move-only types? | The following code is ok:
#include <memory>
#include <vector>
extern template class std::vector<int>;
template class std::vector<int>; // ok on copyable types
int main()
{
[[maybe_unused]] auto v1 = std::vector<int>{}; // ok
[[maybe_unused]] auto v2 = std::vector<std::unique_ptr<int>>{}; // ok
}
However, ... | Explicit instantiation definition (aka template class ...) will instantiate all member functions (that are not templated themselves).
Among other things, it will try to instantiate the copy constructor for the vector (and other functions requiring copyability), and will fail at it for obvious reasons.
It could be preve... |
70,322,262 | 70,322,483 | Why is "insert" of unordered_set Undefine Behavior here? | I am sorry for my fuzzy title.
Suppose there are some pointers of nodes, and I want to collect the nodes' pointers with unique value.
struct node_t
{
int value;
node_t(int v = -1) : value(v) {}
};
For example, if we have 4 pointers:
p1 points to node(1)
p2 points to node(1)
p3 points to node(2)
p4 points to no... | The short version is that your hash and equality operations are incompatible. When you insert an element, first the hash is taken, then the bucket for that hash is checked to see if an equivalent element is present.
Let's say there are three buckets named A, B, and C. You insert n1 and it ends up in, let's say, bucket ... |
70,322,288 | 70,322,409 | Reverse iterators and negative strided iterators in C++, using one before beginning as sentinel | In Another way of looking at C++ reverse iterators Raymond Chen wrote:
... a quirk of the C++ language: You are allowed to have a pointer
"one past the end" of a collection, but you are not allowed to have a
pointer "one before the beginning" of a collection.
I understand that it probably means "undefined behavior" a... |
But I am curious what is the worst that can happen in a realistic
system if one ignores this rule. A segmentation fault? an overflow of
pointer arithmetic? unnecessary paginations?
Wasted space.
To be able to form the address "one before" you need to have the space available. For example, if you have a 1k struct, it ... |
70,322,507 | 70,345,640 | Why LLVM's leak sanitizer not working when using with other sanitizers enabled | I was trying to find a memory leak from a simple program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
void parse(const char* input) {
// Goal: parse out a string between brackets
// (e.g. " [target string]" -> "target string")
char *mutable_copy = strdup(input);
/... | Problem solved. It turns out that on OS X, lsan is integrated into asan, and one must manually use ASAN_OPTIONS=detect_leak=1 to enable lsan when using asan. It seems that if one uses -fsanitize=address,leak, clang thinks that this leak parameter is redundant since address sanitizer already includes leak sanitizer. If ... |
70,322,930 | 70,322,991 | How to pass a constexpr as a function parameter c++ | I have a simple function that populates an array with double values and returns the array:
double create_step_vectors(int n_steps, double step_size)
{
std::array<double, n_steps + 1> vec{};
for (int i = 0; i <= n_steps; i++)
{
arr[i] = i * step_size;
}
return arr
}
I pass in n_steps which i... | You cannot use a function parameter where a compile-expression is expected, because the parameter is not constexpr, even in constexpr function (your constexpr function could also be called with non-constexpr values).
In your case, the easiest solution is probably to use a non-type template parameter:
template <int n_st... |
70,323,234 | 70,323,270 | make a counter in c++ which calculate the number of steps | I make a program which require from the user to enter a number then make this number reach 1 by doing a loop if the number reach an odd value the program will multiply it by 3 then add 1 to it
if the number reach an even value the program will divide it by 2 ... until reachig 1 .so i make a counter to count the number ... | You haven’t init counter variable so it can contain any number. Set it to zero when declare:
int counter = 0;
|
70,323,434 | 70,323,482 | C++11 about *begin(a) | #include<iterator>
#include<iostream>
int a[5][4];
int main()
{
cout << *begin(a);
}
Why does this cout print the same as begin(a)?
It seems the * does not dereference the pointer returned by begin(a)?
Can anyone tell me why?
| Here * affects only the type of the pointer, and not its numerical value.
std::begin(a) returns a pointer to the first element of a, of type int (*)[4] (pointer to an array of 4 ints).
*std::begin(a) returns int[4]. Since cout can't print arrays directly, the array then decays to the pointer to its first element, of ty... |
70,323,837 | 70,323,871 | How to use the global comparison operator when comparing two different structure types to resolve the errors in C++ | When I am trying to compare members of two different structures, getting the below errors:
error C2676: binary '==': 'main::strRGBSettings' does not define this operator or a conversion to a type acceptable to the predefined operator
error C2678: binary '==': no operator found which takes a left-hand operand of type '... | As the compiler error says, you need to define operator== for your strRGBSettings struct:
struct strRGBSettings {
uint8_t red;
uint8_t green;
uint8_t blue;
bool operator==(const strRGBSettings& stg) const {
return stg.red == red && stg.blue == blue && stg.green == green;
}
};
If you cannot ... |
70,324,040 | 70,325,075 | how to distinguish between no time and midnight in COleDateTime class | We use the DD-MM-YYYY HH:mm:ss date and time format API between frontend and backend.
However, there are cases that backend gets only the date since time wasn’t selected at the frontend side.
The GET call parameter will look like this:
startTime=16-11-2021
At the backend side, we use the COleDateTime class in order to... | COleDateTime has a function GetStatus() that is able to tell if the object has no value at all. In all other cases, it's valid. This means that there is no distinction between "no time" and midnight. The type seems designed to encode an absolute point in time. Date-only or time-only hijack this encoding with 0 compo... |
70,324,047 | 70,325,794 | How to convert winrt::hstring to int in C++ Winui application? | I have used the template called Blank App, Package (Winui 3 in desktop) inside Visual Studio. I want to make a really simple function which add 2 value together. This is what the application looks like.
This is the XAML code:
<StackPanel>
<TextBox x:Name="Box1" PlaceholderText="First number"></TextBox>
<TextBo... | I found a method.
std::string number_1 = winrt::to_string(Box1().Text());
std::string number_2 = winrt::to_string(Box2().Text());
int number1 = stoi(number_1);
int number2 = stoi(number_2);
int sum = number1 + number2;
winrt::hstring h_string_sum = winrt::to_hstring(sum);
answer().Text(h_string_sum);
|
70,324,055 | 70,325,835 | Is there any workaround for passing a function template as a template parameter? | I'm trying to make a function template that takes a function template as a template argument and then returns the result of that function when invoked with the normal function parameters passed in. It would be used like this:
auto fooPtr = func<std::make_unique, Foo>(...);
The point of the function is to allow templat... | You can't pass a templated function as a template argument unfortunately unless you specify the template arguments explicitly, e.g.:
template<auto T>
auto func(auto&&... args) {
return T(std::forward<decltype(args)>(args)...);
}
struct Foo { Foo(int i) {} };
int main() {
auto unique_foo = func<std::make_uniqu... |
70,324,119 | 70,324,296 | Why is assigning an int to enum type valid in OpenCV _InputArray::kind()? | I think assigning and int value to an enum variable is invalid in C++, and there's already questions verifying this, such as cannot initialize a variable of type 'designFlags' with an rvalue of type 'int' .
However I just see the following code not causing compile error:
// https://github.com/opencv/opencv/blob/4.x/mod... | opencv define the operator & itself so it no more result in int
you can see it just below the section you linked
__CV_ENUM_FLAGS_BITWISE_AND(_InputArray::KindFlag, int, _InputArray::KindFlag)
link
Implementation of the macro
#define __CV_ENUM_FLAGS_BITWISE_AND(EnumType, Arg1Type, Arg2Type) ... |
70,324,402 | 70,324,492 | Why is the output different even though the expressions are the same in lambda expression? | I have problem about lambda expression like this:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int sum(vector<int>& v){
int total = 0;
auto lambda = for_each(v.begin(), v.end(), [&total](int n){total += n;});
lambda; // lambda expression doesn't work.
for_each(v.beg... | according to cppreference, the for_each(...) call returns the UnaryFunction which was passed to the function.
In this case, the for_each returns the UnaryFunction
[&total](int n){total += n;}
a lambda(5) would increase the total value by 5.
A solution would be to put the for_each call in a separate function - which is... |
70,324,964 | 70,325,133 | Question about using string arrays as function parameters | I am a novice, I encountered a little problem today, I hope to get someone's answer, thank you very much.
Code show as below。
#include<iostream>
using namespace std;
void sub(char b[]){
b[] = "world"; //I alse try b*/b,but it is not ok
}
int main(void){
char a[10] = "hello";
sub(a);
cout<<a<<endl;
... | strcpy(b, "world"); // need <string.h>
But I would use std::string (instead of c-string) directly.
#include<iostream>
#include<string>
using std::cout;
using std::string;
void sub(string &b){
b = "world";
}
int main(){
string a = "hello";
sub(a);
cout << a << endl; // output
system("pause");
... |
70,325,557 | 70,326,295 | How do i make a piezo play 3 times and then stopping in Arduino? | EDIT: https://www.tinkercad.com/things/ampvgOj75D1
This is the link to my tinkercad project witch contains the wiring of the circuit, sorry that i forgot it's also needed to get the code working.
I need this code to make the piezo play 3 times and then stopping it completely, the while() loop does not work for some rea... | Your actual code not work due to variable i is incremented in every loop. So this mean i is more then 3 in very short time and if statement is still false.
If you move i++ statement inside if, your code not leave while loop, because CurrentMillis is not updated.
My recomendation:
use Serial.println("message"); to trac... |
70,325,993 | 70,326,049 | Casting weak_ptr<IBase> to weak_ptr<Derived> | I am trying to create object pooling with an interface base using smart pointers. However I cannot access the derived object without casting it from a weak_ptr to a raw pointer, which kind of kills the purpose of smart pointers. Also it warns me it is vulnerable to the dangling pointer state.
Yes the code compiles, but... | To avoid the dangling pointer issue you need to ensure that a shared_ptr will be alive for the entire time you need access to the object. Then, use dynamic_pointer_cast to execute a dynamic_cast on the pointee:
if (auto sharedPtr = weakPtr.lock()) {
std::weak_ptr enemy0 = std::dynamic_pointer_cast<EnemyEntity>(shar... |
70,326,228 | 70,326,344 | Output buffer empty in iconv , while converting from ISO-8859-1 to UTF-8 | In linux I have created a file with Turkish characters and changed file characterset to "ISO-8859-9". With below cpp, I am trying to convert it to UTF-8. But iconv returns empty outbuffer. But "iconv" returns "inbytesleft" as "0" means conversion done on input. What could be the mistake here?
My linux file format:
[ro... | man 3 iconv
The iconv() function converts one multibyte character at a time, and for each character conversion it increments *inbuf and decrements *inbytesleft by the number of converted input bytes, it increments *outbuf and decrements *outbytesleft by the number of converted output bytes.
output is updated to point... |
70,326,638 | 70,326,816 | Opencv, can't get destroyAllWindows to work | OpenCV 4.5.4, C++ and Win10.
Probably my syntax doesn't compute with this, but can anyone spot a fix to my problem? I can get the usb webcam window to open and it shows the stream. But I cannot close it.
This opens the window but brings no image in stream at all:
cv::imshow("Smaller", resized_down);
int c = cv::waitKey... | your first code should work with this fix (break; is always executing in your code!):
cv::namedWindow(“Smaller”);
while(true){
…
cv::imshow("Smaller", resized_down);
int c = cv::waitKey(1);
if ((char)c == 'c'){
cv::destroyAllWindows();
break;
}
…
}
|
70,326,861 | 70,328,042 | C++ CUDA: Why aren't my block dimensions working? | I'm using an example from a book to solve a 4x4 matrix multiplication. However, the book only provides the kernel code, so the rest of the program is down to me. The book says to use a block width of 2, however I cannot get this to work with dim3 variables. Here is the kernel:
__global__ void matmul_basic(float *c, flo... |
it thinks the block size is 1x1x1?
Yes.
Why aren't my block dimensions working?
Because this:
dim3 dimBlock = (2, 2, 1);
is not doing what you think it is doing, and it is not the proper way to initialize a dim3 variable. You might want to spend some time thinking about what the expression (2,2,1) evaluates to in... |
70,326,968 | 70,339,954 | Show tooltip at mouse position and show legend on top-right corner | The following toy problem show two tabs, each tab contains a QGridLayout, which has a ScrollArea on one of the cells, which in turn contains a customized QLabel (MyLabel). When the user moves his mouse on the customzied QLabel, a tooltip shows up for several seconds.
test.pro
QT += core gui widgets
CONFIG += c++17
CON... | Cursor postion can be retrieved by using QCursor::pos(), so both problems can be sovlved by using QCuros::pos() in paintEvent. I was confused by the fact paintEvent does not directly provide cursor position, as mouseMoveEvent does.
|
70,327,211 | 70,327,367 | selection sort using recursion | void swap(int a[], int x, int y)
{
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
void sort(int arr[], int x)
{
static int count = 0;
if (x == 1)
{
return;
}
int min = 100; // random value
int index;
for (int i = 0; i < x; i++)
{
if (arr[i] < min)
{... | Replace swap(arr, count, index); with
swap(arr, 0, index);
and remove static int count = 0;.
Replace sort(A, x); in the main with
sort(A, x - 1);
and change the condition if (x == 1) to if (x == 0).
I suggest to rename index to last.
Replace min = 100; with
min = arr[0];
|
70,327,567 | 70,327,659 | How to initialize a std::vector from variadic templates with different type each? | My main problem is that i'm trying to create a function that initialize a std::vector of a class that can be initialized by different ways, so I decided to use variadic templates, but, like in this example, that does not compile:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct MyCl... | You need to put the variadic argument last and you could use a fold-expression to populate vec. You could also make it do perfect forwarding:
#include <utility> // std::forward
template<typename... Args, typename T>
void mc_vector_(vector<MyClass>& vec, T&& t, Args&&... args) {
vec.emplace_back(std::forward<T>(t)... |
70,327,648 | 70,327,670 | Overloading << and >> as outside member functions for template class | I am trying to define my operator overloading outside the class like this:
template <typename Type>
class myClass
{
...
friend std::ostream& operator << (std::ostream&, const myClass&);
friend std::istream& operator >> (std::istream&, myClass&);
...
}
template <typename Type>
std::ostream& myClass<Type... | For starters the friend functions are not member functions of the class where they are decalred.
So these declarations in any case are incorrect.
template <typename Type>
std::ostream& myClass<Type> :: operator << (std::ostream& out, const myClass<Type>& other) { ... }
template <typename Type>
std::istream& myClass<Ty... |
70,327,741 | 70,327,918 | Is it possible to write multiple characters in C++ Assembly with no stdlib? | I am developing a operating system, following this tutorial, and I'm on part 7 (chapter 7), and he shows how to print a character to the screen, but I want to print multiple characters but it just overwrites the previous character. Here is my code
extern "C" void main() {
// printf("Hello, World!");
*(char *)0x... | @user2864740 sent me a link that helped me fix it, as it turns out, every 2nd character written to 0xB8000 is a color.
So if you wanted to print Hello!, I'm pretty sure you would do
*(char*)0xB8000 = "H";
*(char*)0xB8001 = 15;
*(char*)0xB8002 = "e";
*(char*)0xB8003 = 15;
*(char*)0xB8004 = "l";
*(char*)0xB8005 = 15;
*(c... |
70,327,977 | 70,328,175 | How to Manually call a Destructor on a Smart Pointer? | I have a shared_ptr for an SDL_Texture in a game I'm making. I want to use a shared pointer to be able to use the same texture on multiple objects without leaking any memory. I have the shared pointer return from a method which is
std::shared_ptr<SDL_Texture> RenderWindow::loadTexture(const char *filePath) {
retur... | You can release the ownership of the object by calling reset() on the shared_ptr. If that is the last one holding the pointer, the shared_ptr's deleter member will be used to destroy the object.
https://en.cppreference.com/w/cpp/memory/shared_ptr/reset
|
70,328,542 | 70,328,632 | While loop and do while loop only running once in a calculator program. C++ | Was trying to run a simple calculator using a while loop and internal class. My issue is that I used a while loop that had the condition that when a boolean called flag is equal to true it would continually run the program over and over. To exit the while loop I included a section to ask the user if it wanted to contin... | In C++ bools are stored as 0 or 1 values. 0 is false and 1 is true. If you're putting in "true" for the cin statement it won't work so loop will always increase. What you have to do is put in 0 or 1 into the console. You could also store the input as a string and use if statements to check if it is "true" or "false" an... |
70,329,898 | 70,329,970 | Specialization doesn't contain data that's declared in the primary template | class Base {
public:
virtual void load() = 0;
};
template<typename T>
class CustomConfig : public Base {
public:
const T& getData() { return data; }
T data;
};
template<>
class CustomConfig<std::set<uint32_t>> {
public:
virtual void load() {
this->data = {4, 5, 6};
}
};
I don't know why I... | To provide an alternative to the other answers, which all say you must add your data member, there's another option which is to derive from a template instantiation instead:
class CustomConfigSetOfUInt : public CustomConfig<std::set<uint32_t>> {
public:
void load() override {
this->data = {4, 5, 6};
}
}... |
70,330,230 | 70,330,660 | Read 2d array from txt file in c++ | This is my code
#include<bits/stdc++.h>
using namespace std;
int main()
{
char arr1[10][10];
cout << "Reading Start" << endl;
ifstream rfile("test.txt");
rfile.getline(arr1[10], 10);
int i, j;
for (i = 0; i < 6; i++)
{
for (j = 0; i < 6; j++)
{
cout << arr1[i][j]... | There are a lot of other ways to perform the specific task, but i guess your method is not wrong, and you have just made a simple typing mistake in your second for loop condition. so ill just fix your code for you.
and also you could just input single values at a time as u go.
#include<bits/stdc++.h>
using namespace st... |
70,330,314 | 70,331,227 | Shortest path question involving transfer in cyclic graph | I'm trying to solve a problem of graph:
There are (n+1) cities(no. from 0 to n), and (m+1) bus lines(no. from 0 to m).
(A line may contain repeated cities, meaning the line have a cycle.)
Each line covers several cities, and it takes t_ij to run from city i to city j (t_ij may differ in different lines).
Moreover, it t... | Your visited set looks wrong. The "nodes" you would feed into Djikstra's algorithm cannot simply be cities, because that doesn't let you model the cost of switching from one line to another within a city. Each node must be a pair consisting of a city number and a bus line number, representing the bus line you are cur... |
70,330,570 | 70,331,147 | How are pairs stored in memory in C++? | I was just reading about pairs in C++ when this doubt stroke my mind that how the pairs are stored in memory and id the identifier assigned to the pairs a object or something else.
pls explain how an array containing pair uses memory to save the pairs and how can we iterate through the that array, by accessing each pa... | As for the pair itself, if you take a look at the standard library source code you'll just notice, that after cutting all the boilerplate, the for the most trivial case std::pair is just a simple class template:
template<typename First, typename Second>
struct pair
{
First first;
Second second;
};
Now, all the boi... |
70,331,033 | 70,331,080 | Vector parameter in a function doesn't seem to actually apply to input? | I have a vector variable named intVec, and I have a function named pushBack, that accepts a vector of type integer just like intVec, but when I actually pass that vector into the function in order to push_back the x parameter, nothing seems to happen.
Output expected from intVec.size() is 1
Output given from intVec.si... | That is because you pass the vector by value instead of by reference (or pointer).
This means, that when you call the function, the vector you call 'push_back' on is actually an independent copy of the original vector, which get deallocated upon leaving the function.
Try this header instead:
void pushBack(int x, std::v... |
70,331,109 | 70,406,085 | Visual Studio Code "python.h: No such file or directory" windows gcc | I 'm a total beginner in C++ and getting crazy trying to embed Python in C++ using VS Code IDE and GCC compiler.
I am stock and now I 'm keep facing this silly error that says:
python.h: No such file or directory gcc
I have followed steps explaned in "Using GCC with MinGW in VS Code" in order to configure C++ in VS C... | The problem was a combinations of simple mistakes and as a beginner I solved it by some digging in gcc -l -L option flags for library link example and gcc arguments docs.
There are several simple and important points that should be observed:
1. The order of options is really important. If its wrong, compiler wont work.... |
70,331,486 | 70,331,660 | Second function with same integers doesn't work | I have a task to create 2 functions to calculate GCD and LCM. But I noticed that my second function doesn't work not matter what calculation is there. What am I doing wrong ?
#include <iostream>
using namespace std;
int gcd(int number1,int number2);
int lcm(int number1,int number2);
int main()
{
int number1;
... | The problem lies within the lcm() function:
int lcm(int number1,int number2)
{
return lcm(number2, number1 * number2)/gcd(number1,number2);
}
This function will be an infinite recursion because there's no base case. Eventually, you will run into, ironically, a stack overflow problem.
Looking at the nature of the f... |
70,331,741 | 70,333,341 | Find the biggest element in range that matches condition | Lets say I have range of integers [l, r) and a function check(int idx) which satisfies the following condition:
there is an index t (l <= t < r) such that for each i (l <= i <= t) check(i) == true and for each j (t < j < r) check(j) == false. Is there a standard way to find index t?
Standard binary_search() needs compa... | Assuming you are searching for a continuous range of integers (and not, for example, an indexed array) I would suggest a dichotomic search:
int find_t(int l, int r) {
// Preconditions
assert(check(l) == true);
//assert(check(r) == false); // this precondition is not mandatory
int max_idx_true = l; // h... |
70,332,218 | 70,332,351 | Template class char*, return type of function const char*? | I have this templated base class:
template <class V>
class ValueParam
{
public:
virtual V convert(const char* f) const = 0;
protected:
V val;
};
Note that I can store some value val that has type V, and that I have a convert function that automatically returns the right type when I call it on a ValueParam obj... | You can add const on the pointed type for the return type:
// for non-pointer type
template <typename T>
struct add_const_pointee { using type = T; };
// for pointer type
template <typename T>
struct add_const_pointee<T*> { using type = const T*; };
// helper type
template <typename T>
using add_const_pointee_t = typen... |
70,332,332 | 70,332,479 | How to use vector as a private member in class to store and pass data | Assuming that there is a Class called Solution:
class Solution{
private:
int COL;
int ROW;
vector<vector <int>> grid(ROW, vector<int>(COL));
public:
void setData();
};
Then put the definition of function setData()
void Solution::setData(){
for (int i = 0; i < ROW; i++){
for (int j = 0; j <... | Currently your definition of grid
vector<vector <int>> grid(ROW, vector<int>(COL));
looks rather like a function. State it's type and name, and initialise elsewhere to avoid this:
class Solution {
private:
const int COL;
const int ROW;
vector<vector <int>> grid;
public:
void setData();
Solution()... |
70,332,551 | 70,435,231 | How to share a view model in C++ UWP? | How can I share a view model between different pages in a C++ UWP application?
This answer is a C# solution which uses a static property:
public sealed partial class MainPage : Page
{
public AppViewModel ViewModel { get; set; } = new AppViewModel();
public static MainPage Current { get; set; }
public Main... | myproject::MainViewModel ultimately derives from winrt::Windows::Foundation::IUnknown. It is this structure that implements all the reference counting machinery, turning each derived type into a shared pointer to its interface.
The following implementation
myproject::MainViewModel MainViewModel() const { return this->m... |
70,332,819 | 70,332,832 | "No default constructor exists for class" if I want to construct a class with another one | I have a class named Ball and I want to create a class Particle with, in its constructor, a std::vector<Ball> particles, but I'm getting the error "No default constructor exists for class 'Ball'"
The Ball.h file :
#pragma once
#include <vector>
#include <raylib.h>
class Ball {
private:
Vector3 position;
... | The problem is that since you have a parameterized constructor for your class Ball, the compiler will not synthesize a default constructor by itself. So if you want to create/construct an object of class Ball using a default constructor, say by writing Ball b;, then you must first provide a default constrcutor for clas... |
70,332,983 | 70,357,585 | How to completely omit CBC loggings in C++? | I'm using the CBC solver to solve a program, and the method model.branchAndBound is called for multiple times(quite many). Because the log messages have to be written to file, so it is actually slowing down the program. I wonder is it possible to ommit the log messages entirely? This is in c++, and I now think that man... | Adding this to the code solves everything:
model.setLogLevel(0);
|
70,333,392 | 70,333,454 | declaring a variable in if statement | Please condiser the following snippet
//foo is just a random function which returns error code
if(int err = foo() == 0){
//err should contain the error code
...
}
The problem with that is err contains the result of foo() == 0, and what I want to evalute is int err = foo(); then if(err == 0) but inside the if s... | For C++ 17 and onwards you can use if statements with initializers:
if (int err = foo(); err == 0) {
...
}
|
70,333,411 | 70,333,523 | my code works but it does not give me what I want | my code is going to take ten numbers and separate the numbers to two groups : odd and positive numbers
#include <iostream>
using namespace std;
int odd(int a)
{
if (a % 2 != 0)
{
return a;
}
}
int pos(int p)
{
if (p >= 0)
{
return p;
}
}
int main()
{
int i;
... | Here it goes your code corrected. Just to let you know, your code wasn't checking all the possible conditions inside odd and pos functions. It just was returning something when the condition was false.
I modified these functions, making it work with a bool now instead of a number. In your main method, now, when this fu... |
70,333,521 | 70,335,279 | Handling all symbols combinations in makefile | Say I have designed a C++ library, and I want to extensively test all the features.
Some of these features are defined at build-time, through symbols that are defined or not.
// library.h
A foo( const B& b )
{
#ifdef OPTION_X
... do it that way
#else
... do it another way
#endif
}
I build a test program that I w... | Interesting problem. If you have GNU make you can try something like the following. The compilation and execution commands are just echoed; remove the two echo and the @ silencers when you will be satisfied with what you see. There are 3 options: A, B and C; add more if you wish or specify them on the command line with... |
70,334,243 | 70,334,616 | Template class definition | Does a class template -that takes integer parameter- define multiple classes for different integer inputs?
for ex:
I applied the following code
template<int val>
class MyClass
{
public:
static int var;
};
template<int val> int MyClass<val>::var = val;
int main(int argc, char* argv[])
{
MyClass<5> a;
MyCla... | Yes, these will be 3 distinct types
You can for instance use C++ Insights to get an idea of the code that the compiler generates from class templates.
#include <iostream>
template<int val>
class MyClass
{
public:
static int var;
};
/* First instantiated from: insights.cpp:14 */
#ifdef INSIGHTS_USE_TEMPLATE
templa... |
70,334,799 | 70,335,523 | Taking the address of a non-instantiated struct | I am reading "C++ Templates. The Complete Guide. Second Edition", by David Vandevoorde, Nicolai M. Josuttis, Douglas Gregor. And, there is something that I don't understand.
This is one code example in pg. 59:
// define binary tree structure and traverse helpers:
struct Node {
int value;
Node* left;
Node* r... | This is not an "a non-instantiated struct".
This is an address of a class member.
left is a member of the Node class. This takes its "address", and not the actual address of some instance of some Node class. This does not take the left pointer of some particular class instance, but of the left itself.
The address of a... |
70,335,313 | 70,335,498 | How to test a class with google test? | I'm just learning google test, I have a class and I want to test its member function, below is the demo code:
class B {
//......
};
class A {
public:
//.....
void add (string s, B* ptrb) { m.insert(s, ptrb); }
void remove(string s) {
auto it = m.find(s);
if (it != m.end())
m... | You have to just verify that state of A has changed as desired.
So just check if it contains added objects.
TEST_F(mygtest, testadd)
{
B b1;
B b2;
a.add("1", &b1);
a.add("2", &b2);
EXPECT_EQ(a["1"], &b1);
EXPECT_EQ(a["2"], &b2);
EXPECT_EQ(a["3"], nullptr);
}
https://godbolt.org/z/ezrjdY6hh... |
70,335,429 | 70,335,753 | How many translation units in one module? | Does a module with multiple source files (.cpp) have one or multiple translation units? My understanding is that every single source file (.cpp) will be its own translation unit unless it is included, and #pragma onced (which I guess is a malpractice), but I don't know how that is done in a modular program. If there's ... | A module consists of one or more translation units. A translation unit that starts with a module declaration is termed a module unit, and if there are multiple module units in a program that have the same module name (ignoring any module partition) then they belong to the same module.
|
70,335,947 | 70,336,048 | How a multiple times #included guarded header file will be inside different translation units? | I know that #inclusion is often described as a text copy-pasting preprocessor directive. Now if a header is #include guarded, or #pragma onced, then how'd we describe what is actually happening past the first translation unit to #include said header?
| There is no "first" translation unit. All translation units are conceptually translated in parallel (of course, in practice you might end up compiling them one at a time, but it doesn't matter).
Each translation unit begins with a blank slate. Technically that isn't quite true because you can add #defines at the comman... |
70,336,171 | 70,338,064 | ctypes: How to access array of structure returned by function? | I have a c++ API functions which I need to call from python using ctypes.
In my c++ libamo.h, I have prototypes for struct and function as below,
typedef struct contain_t
{
uint8_t id;
uint16_t ele1;
uint16_t ele2;
uint16_t ele3;
uint16_t ele4;
float ele5;
} mycontain;
mycontain* get_result(voi... | Use the matching types in the struct. c_uint is typically 32-bit so your Python structure has the wrong size.
To access the array, index the pointer (e.g. output_res[0].id) or use slicing.
Here's a reproducible example with a test DLL:
test.cpp
#include <stdint.h>
#ifdef _WIN32
# define API __declspec(dllexport)
#e... |
70,336,239 | 70,336,267 | Using vectors in C++ program is not printing anything | I have written a C++ program to find fibonacci numbers. It's running successfully but is not printing anything.
#include<bits/stdc++.h>
using namespace std;
int main(){
int n = 5;
vector<int> fib;
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++){
fib[i] = fib[i-1] + fib[i-2];
}
cout<<fib[n];
}
If I do t... | int fib[10];
This creates an array of 10 integers.
vector<int> fib;
This creates a vector of size 0, with 0 integers.
For these two snippets to match, you need to initialize the vector with 10 integers like the array. So:
vector<int> fib(10);
Some notes on vectors
One of the big differences between std::vector and ... |
70,336,370 | 70,336,563 | Initialized declarator inside of C++ catch statement | Do you think that the initialized declarator is a valid lexical structure inside of the caught-declaration part of the catch statement? For example, take a look at the following code:
void func( int = 1 )
{
try
{
}
catch( int a = 1 )
{
}
}
It compiles fine under latest MSVC 17.0.2 but fails to... | No. It's invalid.
The grammar for the catch clause specifies type-specifier-seq declarator. The declarator part of that does not include an initializer. Compare this with the grammar for a function parameter, which does allow an initializer:
attr(optional) decl-specifier-seq declarator = initializer
|
70,336,422 | 70,341,420 | Bluetooth Low Energy application in Visual Studio C++ for image sharing. Which tools should I use? | I'm trying to develop a C++ application on Windows 10 (using Visual Studio 2017) capable of looking for nearby mobile devices and sending data (images) via Bluetooth. I'm new to Bluetooth applications, but from what I understand, the best solution is to use BLE and make the computer a GATT server.
For this purpose, I'm... | The Windows API is what you should use if you write a C++ application for Windows. That will be the best supported option. If you happen to find some library that also does BLE it will probably just be a wrapper around the Windows API.
Unfortunately these APIs use the WinRT architecture which is not the easiest to set ... |
70,337,566 | 70,337,711 | How does std::unique_ptr handle raw pointers/references in a class? | Let's say I have a class A with the following definition:
class A {
A(std::string& s) : text_(s) {}
private:
std::string& text;
}
Note that A contains a reference to a string object. This can be because we don't want to copy or move the object.
Now, if I have the following code
std::string text = "......";
std::... | C++ is not a safe language. If you have a pointer or reference to an object that is destroyed, using that pointer or reference is a bug.
Assuming you actually construct an A that outlives text, it will still reference the destroyed object, and any use of that member is undefined behaviour.
|
70,338,242 | 70,347,271 | avoiding impossible cases in macro | consider the following macro:
#define checkExists(map, it, value) {\
it = map.find(value);\
if(it == map.end()){\
if(!strcmp(typeid(value).name(), "Ss")){ /* value is an std::string */\
manageError(ERR_CANT_FIND_RESSOURCES, "in %s __ failed to find %s in map %s", __FUNCTION__, value.c_str(),... | I solved the problem by converting value to std::string no matter the input type.
#define checkExists(map, it, value) {\
it = map.find(value);\
if(it == map.end()){\
std::stringstream tmpSs;\
if(!(strcmp(typeid(value).name(), "Pc") * strcmp(typeid(value).name(), "PKc") * strcmp(typeid(value).nam... |
70,338,351 | 70,338,689 | What is wrong with this constructor definition? | I want to write a class of "Clock", which basically holds hours, minutes and seconds (as integers).
I want that by default the constructor would initalize hours,minutes and seconds to 0 unless other input was given. So I declared the following:
Clock(int hour=0, int minute=0, int second=0);
Which basically should ... | You can solve this easily.
If you have default arguments, chances are these will pass the test (you define them, after all :-)). So why don't take advantage of this and just write a single constructor that handles both cases?
In both cases (i.e. with/without passing arguments to it), the checks will be performed and on... |
70,338,886 | 70,339,052 | How to use the user input for a file name? | I'm pretty new in c++. I've testing a small program which takes the user input and create a file which contains the data dependent on the user input. So every time I've to change the name of file before running the code. Are there methods to use the user input as file name?
std::cout << "Enter the block size: ";
int bl... | Perhaps this works?
std::cout << "Enter the block size: ";
int block_size = 0;
std::cin >> block_size;
std::cout << "Enter the file name: ";
std::ws(std::cin);
std::string filename;
std::getline(std::cin, filename);
std::ofstream f;
f.open(filename);
std::ws will eat the newline after the block size, otherwise std::... |
70,338,946 | 70,339,902 | GL_TEXTUREn+1 activated and bound instead of GL_TEXTUREn on Apple Silicon M1 (possible bug) | Let's first acknowledge that OpenGL is deprecated by Apple, that the last supported version is 4.1 and that that's a shame but hey, we've got to move forward somehow and Vulkan is the way :trollface: Now that that's out of our systems, let's have a look at this weird bug I found. And let me be clear that I am running t... | Instead of passing a texture handle to glUniform1i(glGetUniformLocation(ID, "textureSampler"), ...), you need to pass a texture slot index.
E.g. if you did glActiveTexture(GL_TEXTUREn) before binding the texture, pass n.
|
70,339,167 | 70,341,062 | pybind11 conflict with GetModuleFileName | I am using pybind11 to let python call an existing C++ module (library). The connection is through, however, in the C++ library, ::GetModuleFileName (Visual Studio) is called to to determine the physical path of the loaded module as it is run in C++. But when I call the library from python (Jupyter Notebook) through py... | "Module" in Windows parlance is a DLL or an executable file loaded to be a part of a process. Each module has a module handle; by convention, the special handle NULL signifies the executable file used to create the process.
GetModuleFileName requires module handle as the first argument. You pass 0, you get back the nam... |
70,339,753 | 70,354,210 | What is XlaBuilder for? | What's the XLA class XlaBuilder for? The docs describe its interface but don't provide a motivation.
The presentation in the docs, and indeed the comment above XlaBuilder in the source code
// A convenient interface for building up computations.
suggests it's no more than a utility. However, this doesn't appear to exp... | XlaBuilder is the C++ API for building up XLA computations -- conceptually this is like building up a function, full of various operations, that you could execute over and over again on different input data.
Some background, XLA serves as an abstraction layer for creating executable blobs that run on various target acc... |
70,339,767 | 70,339,932 | My code with regular expressions for file doesn't run properly | #include <iostream>
#include <fstream>
#include <string>
#include <regex>
using namespace std;
int main()
{
regex r1("(.*\\blecture\\b.*)");
regex r2("(.* practice.*)");
regex r3("(.* laboratory practice.*)");
smatch base_match;
int lecture = 0;
int prakt = 0;
int lab = 0;
string name ... | You need the number of times each regex matches. C++ has std::sregex_iterator for performing multiple regex matches over a string.
That means you can do the following:
for (auto it = std::sregex_iterator{str.cbegin(), str.cend(), r1}; it != std::sregex_iterator{}; it++) {
lecture++;
}
If you want to get really fancy... |
70,340,224 | 70,340,299 | I'm not sure what to do to have the expected output | This is My Code
for(int y=1;y<=20;y++)
{
for(int z=1;z<=y;z++)
{
cout<<z;
z++;
cout<<z;
}
cout<<endl;
}
return 0;
But the Output is this
12
12
1234
1234
123456
123456
12345678
12345678
12345678910
12345678910
1234567891... | For example you can change the inner for loop the following way
for(int y=1;y<=20;y++)
{
for( int z=1; z <= 2 * y; z++)
{
cout << z;
}
cout << endl;
}
If you want to output only 10 lines then change the condition in the outer loop
for(int y=1;y<=10;y++)
{
for( int z=1; z <= 2 * ... |
70,340,507 | 70,340,744 | How to pass a vector or a valarray as an argument to a C++ template function | I feel this is probably an elementary question, but I can't find a simple answer after quite a bit of searching, so I thought I'd ask.
I have a function that is meant to return the nth percentile value in a container, but for legacy reasons the array can be either a vector or valarray, and it can contain doubles or flo... | std::vector has 2 template parameters. The second one is the allocator, which has a default value so you normally don't use it.
However, prior to c++17 template template parameters would only match if the number of template arguments where the same. In c++17 this was relaxed a bit and it's since allowed to match a temp... |
70,340,668 | 70,344,142 | Which GL blend mode for blending the same color in source and destination, and getting the same color back? | I have an texture that is with a solid background (let's say navy blue, #000080) and white text on it. Even though the texture is a single file with both background and text, I'd like to cause just the text to fade out.
I've prepared a second texture, just solid navy blue without any text. I'd like to "fade" the text... | You shouldn't need anything more than just:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBlendEquation(GL_ADD);
glEnable(GL_BLEND);
Which corresponds to the following:
original_pixel = [0, 0, 0.5, 1]
incoming_pixel = [0, 0, 0.5, 0.5]
final_pixel = incoming_pixel * 0.5 + original_pixel * (1 - 0.5);
Which sho... |
70,340,719 | 70,340,785 | Why does the first element outside of a defined array default to zero? | I'm studying for the final exam for my introduction to C++ class. Our professor gave us this problem for practice:
Explain why the code produces the following output: 120 200 16 0
using namespace std;
int main()
{
int x[] = {120, 200, 16};
for (int i = 0; i < 4; i++)
cout << x[i] << " ";
}
The sample answer... |
I'm a bit confused as to why that last element outside of the array
always "defaults" to zero.
In this declaration
int x[] = {120, 200, 16};
the array x has exactly three elements. So accessing memory outside the bounds of the array invokes undefined behavior.
That is, this loop
for (int i = 0; i < 4; i++)
cout <<... |
70,340,826 | 70,341,204 | Is there a way to get the function type of a pointer to a member function? | If you have a pointer to a member function like so:
struct Foo { void func() {} };
void(Foo::*funcPtr)() = &Foo::func;
Is there a way to get the type of the function, with the Foo:: removed?
I.e.,
void(Foo::*)() -> void(*)()
int(Foo::*)(int, double, float) -> int(*)(int, double, float)
You get the idea.
The goal is... | To answer your question, it is possible with a simple template:
template <typename Return, typename Class, typename... Args>
Return(*GetSig(Return(Class::*)(Args...)))(Args...);
This defines a function called GetSig that takes as parameter a member function pointer and essentially extracts the Return type and the Args... |
70,340,966 | 70,341,376 | Constructor overloading with variadic arguments | First, my code:
#include <iostream>
#include <functional>
#include <string>
#include <thread>
#include <chrono>
using std::string;
using namespace std::chrono_literals;
class MyClass {
public:
MyClass() {}
// More specific constructor.
template< class Function, class... Args >
explicit MyClass( const... | I would make the constructors viable iff function is invocable with the arguments:
C++20 concepts
class MyClass {
public:
MyClass() {}
// More specific constructor.
template< class Function, class... Args >
requires std::invocable<Function, Args...>
explicit MyClass( const std::string & theName... |
70,341,186 | 70,341,432 | I am using modulo operator, but it still giving me a negative number | I am trying to solve a programming problem in c++ (version : (MinGW.org GCC Build-2) 9.2.0)
I am using modulo operator to give answer in int range but for 6 ,it is giving me -ve answerwhy is this happening??
my code :
#include <cmath>
#include <iostream>
using namespace std;
int balancedBTs(int h) {
if (h <= 1) r... | The code makes two implicit assumptions:
int is at least 32 bit (otherwise the 1,000,000,007 for mod will not fit)
long is bigger than int (to avoid overflows in the multiplication)
Neither of these assumptions are guarantee by the standard https://en.cppreference.com/w/cpp/language/types
I don't have access to the s... |
70,341,367 | 70,341,534 | Using a C++ std::vector as a queue in a thread | I would like to have items added to a queue in one thread via in an asynchronous web request handler:
void handleRequest(item) {
toProcess.push_back(item);
}
There is a background thread that constantly processes these queue items as follows:
while(true) {
for(auto item : toProcess) { doSomething(item); }
to... | I'm going to use std::atomic<T>::wait which is a C++20 feature, there is a way to do it with condition variables too however, and they exist since C++11.
Include <atomic> and <mutex>
You will need a member atomic_bool.
std::atomic_bool RequestPassed = false;
and a member mutex
std::mutex RequestHandleMutex;
Your handle... |
70,341,467 | 70,341,583 | How is 'if (x)' where 'x' is an instance of a class, not an implicit conversion? | According to cppreference.com an explicit conversion function cannot be used for implicit conversions. As an example they have this:
struct B
{
explicit B(int) { }
explicit B(int, int) { }
explicit operator bool() const { return true; }
};
int main()
{
...
if (b2) ; // OK: B::operator bool()
... | Contextual conversions
In the following contexts, the type bool is expected and the
implicit conversion is performed if the declaration bool t(e); is
well-formed (that is, an explicit conversion function such as explicit
T::operator bool() const; is considered). Such expression e is said to
be contextually converted t... |
70,341,661 | 70,341,944 | C++/Qt: How to create a busyloop which you can put on pause? | Is there a better answer to this question than creating a spinlock-like structure with a global boolean flag which is checked in the loop?
bool isRunning = true;
void busyLoop()
{
for (;;) {
if (!isRunning)
continue;
// ...
}
}
int main()
{
// ...
QPushButton *startBusyLoop... | You can use std::condition_variable:
std::mutex mtx;
std::condition_variable cv_start_stop;
std::thread thr([&](){
/**
* this thread will notify and unpause the main loop 3 seconds later
*/
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
cv_start_stop... |
70,341,803 | 70,342,206 | Is this ? ternary operation legal? | I'm no expert, but I do like to learn and understand. With that in mind I wrote the following in the Arduino IDE:
lockout[idx] ? bulb[idx].off() : bulb[idx].on();
to replace this:
if (lockout[idx]) bulb[idx].off(); else bulb[idx].on();
lockout[] is an array of bool, and bulb[] is an array of a class, with .off and .o... | Yes, this is legitimate C++. While that operator is commonly called the ternary operator, it is called the conditional operator in the C++ standard, and it is defined in the section named "expr.cond".
The C++ standard explicity says it is OK for both the second and third operands to have type void. So the standard wr... |
70,342,314 | 70,342,518 | cin input user for dynamic allocation of array of strings | i'm new at this, learn c++, try to dynamic allocate a array of strings and input every string by the user. so at first, the user input the number of strings, and then put every string using cin>>
int main() {
int numberOfTeams;
char** Teams;
cout << "Enter the number of teams " << endl;
cin >> number... | Something like this
const int MAX_STRING_SIZE = 1024;
int main() {
int numberOfTeams;
char** Teams;
std::cout << "Enter the number of teams " << std::endl;
std::cin >> numberOfTeams;
Teams = new char*[numberOfTeams];
for (int i = 0; i < numberOfTeams; i++) {
Teams[i] = new char[MAX_STRING_SIZE];
... |
70,342,456 | 70,342,572 | Speeds of 3D Vector Versus 3D Array of Varying Size | I'm designing a dynamic hurtbox for characters in a text-based game, which catches the locations of hits (or misses) of a weapon swung at them. The location (indices) and damage (magnitude) of hits are then translated into decreases in corresponding limb health variables for a character. My thoughts are that this hurtb... | You'd be better off simply allocating the 3D array in a single allocation, and use indexing to access the elements. Allocation for the std::vector storage can then be handled in the constructor for std::vector.
In general it's best to avoid:
multiple allocations
repeatedly calling push_back
class hurtBox {
private:
... |
70,342,590 | 70,342,960 | Equivalent of python list multiplying with a scale in c++ | How would you code list multiplying with a scale in c++?
In python I would do:
lst = [1,2,3]
lst*3 # we will get [1,2,3,1,2,3,1,2,3]
What is the c++ equivalent of that?
| If you really need the operation of multiplication, for example, you are developing some math library, you can consider the operator overloading. Otherwise, I suggest you throwing the python style away while working with C++, just use std::copy or vector::insert with a loop to insert repeated elements into a vector.
st... |
70,342,675 | 70,342,777 | What is the best way to determine an intersection between 2D shapes on a cartesian grid? | The function below is supposed to determine whether two objects of the movingBall struct are "touching" with each other
bool areBallstouching(movingBall one, movingBall two)
{
int xMin, xMax, yMin, yMax;
int TxMin, TxMax, TyMin, TyMax;
xMin = one.xPosition - one.radius;
xMax = one.xPosition + one.radiu... | Mathematically, the point where two circles touch will separate their center positions by a distance equal to the sum of the two radii. It follows:
if distance between centers is less than the sum of radii, circles intersect;
if distance between centers is greater than the sum of radii, circles do not intersect (or t... |
70,342,964 | 70,343,007 | c++ header file not found when compiling ios project in xcode | When I built an iOS project, I got an error "'tuple' file not found". Seems xcode is not trying to look for c++ header files.
The error message is:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS15.0.sdk/usr/include/simd/vector_make.h:5310:10: 'tuple' file not found
In vec... | I'd check and make sure your language version is at least C++11, since that's when tuple was introduced.
Failing that I'd verify the .mm file is properly tagged as C++ in the project file (select the file, then open the right hand side "File inspector" thing.)
|
70,343,285 | 70,343,437 | Check what files a program reads from a computer (C++) | I have a program that reads files (given to it by the user) from the computer and performs operations on these files. However, the program isn't working. I input a valid file with a valid path and the program says it is reading this valid file, however, it doesn't find the files. I have verified that the method I use t... | For Linux, the strace utility is the answer (as mentioned by Peter in a comment). You probably have it installed already, so just run strace your_program_name and you can see all the system calls the program is running, and their arguments and return codes. You should focus on the open calls.
|
70,343,367 | 70,345,525 | Splitting string with colons and spaces? | So I've made my code work for separating the string:
String c;
for (int j = 0 ; j < count; j++) {
c += ip(ex[j]);
}
return c;
}
void setup() {
Serial.begin(9600);
}
I have had no luck with this, so any help would be greatly appreciated!
| I would simply add a delimiter to your tokenizer. From a strtok() description the second parameter "is the C string containing the delimiters. These may vary from one call to another".
So add a 'space' delimiter to your tokenization: ex[i] = strtok(NULL, ": "); trim any whitespace from your tokens, and throw away any e... |
70,343,841 | 70,343,886 | Can function templates be instantiated based on the result of runtime if else conditions without creating class templates in C++? | If following is the definition of simple function template:
template<typename T>
T compare(T a, T b)
{
return a>b ? a : b;
}
Can it be called with different template parameter based on some user input during runtime, WITHOUT creating class templates, with different T values as follows for example:
char type;
cout<<... | No. If you want to determine the type at runtime then you need to do what are you doing (the if else)
There are more advanced techniques for more advance uses, like using polymorphism with a table of callables, but in essence they do the same thing, just in a fancier way.
|
70,343,892 | 70,344,041 | C++ sockets: accept() hangs when client calls connect(), but accept() responds to HTTP GET request | I'm trying to write a demo server/client program in C++. I first ran my server program on my Macbook, with ngrok on and forwarding a public address on the Internet to a local address on my machine. I'm seeing something that I don't understand when I try to run my client program to connect to the server:
If the client ... | Contrary to the typical port forwarding done in the local router, ngrok is not a port forwarder at the transport level (TCP) but it is a request forwarder at the HTTP level.
Thus if the client does a TCP connect to the external ngrok server nothing will be forwarded yet. Only after the client has send the HTTP request ... |
70,344,624 | 70,344,717 | source is compiled without proper #include | I have a very simple c++ source like this:
#include <iostream>
int main() {
srand(time(NULL));
}
I am using g++ to compile like this :
g++ ./test.cpp
but it successfully compiles despite the fact that time() function is defined in ctime and it is not included with #include
my professor at university runs the code... | First of all, on my platform, it didn't compile successfully when I removed #include <iostream>
I am using WSL2 ubuntu 20.04, compiler i used g++ and clang++.
Whichever compiler it is, it gives the error:
>>> g++ t.cpp
t.cpp: In function ‘int main()’:
t.cpp:2:16: error: ‘NULL’ was not declared in this scope
2 | ... |
70,345,733 | 70,362,457 | Installing wxPython on Windows: DistutilsPlatformError: Microsoft Visual C++ 14.2 or greater is required | I have installed:
Python 3.10.1
PyCharm Community 2021.3
Visual Studio Build Tools 2022, including:
C++ Build Tools Core Features
C++ 2022 Redistributable Update
C++ core desktop features
MSVC v143 - VS 2022 C++ x64/x86 build tools (Latest)
Windows 10 SDK (10.0.19041.0)
C++ CMake tools for Windows
Testing tools core ... | I have the same problem. Solved for me to use Python 3.9.9.
Its maybe about a distutils problem in Python 3.10.1 with this warning from msvc9compiler.py:
DeprecationWarning: The distutils package is deprecated and slated for
removal in Python 3.12
This leads to:
raise DistutilsPlatformError("Unable to find vcvarsall... |
70,346,700 | 70,346,792 | deque.at No Maching Function | I am trying to deque (a string element) from a deque data structure. But I am getting and error:
error: no matching function for call to ‘std::__cxx11::basic_string::basic_string(__gnu_cxx::__alloc_traitsstd::allocator<std::array<std::__cxx11::basic_string<char, 1> >, std::arraystd::__cxx11::basic_string<char, 1> >::v... | It is not quite clear why you are using array as elements. The value returned from at is not a string but an array.
deque<array<string, 1>> records;
string data("hello this is 1st record");
array<string, 1> buffer{data};
records.push_back(buffer);
string record = records.at(0)[0];
^^... |
70,347,206 | 70,347,603 | Class with no blocking methodes with multithreading | I am programming a class which should use multithreading features.
The goal is that I don't have any blocking methods from the outside although I use libraries in the class that have blocking functions.
I want to run them in their own threads.
Unfortunately I get a memory fault (core dumped) error.
What would be the be... | The lambda associated with your thread is capturing a reference to local stack variable. When startUp returns, the thread will continue on, but the address of retValue is now off limits, including to the thread. The thread will create undefined behavior by trying to assign something to that reference to retValue. Tha... |
70,347,311 | 70,348,831 | How is the string layout of cpp? | I wondered how char sequence(string) arranged in RAM, so make below testing with c++.
The compiler environment is 64bit system, cygwin on windows10.
#include <iostream>
using namespace std;
int main() {
char* c1 = "01";
cout << "string to print:" << endl;
cout << c1 << endl;
cout << "the address in s... |
I recognize that the address of char '0' and '1' just offset 1bit.
No. They are offset one byte. The size of char is one byte and array elements are adjacent in virtual memory. String is an array.
|
70,347,533 | 70,348,572 | "warning C4172: returning address of local variable or temporary" when returning reference to static member | I have this class with a function that returns a value. For complicated reasons, the value needs to be returned as a const reference.
(minimal working example contains an int array, real code has more complex objects, hence the reference)
class Foo
{
public:
static constexpr const int OUT_OF_BOUNDS_VALUE = -9999;
... | The problem is that in C++11, we have to add a corresponding definition for a static constexpr declaration of a class' data member. This is explained in more detail below:
C++11
class Foo
{
public:
static constexpr const int OUT_OF_BOUNDS_VALUE = -9999; //THIS IS A DECLARATION IN C++11 and C++14
//other members... |
70,347,787 | 70,357,225 | How to add a symbol to cmake, in debug mode only? | I want the following code to only be compiled in debug mode
main.cpp
#ifdef __DEBUG__
int a=1;
std::cout<<a;
#endif
adding the following to cmake
add_compile_options(
"-D__DEBUG__"
)
or
add_compile_options(
"$<$<CONFIG:DEBUG>:-D__DEBUG__>"
)
just doesn't seem to do anything.
How can I ach... | Option 1: NDEBUG
CMake already defines NDEBUG during release builds, just use that:
#ifndef NDEBUG
int a=1;
std::cout<<a;
#endif
Option 2: target_compile_definitions
The configuration is spelled Debug, not DEBUG. Since you should never, ever use directory-level commands (like add_compile_option... |
70,348,102 | 70,348,122 | For Loop is not iterating for a third time? (C++) | Question: Why is my for loop not iterating for the third time?
What I noticed: In the for loop statement below, removing the if-else statement allowed me to print i from 0-2 and the "1" three times.
for (size_t i {0}; i < user_input.length(); ++i) {
cout << i << endl;
cout << user_input.length(... | z >= 0 is always true since z is an unsigned type.
Your program therefore loops. Although there are other solutions, using a long long rather than a std::size_t as the loop index is probably the simplest.
b < (user_input.length() - 1) is also problematic if user_input is empty. Use
b + 1 < user_input.length()
instead... |
70,348,873 | 70,351,288 | Problem with python and arduino in pyserial | I wrote this code to print the sensor values in Python, but the problem is that the soil_sensor prints twice.
This is the code in the Arduino :
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN 8
#define DHTTYPE DHT11
int msensor = A0;
int msvalue = 0;
int min = 0;
int max = 1024;
DHT dht(DHTPIN, DHTTYPE);
void setu... | The first thing you should notice is that sending numbers throug the serial interface will result in different string lenghts depending on the number of digits.
So reading a fixed number of 6 bytes is not a good idea. (actually this is almost never a good idea)
You terminate each sensor reading with a linebreak. So why... |
70,348,888 | 70,349,018 | Tuple of Jsoncpp functions | I am currently working with some config files, and I wanted to map options with configuration functions. So far, I have this working code:
std::unordered_map<std::string, void (Model::*)(int)> m_configMap =
{
{ "threshold", &Model::setThreshold }
};
Now, as you may very well notice, this approach would not work if th... | Looks like you're not refering to an instance of Model, or the member function of Model is not static. I don't know about the JSON part but this should get you started. If you have questions let me know.
#include <iostream>
#include <functional>
#include <string_view>
#include <unordered_map>
struct Model
{
public:
... |
70,349,958 | 70,350,089 | Use of ternary operator instead of if-else in C++ | I just came across the following (anonymized) C++ code:
auto my_flag = x > threshold;
my_flag ? do_this() : do_that();
is this a standard C++ idiom instead of using if-else:
if (x > threshold)
{
do_this();
}
else
{
do_that();
}
Even though it's only two lines, I had to go back and re-read it to be sure I kne... | No. In general the conditional operator is not a replacement for an if-else.
The most striking difference is that the last two operands of the conditional operator need to have a common type. Your code does not work eg with:
std::string do_this() {return {};}
void do_that() {}
There would be an error because there is ... |
70,350,208 | 70,352,742 | C++ Returning a member from one of 2 structs using macros or templates | I am working on a plugin that runs inside a host program against a proprietary PDK. At times there will be breaking changes in the PDK, so my code uses wrapper classes that allow it to work with more than one version of the host while encapsulating the changes from version to version.
Here is a very simplified example ... | With std::variant, you might do something like:
class DataWrapper // my class
{
private:
std::variant<DataV1, DataV2> data;
public:
DataWrapper(); // initializes _forV1
int GetA() const { return std::visit([](auto& arg){ return arg.a; }, data); }
void SetA(int a) const { std::visit([&a](auto& arg){ arg.a ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.