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 |
|---|---|---|---|---|
67,019,763 | 67,019,950 | Initialize an std::vector from members of another vector using modern C++ | Is there a nicer way in modern C++ to initialize a vector from members of another vector? E.g. using lambdas?
#include <array>
#include <cstdint>
#include <vector>
struct IntRectangle {
uint64_t id;
std::array<uint64_t, 2> width_height;
};
std::vector<std::array<uint64_t, 2>> rect2array(const std::vector<IntRecta... | I think you need transform
std::vector<std::array<uint64_t, 2>> rect2array(const std::vector<IntRectangle>& rects) {
std::vector<std::array<uint64_t, 2>> rect_array;
rect_array.reserve(rects.size());
std::transform(std::begin(rects), std::end(rects), std::back_inserter(rect_array), [](const auto& ir) {
retu... |
67,020,013 | 67,020,400 | Static member declaration in Parametrized polymorphism | I have gender class with Male and Female as my parametric types of class
I am using following hierarchy:
#ifndef __GENDER_H
#define __GENDER_H
#include <string>
using namespace std;
// Forward declaration of templatized class
template<typename T>
class GenderTypes; // Generic Gender type to generate specific genders... | With this small change in your .cpp it compiles (and works) fine on my machine :
template<>
const string Gender::Male::sName = "Male";
template<>
const string Gender::Female::sName = "Female";
And indeed in your header you should use
#ifndef GENDER_H
#define GENDER_H
[...]
#endif
OR
#pragma once
[...]
|
67,020,168 | 67,020,294 | Using std::invoke when a function is overloaded | I am trying to use std::invoke() with an overloaded function:
#include <iostream>
#include <functional>
struct S {
void foo(int) { }
void foo(int, int) { }
};
int main()
{
S s;
std::invoke(&S::foo, s, 1);
}
but I get an error: 'std::invoke': no matching overloaded function found. It works fine, when ... | There are two example solutions:
std::invoke(static_cast<void(S::*)(int)>(&S::foo), s, 1);
std::invoke([&s]() { s.foo(1); });
|
67,020,487 | 67,020,944 | Problem with malloc and memcpy in array class | I've started writing some code for a List class and I'm lost. I need it for my Arduino project – I can't use STL.
Here's the code.
#include <iostream>
template <typename T>
class List
{
public:
List<typename T>()
{
m_Count = 0;
m_Data = nullptr;
}
~List()
{
free(m_D... | The essential problem is in the line *(m_Data + sizeof(T) * (m_Count - 1)) = element;. Here, you are attempting to copy the given element into the old (i.e. pre-existing) m_Data array; this will be nullptr the first time the Push function is called (and one element too small every other time)†.
So, you need to first re... |
67,020,560 | 67,022,615 | C++ variadic template arguments: object is not forwarded as a reference | Let's say I have the following code:
#include <iostream>
struct NotCopyable
{
std::string value;
NotCopyable(const std::string& str) :
value(str)
{
}
// This struct is not allowed to be copied.
NotCopyable(const NotCopyable&) = delete;
NotCopyable& operator =(const NotCopyable... | template<typename T, typename... ARGS>
void ConstructAndPrint(ARGS... args);
take argument by value, so does copy.
You want forwarding reference instead:
// This function constructs an object of type T,
// given some arguments, and prints the object.
template<typename T, typename... ARGS>
void ConstructAndPrint(ARGS&&... |
67,020,636 | 67,021,698 | operator<< overload resolution (C++) | The code below gives an error in the a::b::print function: Invalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'Foo').
The error goes away if I comment out the operator<< overload in namespace b. But I don't understand why that makes a difference because it has a different signature to... | As namespace b is nested inside namespace a, names declared in b will hide names declared in a. When name lookup occurs in a::b::print, it searches b, and if it doesn't find what it's looking for continues searching in a. So it does find operator<< in b and stops looking, and does not even consider the proper one in ... |
67,020,672 | 67,021,033 | How to remove object from a vector if it was deleted | I'm making a console game, where the player can shoot. After the player presses the space bar, a new object is created, placed on the map, and the map contains a pointer to that object. These objects are stored in a vector. I read an article about vectors, where it says:
Vectors are same as dynamic arrays with the abi... | From your sample code, I assume your vector is defined somewhat like this:
std::vector<YourType*> entities;
Therefore, your vector does not contain YourType objects, but pointer to YourType. That is, the elements the vector manages are the pointers, not the pointed objects.
Thus when you do this delete entities[x + y ... |
67,020,715 | 67,020,850 | Is a function terminates as soon as it returns a value, ignoring its next lines? | What value the return_a_number function returns in following case:
#include <iostream>
#include <conio.h>
using namespace std;
int return_a_number(int n)
{
if(n < 0) return -1;
return 1;
}
int main()
{
cout << "Enter any number: ";
cin >> num;
cout << return_a_number(num);
getch();
return 0;
}
As return... | If a function returns, it terminates there, following lines of code in that function will not be executed.
#include <iostream>
#include <string>
std::string foo(int x)
{
if(x < 0) return "If x < 0, this will be returned";
if(x == 0) return "If x == 0, this will be returned";
return "If x > 0, this wil... |
67,020,877 | 67,056,203 | How to enable all suggestions in intellisense all the time? | I am quite new to Microsoft Visual Studio. I am using VS Community 2019. I want to enable all suggestions in intellisense all the time, how can I do that?
For example, I have a vector variable v2qPenLine which is a QVector<QVector<QPen>>. The vector variable is named in such a way so that I have easy access to it throu... | I think it is a problem of your VS IDE Intellisense. And you can see that the Intellisense of your environment does have any info about variables, functions, classes ....on the first time. It should show all types on the first time. In your side, it only has the type of methods, quite strange.
Try the following sugges... |
67,021,071 | 67,021,130 | How to center an opengl window with glfw? | I wanna draw an opengl window in center of the screen,however I searched everywhere but didn't find any answer to it. Below is a common snippet code of creating a window But it always show up in most left-top position.How can I control it.
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
... | Please use this function "glfwSetWindowPos".
Here is an example.
|
67,021,185 | 67,021,317 | How to Find Dominant colors in an image in c++ and percentage of each cluster? | I am able to get the dominant color from image, but I am not able to get the percentage of color.
This is my code to get the dominant color from a image:
cv::Matsource_img=cv::imread("detect.bmp",1); // Read image from path
// Serialize, float
cv::Mat data = source_img.reshape(1, source_img.total());
data.convertTo(d... | You want to count how often each individual label occurs in labels, i.e. label 0 occurs 29.34% in labels. That's just a std::count divided by labels.size()
|
67,021,475 | 67,024,619 | SFINAE does not properly disable ambiguous overloads | I'm trying to build a more flexible version of std::equal_to, which can be called on objects of two different types T1and T2 and only requires that T1::operator==(T2) or T2::operator==(T1) is defined. I'm using C++17. First, I have some struct that tests if SomeType::operator==(OtherType) is defined:
#include <vector>
... | Your SFINAE detector for operator== is bugged. Replace this:
decltype(std::declval<FromT>() == std::declval<ToT>())
with this:
decltype(std::declval<FromT>() == std::declval<ToT>(), void())
|
67,021,509 | 67,021,764 | MFC SetRegistryKey opposite function? What am I missing? | In my app the default Registry key is created called:
SetRegistryKey(_T("Trains"));
It places that "root" key value like so:
Computer\HKEY_CURRENT_USER\SOFTWARE\Trains
My app saves all the window info and other data in subkeys under Trains. I have a "reset" menu item that when the user activates, I would like to dele... | You can use the SHDeleteKey() function. You can use HKEY_CURRENT_USER for the first argument and specify the key path (from that) in the second:
#include <shlwapi.h>
LSTATUS status = SHDeleteKey(HKEY_CURRENT_USER, _T("SOFTWARE\\Trains"));
You will need to include "Shwlapi.lib" in your link.
(Note: Calling the DelRegT... |
67,021,588 | 67,023,674 | Make a shape move towards mouse in SFML | Here is my code:
void Ant::Update(float dt, sf::RenderWindow& window) {
// calculate difference between mouse pos and ant pos
float x = sf::Mouse::getPosition(window).x;
float y = sf::Mouse::getPosition(window).y;
if (this->pos.x + radius > x) {
this->pos.x -= speed * dt;
}
if (this->pos.y + radius > y) {
this... | I found the solution. I used the distance formula sqrt((x2-x1)^2 + (y2-y1)^2):
void Ant::Update(float dt, sf::RenderWindow& window) {
// calculate difference between mouse pos and ant pos
float x = sf::Mouse::getPosition(window).x;
float y = sf::Mouse::getPosition(window).y;
float xDist = x - (this->pos.x + radius);
f... |
67,021,626 | 67,022,065 | How do you define user-defined string literal operator templates in C++17? | According to my (draft) version of C++17 (16.5.8 [over.literal]) as well as as cppreference.com, C++17 should have support for templated operators for user-defined string literals.
Specifically:
template <char...>
double operator "" _pi() {
return 0.;
}
int main() {
"test"_pi;
}
However, both gcc and clang yell... | The template char... user defined literal is not for strings. It is called a numeric literal operator template and it allows you to have a literal operator that will take the number you are using and expand it into a pack for the template operator. For example, you would use your operator like
1234_pi
and that would... |
67,021,756 | 67,021,911 | How to sort a vector containing objects of class in C++? | the class(staff) contains objects int ID, string Name, string Class
The vector contains
vector <staff> s = { {234, "Mark", "biology"},
{3455, "Mitch", "English"},
{1234, "Hen", "Maths"}}
How can I sort this from ID? and print sorted?
Thank you
| I'm sure that this has been answered before, but for your specific case;
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
struct staff {
int ID;
std::string Name;
std::string Class;
};
int main() {
std::vector <staff> s = {
{ 234, "Mark", "biology" },
{ 345... |
67,022,118 | 67,022,791 | Switching a's and b's in a String C++ [Code Wars Problem] | #include <string>
#include <algorithm>
using namespace std;
std::string switcheroo(const std::string &s) {
string myString = s;
int i = 0;
int j = s.length();
if(s[i] != 'a' || s[i] != 'b') i++;
if(s[j] != 'a' || s[j] != 'b') j--;
else
{
swap(myString[i],myString[j]);
}
return myString;
}
... | Here's a version of the function that passes all tests.
Because the parameter s is passed in as a reference to const, we can't make changes to it directly. So, we declare a new string, tmp, and build it letter by letter. The key is looping through s so that we can examine each letter. If it's 'a', be add a 'b' to tmp. ... |
67,022,438 | 67,060,469 | SDL Lag / Super slow (SDL 2.0.14) | i have a game loop which measures the ms it takes to finish.
before entering the loop i call a "Init" function which looks like this:
void screen::Init()
{
if(SDL_Init(SDL_INIT_EVERYTHING) == 0)
{
m_window = SDL_CreateWindow("TITLE", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH*SIZE, HEIGHT*SIZ... | okay, found out why it was lagging:
i was calling handleevent everytime it executed a loop (which is a couple thousand times per second) instead of doing it inside this if statement:
if(currline == 151 && Time == 0)
{
end = SDL_GetTicks();
printf("s: %8d e: %8d r: %d\n", start, end, end-start);
... |
67,022,478 | 67,022,529 | C++ Error : undefined reference to `Vector2<int>::add(int)' | I'm new to C++
I have been attempting to write a linked list below you can see I have linkedList header and implement and a main file I'm using MinGW-W64 as compiler
in my linkedList.h I have template struct Node and a template class Vector2
// linkedList.h
template <class T>
struct Node
{
T value;
Node *next;
... | Template functions cannot be diveded as multiple files. You must inplement it in your header file.
|
67,022,554 | 67,051,853 | Calling a function in another process with parameters using CreateRemoteThread | I want to call a function in another process in the context of the same process with parameters. For this, the CreateRemoteThread() function seems to do the job. A code example can be found e.g. here.
Note: I don't want to implement the other provided solution since this one seems nice and to the point.
When it comes t... | The message box produces incorrect values. As mentioned in the comments, you cannot modify the parameter list of the function, but use code similar to the following:
DLL_EXPORT void show_message_dialog(LPVOID *myparam)
{
my_parameters *p = (my_parameters *)myparam
const auto text = std::to_string(p->i);
con... |
67,022,572 | 67,058,410 | Ambiguous call with const overloading and templates | In my image class I provide direct memory access to a specific row using the following const overloaded templated functions
template <typename T>
inline T* Image::getRow(unsigned int y)
{
...
}
template <typename T>
inline const T* Image::getRow(unsigned int y) const
{
...
}
However, if I specify another temp... | As it turned out, it could very well be a bug in MSVC, as other compilers don't have problems with this.
@Yksisarvinen mentioned in a comment that the error can be fixed by using this->getRow<T>(y) instead of getRow<T>(y). This solves it for MSVC.
|
67,022,668 | 67,026,546 | Why the speed of the video depends on the number of FPS in OpenCV | I have a code which capture screen and make a video from the screenshots using OpenCV. So if I change fps to 60 in my videoWriter object(video lasts 10 seconds or more) will play for 1 second. As I understood, higher FPS makes video faster and lower FPS makes it's slower. Could you explain for me why it works that way?... | Imagine you record a video for 4 seconds with 2 FPS. You'll record 8 frames in total:
Now suppose you double the frame rate to 4 FPS. This tells your video player to show 4 frames every second, so those 8 frames are now shown to the viewer in 2 seconds - a speed up of the video.
|
67,023,539 | 67,023,758 | Do deduction guides require noexcept specifiers? | For some reasons, I've always thought that deduction guides must have the same noexcept-ness of the constructor to which they refer. For example:
template<typename T>
struct clazz {
clazz(const T &) noexcept {}
};
clazz(const char &) noexcept -> clazz<int>;
That is, if the constructor is noexcept and I want it to... | The grammar for the deduction guide is defined in [temp.deduct.guide]/1 as
explicit-specifier(opt) template-name ( parameter-declaration-clause ) -> simple-template-id ;
and as you can see, it does not include a exception specifier.
This does make sense. The deduction guide doesn't actually construct anything. It is... |
67,023,678 | 67,024,371 | How to automaticaly dowload library from github inside lib folder cmake | I want to create my first big project in c++.
And I need to use some library. So I have made this structure
├── CMakeLists.txt
├── README.md
├── src
│ ├── CMakeLists.txt
│ ├── HelloWorld.cpp
│ ├── HelloWorld.h
│ └── main.cpp
├── tst
| ├── CMakeLists.txt
| ├── HelloWorld-test.cpp
| └── main.cpp
└── lib
an... | The issue here is that the repository is cloned to the binary directory, but add_subdirectory looks for the directory relative to the source directory.
You need to use add_subdirectory with an absolute path here and pass a build directory. Furthermore add quotes to avoid issues with spaces in the file path.
set(REPO_PA... |
67,024,133 | 67,024,190 | Writing 2 names (with spaces) in C++ (cin command) | I am beginner to the C++ and was trying to build first codes. Right now I'm trying to learn cin command but there is a problem. When I use this code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
string surname;
cout<<"Please enter your name: ";
cin>>name;
cou... | Use the getline function:
#include <iostream>
#include <string>
using namespace std;
int main() {
string name, surname;
cout << "Please enter your name: ";
getline(cin, name);
cout << "Please enter your surname: ";
getline(cin, surname);
cout << "Your name: " << name << endl;
cout << "Yo... |
67,025,026 | 67,026,881 | Best practice to run a prebuild step with CMake | Suppose you have a repository with a folder (named dataset) with several .csv files and a python script (named csvcut.py) that takes all the .csv in dataset and generates corresponding .h files.
Those .h files are included in some .cpp files to build an executable (add_executable(testlib...) used for testing.
Suppose y... | This requires multiple steps, but can all be handled with standard CMake. First, we'll use add_custom_command to actually generate the files. I'm also adding a custom target, but only since I couldn't figure out how to make an INTERFACE library work without it.
add_custom_command(
OUTPUT
"${CMAKE_CURRENT_... |
67,025,099 | 67,026,555 | Visual Studio incorrectly uses information from .rc-file | I have added 3 static texts to main waindow using the Visual Studio 2012 resource editor:
Each static is at the same distance from each other. It is equal to 8
Here is the code from .rc-file:
LTEXT "Example",IDC_STATIC_1,25,30,35,8
LTEXT "Example",IDC_STATIC_2,25,38,35,8
LTEXT "Example",I... | This is expected. You need to look at the documentation for MapDialogRect() and GetDialogBaseUnits().
Dialog units are not pixels. They are their own thing.
When you create a dialog, it scales the dialog using the font for the dialog. If not specified, or it's specified to use the system font, then the dialog will be s... |
67,025,168 | 67,025,384 | How to detect what mouse key is pressed in C++ SDL? | How do I determine which exact mouse button (right, left, middle, etc.) is pressed? I'm using SDL. Here is the code that I have, which says if any mouse button is clicked or not:
case SDL_MOUSEBUTTONDOWN:
{
Mouse_Pressed = event.button.clicks;
} break;
... | You can access that through the event button field.
case SDL_MOUSEBUTTONUP:
switch ( ev.button.button ) {
case SDL_BUTTON_LEFT:
break;
case SDL_BUTTON_RIGHT:
break;
case SDL_BUTTON_MIDDLE:
break;
... |
67,025,237 | 67,027,042 | Is there a purpose for using a static std::set to manage resources of all instances of a class? | I inherited some code that I'm in the process of re-factoring, and I came across something where I'm uncertain of the intention. Many (more or less all) of the classes have defaulted to the below pattern, where it appears as though memory management is intended to be handled with a static std::set.
class A
{
public:
... | I think this is an attempt at implementing a "poor man's garbage collection". Here is how this could work in a batch processing situation:
You get a new batch of work, and start the processing
You allocate the memory as you go, and ignore the need to deallocate it
Once the batch is over, you call DestructAll_XYZ to cl... |
67,025,308 | 67,025,919 | Deduction guide for brace initializer list | There is a implementation quite similar to std::initializer_list used in an environment where standart C++ library is not available:
template<typename T>
class initializer_list {
public:
using value_type = T;
using reference = const T &;
using const_reference = const T &;
using size_type = size_t;
u... |
in an environment where standart C++ library is not available
There is no such thing. While freestanding C++ implementations are free to only implement parts of the standard library, there are some components which all valid C++ implementations must provide. std::initializer_list is among these components.
As such, i... |
67,026,058 | 67,026,499 | How do I insert into boost::unordered_set<boost::unordered_set<int> >? | The following code fails to compile, but if I remove the commented line, it compiles and runs correctly. I was only intending to use boost because C++ doesn't provide a hash function for std::unordered_set<int> by default.
#include <iostream>
#include <boost/unordered_set.hpp>
int main() {
boost::unordered_set<boo... | An unordered_set (or _map) uses hashing, and requires a hash operator to be defined for its elements. There is no hash operator defined for boost::unordered_set<int>, therefore it cannot put such a type of element into your set.
You may write your own hash function for this. For example, this is a typical generic has... |
67,026,244 | 67,026,280 | GCC optimalizations ignore for loop condition | so I wrote this code:
#include <iostream>
constexpr
int fibonacci (int n) {
int a = 0;
int b = 1;
for(auto i = 0; i < n; i++) {
b += a;
a = b - a;
}
return b;
}
template<int N, int (T)(int)>
struct array {
using type = decltype(T(0));
constexpr array() : arr() {
f... | You are invoking undefined behavior by using out-of-range x[i].
Allocate one more to avoid out-of-range access.
In other words,
constexpr auto x = array<10, fibonacci>();
should be
constexpr auto x = array<11, fibonacci>();
Defining constant to avoid typo is better:
int main() {
constexpr int num = 11;
... |
67,026,688 | 67,098,487 | Why are C++ debug symbols mismatched when generated in the same Visual Studio solution? | Something is wrong with my Visual Studio 2019 project configuration and I have run out of ideas to check. I have 3 native C++ shared libraries (A, B, C) that all sequentially stack on each other. B depends on A. C depends B. I then link all 3 to an executable. So the final stack looks like A->B->C->Executable. All ... | The CMake file for library C (called foo_client here) has this snippet.
add_library(foo::foo_client ALIAS foo_client)
set_target_properties(foo_client PROPERTIES EXPORT_NAME client)
The executable's target name in CMake is foo_client_exec. For a reason unknown to me this triggers a corrupt foo_client.pdb file. By us... |
67,027,124 | 67,050,425 | GDB on Visual Studio Code trying to read headers from a non-existent directory | I'm trying to debug a program written in c++ using gdb from vscode.
When the debugger calls the function ifstream() from the header fstream, it's unable to find the header file because gdb is looking for it on the directory /build/gcc/src/gcc-build/x86_64-pc-linux-gnu/libstdc++-v3/include/ , which doesn't exist and res... | Finally, I have solved this problem.
When gdb is executed, it looks for a configuration file called .gdbinit on the user's home directory (Unix systems). To give gdb the right header's directory it's as easy as put the command source {your header's directory} on the file previously mentioned.
If Visual Studio doesn't r... |
67,027,299 | 67,075,893 | Apply function attribute to destructor | Is it possible to apply attributes to destructors? Example:
#if defined (__GNUC__) && !defined(__clang__)
# define TEST_PRE_ATTR [[deprecated]] __attribute__((deprecated))
# define TEST_POST_ATTR __attribute__((error("test")))
#elif defined(_MSC_VER) && !defined(__clang__)
# define TEST_PRE_ATTR [[deprecated]] __de... | GCC will emit the warning with a prepositional attribute, if you replace defaulting the destructor by an empty body. Postpositional attribute will not trigger warnings.
struct Foo {
[[deprecated,gnu::noinline,gnu::error("test")]]
~Foo() { __asm__(""); }
};
int main() {
Foo* f = new Foo();
delete f;
... |
67,027,417 | 67,046,107 | Picking an n-digit combination lock with C++ | I need to write a C++ code to somehow iterate over each combination of a "combination lock" with different possible maximum number of states given for each digit. It is important that there is a specific call to a function for each try. Also, the number of digits may vary runtime.
Can you please help?
This is how I pic... | Mooing Duck commented a link (http://www.ideone.com/nI0Z7h) which helped a lot. I just modified it a little, to make it capable of handling different maximal states on each "digit", also to always start from zero (assuming, that the function will always be used only for numeric input). Thanks for your help!
This is the... |
67,027,913 | 67,029,787 | a white box problem in C++ SFML due to Sprite | Hello i was trying to draw a simple square for my game but it is drawing a white square instead of my image. Here is my codes...
paddle.hpp
class Paddle
{
public:
Paddle(){}
Paddle(sf::RectangleShape myPaddle);
void Draw(sf::RenderWindow& window);
void setImage();
private:
sf::Texture m_texBackgr... | I guess i fixed the problem at least. The problem is whatever i do i couldnt prevent some instances from losing because ending their related scopes. It took time for seeing because i didnt do it base class..But i am defining a paddle in my Game.cpp. So problem is same. They are calling this a white square problem..am l... |
67,027,923 | 67,029,761 | How do I initialize values of a 2d array of structs? | Im writing a ppm file with a 2d array of structs which act as the rgb values. The file writes, but when I try to pass the struct which contains the color value I want through my drawRect and drawCircle functions, the image does not draw with the dimensions I intended. The pixel values aren't written correctly into the ... | Looks like this line is wrong:
imgFile << static_cast<int>(image[row][col].red << image[row][col].green << image[row][col].blue) << ' ';
Instead of casting each color to int, yous SHIFT the value of red by the number of bits specified by green, then by blue.
You want this instead:
imgFile << static_cast<int>(image[row... |
67,027,971 | 67,028,290 | Templated references to std::array not invoking SFINAE* in MSVC . Bug? | I ran across a problem upgrading templated array references to std::array where I had used this:
template<class T, int N>
void f(T(&a)[N]){/* do stuff */;}
This has worked in all compilers I have used so I just did this when changing to std::array
template<class T, int N>
void f(std::array<T,N>& a){/* do stuff */;}
A... | std::array size_type is specified as std::size_t.
GCC and Clang are right, template deduction should fail in this case, according to [temp.deduct.type]/18:
If P has a form that contains <i>, and if the type of i differs from the type of the corresponding template parameter of the template named by the enclosing simple... |
67,028,182 | 67,112,848 | Can't modify global integer variable with user input from a GtkSpinButton widget | I wrote a simple program using GTK and glade to allow the user to enter a number in a GtkSpinButton. Once the user hits the enter key (activate signal) the global variable should be changed to whatever the user entered in. Unfortunately that doesn't work and when I print out the global variable in the main function it ... | Apparently the maximum value of the adjustment variable in glade was set to zero and that's why the global variable was being set to zero. Once I entered a different value for the maximum value the problem went away.
|
67,028,425 | 67,028,741 | Stroke is not drawn correctly (OpenGL) | I am trying to make a stroke for chests in a minecraft game and I almost succeeded, but for some reason it is not drawn correctly.
ScreenShot
The screenshot shows how part of the line has disappeared. This happens when the line is on the chest. Maybe it's a texture mapping or something else. In this case, the stroke is... | From your screenshots it seems that the order of rendering is the following:
terrain
outline
chest
Now since you have disabled GL_DEPTH_TEST in step 2, the fragments (pixels) that turned white (those on which the outline is drawn), won't get their depth information updated. That's because disabling GL_DEPTH_TEST not ... |
67,028,766 | 67,028,849 | C++: how to pass 'this' object as pointer reference | The question is not very clear, because I know that 'this' is const* and I can't modify pointer. I have class Queue and struct Element inside. I have constructor for Element which asign value and pointer to next element. I want to make function Push in Queue class which just create Element object (and pass value to Pus... | Just pass a simple pointer to the Element() constructor:
Queue::Element::Element(Queue* queue, int x)
The only thing you need to assure, is that Element can access Queue::front and Queue::back. For instance, if they are private members of Queue, then you can make Element a friend of Queue, something like:
class Queue ... |
67,029,147 | 67,033,287 | Why is the widget in this Listbox too small? GTK | I'm building a small podcast application for Linux using GTK-3.0 I want to use a listbox To hold Search results however when I add a widget to the listbox its far too small enter image description here
I've put all of the ui stuff into a header file.
#include<gtk/gtk.h>
#include <iostream>
extern "C"{
void createSearch... | It's a bit hard to know what exactly is going wrong in your code without having a small example code that reproduces the issue.
That being said, one thing you should keep in mind, is that in GTK3, widgets are not visible by default (this got changed in GTK4 however). So what you probably want to do in your createSearch... |
67,029,306 | 67,029,384 | About array in stringstream in C++ | I want to design a program that inputs a string with space and output split string and the number of letters, but I don't know what the "word[]" means in "while (!ss.eof()){}". For example, I input "Programming is fun", the result is
Programming
is
fun
Length:18
While I change "word[i]" to word[0] the result is
fun
... | This loop:
while (!ss.eof())
{
ss >> word[0];
i++;
}
sets the first item in your array to 3 different values, at each iteration the value gets replaced with a new one, so you are left with the last word in the first position of your array, with the other entries being unset (empty).
When you change word[0] wit... |
67,029,666 | 67,029,911 | readFile function not working on second iteration with different argument - c++ | I've written a readFile function for a project I'm working on. I call it once, load in a file and read in it's contents - works fine
However, when I try to load it a second time, attempting to change the file name - it loads it in, saves it to a static string 'path' that I access in a different function - but then the ... | In general, do not use global variables. The path variable should be passed as a parameter, not kept as a global variable altered between function calls, as this leads to many side effects and is the source of countless bugs. See the following refactoring:
void menu() { // put in while loop - while True
while(true)
{
... |
67,031,776 | 67,031,957 | Missing DLL in my project during compilation | I'm new to conan/premake, I've made a conanlist and a premake which is suppose to set my project.
But when I execute my project in release mode, I receive QT6Widgets.dll is missing and QT6Core.dll is missing. I don't know how to fix that. Here is my conanfile
[requires]
glfw/3.3@bincrafters/stable
qt/6.0.1@bincrafters/... | Dynamic Link Libraries or DLL for short, is not linked to your application at compile time. The library type that gets liked at compile time are static libraries (.lib files).
By default when you try executing an application, the system will check if the required DLL is in the working directory (in the directory which ... |
67,031,807 | 67,031,844 | Why fundamental type int x gets initialized if a vector member is present in a class? | If I replace the vector member by another fundamental type variable (such as int y for example), x doesnt get initialized, as expected. What does the vector member does to member x, that makes x gets initialized even though it is not initialized at declaration and fundamental types are not supposed to initialized upon ... | x is uninitialized. Reading from it causes undefined behavior, which can have any effect, including giving you 0 every time.
You can inspect the generated assembly to know what exactly is going on, but I don't see much value in it.
|
67,032,188 | 67,032,261 | Error C2661 'fmt::v7::print': no overloaded function takes 3 arguments | I am trying to do :
fmt::print(fg(fmt::color::red), "A critical error has occured. consult the logs and fix the issue! {0}", std::endl);
This results in the error message: Error C2661 'fmt::v7::print': no overloaded function takes 3 arguments.
Looking at the official documentation here shows the fmt::print as :
templ... | std::endl is a template, but template arguments can't be determined in this case, you have to specify them explicitly. e.g.
fmt::print(fg(fmt::color::red),
"A critical error has occured. consult the logs and fix the issue! {0}",
std::endl<char, std::char_traits<char>>);
// ^^^^^... |
67,032,468 | 67,032,581 | How do I select a random item out of an array? | I'm making a rock paper scissors bot that randomly picks rock, paper or scissors. I have an array called rpsoptions as shown below.
#include <iostream>
#include <string>
int main()
{
std::string rpsoptions[3] = {"rock", "paper", "scissors"};
std::cout << ( RANDOM ITEM FROM ARRAY) << std::endl;
}
How do I selec... | You do this by:
Generating a random index into the array (in your case between 0 and 2); let that index be i.
Emitting rpsoptions[i].
As @ThomasSablik notes, the first step is covered by this question:
How to generate a random number in C++?
Combining the two steps, here is what you could get for your program:
#inclu... |
67,032,480 | 67,032,576 | How to pass the type of a variable to a template method? | I think the best explanation is an example. I have 2 different variables of different types, and I want their type max values:
int iVal;
size_t sVal;
auto iMax = std::numeric_limits<**??**(iVal)>::max();
auto sMax = std::numeric_limits<**??**(sVal)>::max();
So, is there a method to replace ?? with something that will... | decltype is used to deduce type of an expression. Here you can use it like:
auto iMax = std::numeric_limits<decltype(iVal)>::max();
auto sMax = std::numeric_limits<decltype(sVal)>::max();
or additionally you can form a template function to do it for you:
template<typename T>
auto maxof(const T&){
return std::numer... |
67,032,582 | 67,032,662 | Values of padding bytes in C | I've spotted a strange behavior in this small C program. I have 2 structures, both with padding bytes, but in different places.
The first structure has padding bytes with indices [1:3], and the output is expected: static variables are zeroed-out, so padding values are all 0, local variables on stack are left with garba... | There's no problem if I run your program. Last bytes are random. It likely depends on your system.
|
67,032,916 | 67,033,076 | C++ Does the compiler optimize out known statements? | This question no doubt would constitute premature optimization, however I want to know what the compiler will do with this to learn more about how the compiler works.
In the below example, can I expect the compiler to produce 2 or 3 functions with the if statements removed, or is it always going to execute that if stat... | This depends entirely on the compiler and optimization level.
For example, GCC 10 will transform loops to hoist invariants out at -O3 level. We can see in this demo (Godbolt link) that it generated 3 separate loops essentially:
myfunction(int):
push rbp
push rbx
mov ebx, edi
su... |
67,032,938 | 67,033,399 | Templated rvalue reference vs non templated compilation errors | #include <typeinfo>
#include <iostream>
using namespace std;
template<typename T> void f1(T&& a) {}
void f2(int&& a) {}
int main()
{
int i = 0;
f1(i);//This is fine
f2(i);//This gives compilation error
}
Why is same type of calling is having different compilation rules?
templated f1 accepts lvalue, but non t... | In a template context, T&& isn't just an rvalue reference, it's a forwarding reference.
In a call f1(i), T is deduced as int&, and according to reference collapsing rules, int& && becomes int&, i.e. an lvalue reference.
That's why it is able to bind to int x.
In a non-template context as in f2, int&& is just an rvalue ... |
67,033,165 | 67,033,239 | How do you do logical exclusive XOR in the C preprocessor with defines | What's the simplest way to ensure that only one of two names is defined, for example:
#define USE_OPTION1
#define USE_OPTION2
#if not(USE_OPTION1 ^ USE_OPTION2)
#error "You must use at least one option, but not both"
#endif
I know there's no logical XOR in C or C++, so what's the best way of doing this? It doesn't ha... | you can solve this by checking if both are defined equally. so 0 0 and 1 1 will throw the error, while 0 1 and 1 0 are allowed.
#if defined(USE_OPTION1) == defined(USE_OPTION2)
#error "You must use at least one option, but not both"
#endif
|
67,033,217 | 67,033,367 | Having a std::vector related conceptual problem | I have been using vectors but only for the convenience of resizing which they offer. Today, I realized that I do not understand std::vector fully. I have created a data structure needed for my program. It is defined as:
vector<vector<string>, int> memtable;
// the idea is that an element of this vector is something lik... | A std::vector has two template parameters, the 1st (T) being compulsary (the type of the value contained) and the 2nd (Allocator) (not compulsary) the allocator type that is used to provider memory for the 1st (T). Note that a vector is a sequence of values of type T (is is not a sequence of types).
The prerequisites f... |
67,033,549 | 67,034,020 | C++ : Problem faced while implementing observer design pattern with smart pointers | I am trying to implement observer design pattern in C++. I want it to be in such a way that the observer need not explicitly remove itself when being destroyed. So, I am trying to use a vector<weak_ptr<Observer>> to maintain the observer list in the Subject class.
I also want the observers to add themselves to the subj... | Use "static constructors":
class observer1 : public observerInterface
{
public:
explicit observer1(const OtherParam&);
static std::shared_ptr<observer1> create(
Subject& subj, const OtherParam& p)
{
auto ptr = std::make_shared<observer1>(p);
subj.addObserver(ptr);
return ptr... |
67,033,730 | 67,466,146 | How to set a constraint's motor target? | I am trying to implement a ragdoll in Bullet Physics, mimicking one I created in a Maya plugin which uses PhysX. I have everything 1:1 besides constraint motors.
In physX, motors simply have linear and angular damping/stiffness and a target represented as a mat4 (position and rotation).
Ideally I'd be using btConeTwist... | You should be using the btGeneric6DofSpring2Constraint. It's the most flexible and feature rich out of all of Bullets constraints as well as the most stable from my experience. From what I can tell you understand how to setup the constraint frames and the rest of the constraint, so I'll skip that part. Setup is the sam... |
67,034,029 | 67,197,430 | Using std::atomic with futex system call | In C++20, we got the capability to sleep on atomic variables, waiting for their value to change.
We do so by using the std::atomic::wait method.
Unfortunately, while wait has been standardized, wait_for and wait_until are not. Meaning that we cannot sleep on an atomic variable with a timeout.
Sleeping on an atomic vari... | You shouldn't necessarily have to implement a full custom atomic API, it should actually be safe to simply pull out a pointer to the underlying data from the atomic<T> and pass it to the system.
Since std::atomic does not offer some equivalent of native_handle like other synchronization primitives offer, you're going t... |
67,034,132 | 67,035,229 | gperftools not installing -lprofiler on Mac after installing it with brew | Recently I wanted to profile my cpp code and came across gperftool, but there aren't really clear instructions on how to use it with Mac. So far I have run brew install gperftools and wanted to compile my simple cpp file which just outputs "Hello world!". I run g++ main.cpp -lprofiler -o main but get error ld: library ... | So brew didn't install the binaries and that's it.
Follow these steps if you are having a hard time making it work
clone https://github.com/gperftools/gperftools
run ./autogen.sh
run ./configure
make && sudo make install
you should see some path where the binaries where installed, if you wanna take a look at it to mak... |
67,034,688 | 67,035,014 | const char* returns true in C++ CLI | since yesterday I have been struggling to turn text into label with code from another class, I came to this:
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
TestApp::UI_Error form("test", "test");
Application::Run(% form);
Using the above code, i display a winapi form that rec... | Maybe I am wrong here, but System::Convert::ToString() seems not to have a method that accepts a const char* pointer. It looks like it gets cast to something else.
Try this instead:
Text = gcnew System::String(errorText);
|
67,034,761 | 67,035,040 | Why a struct pointer can't be declared by another struct pointer | Today, I have learned about the Binary Search Tree, and I am trying to implement it, but I got a problem.
Assume that I have a Struct like this:
struct Node {
int v;
Node* left = NULL;
Node* right = NULL;
}
Below it, I have:
// At the beginning, root is NULL
Node* root = NULL;
Node* new_node(int v) {
... | In your code you do not modify root after initialization. root is always NULL. This
Node* c = root;
// ...
c = new_node(v);
will not change root. It merely declares a local variable c, initializes it with the value of root and assigns a new value to it.
If you want to change the value of something inside a function yo... |
67,035,706 | 67,037,333 | Why doesn't default template type refer to specified type in instantiation? | #include <typeinfo>
#include <iostream>
using namespace std;
template<typename T, typename U = T> void f1(T a, U b)
{
cout<<typeid(a).name()<<endl;
cout<<typeid(b).name()<<endl;
}
int main()
{
f1<float>(1,2);
}
output:
f
i ----> why is it int not default float as per template instantiation?
| Default template arguments are last resort, and used only when the argument wasn't specified or deduced.
It's specified in [temp.deduct]/5:
The resulting substituted and adjusted function type is used as the
type of the function template for template argument deduction. If a
template argument has not been deduced and ... |
67,035,898 | 67,038,341 | Saving Class Object to Binary File | I am looking for an easy way to save and load this C++ object to and from a binary file.
#include <iostream>
#include <vector>
class User
{
private:
std::string _name;
int _age;
std::vector<std::string> _hobbies;
public:
std::string Name() { return _name; }
int Age() { return _age; }
std::vect... | Here is a very abstract idea of what you want, Write string size that helps to read string back for name, write age, again wite hobbies size that helps to read it again and finally write each string with it size. To read reverse the process,
#include <iostream>
#include <fstream>
#include <vector>
class User
{
private... |
67,035,899 | 67,036,289 | Why my function in C++ is not being executed? | I have a C++ lab and the problem is this: The user should enter a value for X(X is the number of tests held). If x<15, the program does not calculate anything. If X is between 16 and 30, the program should calculate C=1.0/10.0*(24A) and if X>30 the program should calculate C=0.15(24*A). My multiple if code works but wh... | cin >> C; will get the user input for C.
change it to cout << C in both the else blocks.
|
67,035,987 | 67,036,708 | Is there a problem with this code? I can't get it to work. Help me PLEASE | The purpose is to sort, display, and average out scores input by the user.
I haven't been able to figure it out yet.
If you have solved this, please help.
So far, I have tried this code, but it doesn't work.
#include<iostream>
using namespace std;
void sortArr(int [], int);
void getAvg(const int [], int);
int main()
... | As the others have pointed out, your declaration of sortArr() does not match the definition.
The Declaration:
void sortArr(int [], int);
The Definition:
void sortArr(int *arr[], int SIZE) {...}
As you see, the definition says that sortArr() takes parameters of an array of ints, and a int. However, your definition sa... |
67,036,063 | 67,036,265 | Why path with 2 words ("Start Menu") doesn`t work correctly in c++? | It doesn`t work because it could be "Start menu", not Start menu . But system("_path_"Start Menu"_path_") gives an error (system('_path_"Start Menu"_path_') also gives an error). How to fix it?
Code:
system("move C:\\Users\\%USERNAME%\\Downloads\\a.exe C:\\Users\\%USERNAME%\\AppData\\Roaming\\Microsoft\\Windows\\Start ... | system("move \"<src_path>" \"<dest_path>\"");
Also, if you need escape a " characters inside of a path, use \ to escape, but as far as I know, Windows would not allow you to name entities with particular set of special characters.
|
67,036,418 | 67,320,122 | My custom vector has a run-time error Debug Assertion Failed: _CrtIsValidHeapPointer(block) | PART OF MY VECTOR CLASS
class CVector
{
friend ostream &operator<<(ostream& output, const CVector& vec);
public:
CVector()
{
sPtr = new char[10];
size = 0;
capacity = 10;
}
CVector(const CVector &vec)
{
size = vec.size;
capacity = vec.capacity;
... | In your copy constructor, you allocate vec.size bytes, but set capacity to vec.capacity. You probably want to allocate vec.capacity bytes instead.
The next thing is, that there is a difference between copy construction and copy assignment:
CVector vecb(veca); // this calls the copy constructor
CVector vecc; // this cal... |
67,036,548 | 67,036,608 | How to correctly delete a pointer after using new operator? Code Keeps Throwing Error | So I keep getting the same error when trying to delete pointers after I've used the new operator.
I've checked online for ages and can't wrap my head around whats going on, I'm very new to C++ and am working on a university assignment.
Additionally I've successfully used new and delete operators for integer arrays and ... | The short answer is, remove all pointers, new and delete from your code.
There is no need for it anywhere.
Literally remove every call to both, and remove every * (except when being used to multiply), and your code becomes correct.
Not for this problem, but in other situations, you need to read up on the rule of five,... |
67,036,885 | 67,036,929 | Try/catch all block in C++ program not working | Try/catch block in C++ not being "caught."
I'm trying to have one catch block to get all exceptions.
#include <iostream>
#include <exception>
using namespace std;
int main()
{
try
{
throw 1;
}
catch (exception& e)
{
cout << "ERROR: " << e.what() << endl;
return 1;
}
return 0;
}
| throw 1; will throw an int. As you do not catch an int, the exception goes uncaught, which is undefined behavior. Though it is possible to throw anything, always prefer to throw a class that derives from std::exception. You can catch an int with catch(int e) or catch(...), but there's really no reason to ever do that... |
67,037,003 | 67,038,904 | Visual Studio 2019 is not running other .cpp files |
New to VS and C++. I'm trying to run code for source file "test2.cpp." However, every time I run the program, VS always runs "Simple-letter-with-ASCII-number.cpp."
I'm on the "test2.cpp" window, but the file never runs. I need assistance in running "test2.cpp" and not "Simple-letter-with-ASCII-number.cpp," without del... | Your project will call main() when it runs. When you said “differently labeled main()” I am assuming you changed a main() to test2main(). Just change the main function you want to run to be main() and your program should run when you recompile.
|
67,037,605 | 67,038,019 | Is there a better way to draw multiple points in SFML? | I am trying to draw every pixel on an 800 by 800 window with a random color, and I am drawing the pixel using sf::Vertex, but when I run the program, it is very slow. Is there a better way to draw multiple points that is faster and uses less memory? Here is the code I wrote:
#include <SFML/Graphics.hpp>
#include <ctim... | Thanks to one of the comments, I now know how to fix this problem.
Instead of using a bunch of sf::Vertecies, I could use a sf::Image. What I did was that I created an image the size of the window and made it all black. Then instead of drawing each individual point, I set each of the pixels in the image to a random col... |
67,037,801 | 67,038,870 | How to read the matrix from file and make some change in it and again write it to the file? | How to read the content of matrix from file to again in the matrix. so I can use it for updating some value in it and again copy this in the matrix ...
In this first, I check that file is empty or not if it is empty then I write a matrix with all values zero, if it is not empty then I read the value from the file and p... | Here is an example of how to read a matrix from a file
#include <fstream>
#include <iostream>
#include <cstring>
int main() {
int arr[10][10];
for (std::size_t i = 0; i < 10; i++)
for (std::size_t j = 0; j < 10; j++)
arr[i][j] = 0;
std::size_t m1 = 10;
std::size_t n1 = 10;
... |
67,037,983 | 67,038,345 | C++ pointer referencing itself not producing expected output | I'm working with C++ pointers and I've encountered something curious.
If I reset a pointer to itself using "b = (int*)&b;", I expected the deferenced output to be the memory address of itself -- since it was pointing to itself.
So I thought *b would be "0x7ffea00819b0", but it's some strange numeric value.
But this isn... | Changing the type to unsigned long int fixed the issue.
Thank you all!
#include <iostream>
#include <type_traits>
using namespace std;
int main(int argc, char** argv)
{
unsigned long int a = 10;
unsigned long int *b = &a;
b = (unsigned long int*)&b;
cout <... |
67,038,510 | 67,039,129 | Map constructor with comparator | class cmp{ // simple comparison function
public:
bool operator()(const int x,const int y)
{ return x > y; }
};
When I call any stl algorithms like std::sort with an object of compare , it works fine.
std::sort(vec.begin(), vec.end(), cmp());
But for stl containers this is not similar.
std::map<int, int> mp(c... | This works:
std::sort(vec.begin(), vec.end(), cmp());
because function templates can deduce their template arguments from the provided arguments. For stl containers this does not work because you're not calling a template function, but declaring a specialization of a class template.
std::map<int, int> mp(cmp()); // N... |
67,038,680 | 67,103,313 | Is there a solution to asynchronously wait for C++ data on Flutter's invokeMethod? | Currently, this is how I read from C++ using Flutter:
final Uint8List result = await platform.invokeMethod(Common.MESSAGE_METHOD, {"message": buffer});
It is handled by Kotlin like this:
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
if (call.metho... | If reading something from C++ is a heavy process, You can use AsysncTask to perform it in the background for android.
internal class HeavyMsgReader(var result: MethodChannel.Result) : AsyncTask<ByteArray?, Void?, String?>() {
override fun doInBackground(vararg message: ByteArray?): String {
//... //respons... |
67,038,822 | 67,039,066 | C1202: recursive type or function dependency context too complex | I tried to write a function that would call back with every permutation of size n:
template<typename F>
void permutationsCallback(int n, F f) {
if (n == 1) {
f(std::vector<int>{0});
}
else {
permutationsCallback(n - 1, [n, &f](std::vector<int> p) {
p.emplace_back(n - 1);
... | There is an infinite recursion inside the template.
Even if you know the else-block won't be called at runtime, at compile time, the compiler needs to know what code would have gone into the else block, endlessly.
You can for example consider making n a template parameter instead, and implement the 0 case, like MSVC ex... |
67,038,825 | 67,038,878 | Using universal references with non template types? | I am building a simple piping operator for vectors, which the user would use like this (pseudocode):
auto x = std::vector{1,2,3} | push_back(10)
| push_back(100)
;
Now I tried defining the piping operator like so:
template <typename T>
constexpr inline auto& oper... | Sure, you can use forwarding references.
template <typename T> inline constexpr bool is_vector = false;
template <typename ...P> inline constexpr bool is_vector<std::vector<P...>> = true;
template <typename T> requires is_vector<std::remove_cvref_t<T>>
constexpr auto &operator|(T &&vec, std::invocable<T> auto &&func);... |
67,038,893 | 67,038,927 | C++ linked list insert_end() | #include <iostream>
using namespace std;
class Node {
friend class LinkedList;
private:
int value;
Node *pNext;
public:
Node();
Node(int);
~Node();
};
class LinkedList {
private:
Node *pHead;
Node *pCursor;
public:
LinkedList();
void insert_front(int);
void insert_end... | while(pCursor!=NULL) pCursor = pCursor->pNext;
iterates pCursor untill it's NULL
pCursor->pNext = pNewNode;
is now dereferencing the NULL pointer.
What should you be doing? Probably stop one earlier, iterate until pCursor->pNext is NULL and then allocate the new one into pCursor->pNext as you are already doing.
|
67,039,119 | 67,042,922 | Adding numbers from 1 to 100 OpenMP | I'm trying to get the sum of numbers from 1 to 100 using only 5 threads even though I have 12 available.
This was my approach.
Please show me where I went wrong.
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
int nthreads = 5, tid;
int sum = 0;
int a[100];
for(int i = 1; i... | You have some problems in your code, namely:
First:
for(int i = 1; i < 101; i++){
a[i] = i;
}
you have allocated the array a as int a[100];, so in your loop you are getting of the array boundaries, changed it to:
for(int i = 0; i < 100; i++){
a[i] = i + 1;
}
Second:
int nthreads = 5
...
/* Fork a team of thre... |
67,039,132 | 67,048,764 | "nghttp2::asio_http2::client" with TLS 1.3 - SSL_CTX_set_cipher_list doesnt add cipher suite in cipher suites | I use nghttp2 asio_http2_client with TLS 1.3 protocol, but when i try to add additional suites in cipher suites list via SSL_CTX_get_ciphers function, i don't see anything changes in my Client hello message. I.e. cipher suites list stay without changes.
My code example:
#include <nghttp2/asio_http2_client.h>
#include ... | If you go to the documentation for SSL_CTX_get_ciphers it states:
SSL_CTX_set_cipher_list() sets the list of available ciphers (TLSv1.2
and below)
and
This function does not impact TLSv1.3 ciphersuites. Use
SSL_CTX_set_ciphersuites() to configure those.
So you need to go read the SSL_CTX_set_cipher_list API as the ... |
67,039,285 | 67,039,399 | keeping shared_ptr use_count() at 1 | I was unable to find a similar question to this one, please direct me to one if I missed it!
I am experimenting with smart pointers, and came to this scenario where I would like to keep the value returned by use_count() in a shared_ptr object to 1 (to practice optimizing code). Here is a snippet I am working with:
#i... | The problem is the temporary initializer_list<shared_ptr> keeps a copy of the elements, and it lives until the end of the full-expression (the ;).
There isn't much you can do, an initializer_list always stores its elements by copy.
As a workaround, you can construct the vector beforehand:
std::vector<std::shared_ptr<in... |
67,039,304 | 67,039,471 | New to programming: How to call a structure's variables in a function and then update them? (C++) | I've created a function below getPoint() that is supposed to ask the user for two points so I could late calculate the slope of them. This function is supposed to call for two variables in struct Point to assign them to. These variables in struct Point have to be floats, and the function needs to return a Point variabl... | Seems to me that you want this:
#include <iostream>
struct Point {
float X;
float Y;
};
struct Line {
Point Point1;
Point Point2;
float slope;
float yInt;
float lineLength;
float Angle;
};
Line getLine()
{
Line var;
std::cout << "enter the first point:";
std::cout << "\nE... |
67,039,378 | 67,040,551 | C1189 #error: <mutex> is not supported when compiling with /clr or /clr:pure | I have a C++ library with managed C++ classes and unmanaged C++ classes, so the library is compiled with /clr support. I need to make some thread safe locking on the unmanaged side but if I include I have the compiler error:
C1189 #error: <mutex> is not supported when compiling with /clr or /clr:pure
How can I work a... | A mixed-mode project can include both unmanaged C++ and managed C++/CLI code. Since <mutex> "is not supported when compiling with /clr" the code that requires it needs to be moved into a separate .cpp file set to compile without /clr. That can be done by adding a new .cpp file to the project, then changing the Property... |
67,039,381 | 67,039,569 | How to make GetLocaleInfoEx return its data in a specific language? | I'm using GetLocaleInfoEx to obtain the "display name" of a locale : however, I would like the "display name" to be returned in the language that's used in that locale.
The code amounts to this (ex-MX is used here as an example) :
const wchar_t localeName[] = L"es-MX";
wchar_t buf[1024];
GetLocaleInfoEx(localeName, LOC... | You can use LOCALE_SNATIVEDISPLAYNAME instead of LOCALE_SLOCALIZEDDISPLAYNAME iin your call to GetLocaleInfoEx.
|
67,039,546 | 67,039,675 | How do pointers to 2d arrays work in C++? | I'm pretty new to C++ and I've been playing around with the language to try to understand most of it.
I recently started to look into 2d arrays, and I totally understand arrays of pointers to arrays (created on the heap), but I have a harder time with the code below.
int arr2d[3][2] = {
{1, 2},
{3, 4},
{5, ... | This is actually very interesting and, the more you learn about C++ the more completely irrelevant you find it becomes in all but rare situations.
int arr2d[3][2] = {
{1, 2},
{3, 4},
{5, 6}
};
So here you have an identifier arr2d and that identifier has a type:
array of arrays
Now the type array in C++ rel... |
67,039,971 | 67,040,045 | Faster way to write an integer vector to a binary file with C++? | I currently have the following method for writing vector<int> objects to a binary file.
void save_config(std::string fname, std::vector<int> config) {
std::ofstream out(fname);
for (auto&& item : config)
out << item;
}
The data I need to save, however, is on the order of 60 MB and takes about 5 seconds... | Whether or not it will result in a significantly faster operation will have to be tested, but the following use of the write() function avoids iterating through the vector:
#include <fstream>
#include <vector>
void save_config(std::string fname, std::vector<int> config)
{
std::ofstream out(fname, std::ios_base::bi... |
67,040,137 | 67,041,169 | Is this good or bad practice with dynamic memory allocation? | I've seen this used by other people and it looks really clever, but I'm not sure if it's good or bad practice. It works, and I like the way it works, personally, but is doing this actually useful in the scope of a larger program?
What they've done is dynamically allocate some data type inside the actual function argume... | No, this is not clever at all. It takes a function that could be simpler and more general and reduces its capabilities for no reason, while at the same time creating an entry point into your program for difficult-to-debug bugs.
It's not clear to me exactly what Foo::new_num is meant to do (right now it doesn't compile... |
67,040,145 | 67,055,662 | Function that returns max element of an array of different types | I have couple of compare function that go something like this:
int greater_than_int(const void *a, const void *b) {
if (*(int *)a > *(int *)b) return 1;
return 0;
}
and a max function that goes like this:
const void* max(const void *base, size_t members, size_t size,
int (*compar)(const void *, c... | Since you're forced to work with those function signatures, here's one way of dealing with them.
// I suggest changing this to `bool`, but you can leave it as `int` if you must
bool greater_than_int(const void *a, const void *b) {
// no need for `if(...)` - just return the result of the comparison
return *stati... |
67,040,290 | 67,040,307 | Can we have more than one namespace in a library (in c++) | I'm new at oop an I just discover the namespace , I want to know if we can have more than one namespace in a library
| Yes, you can have multiple:
namespace A {};
namespace B {};
And nested:
// Pre C++17
namespace A {
namespace B {};
};
// C++ 17+
namespace A::B {};
|
67,040,392 | 67,040,489 | Range checking for int32_t data type in C++ | I'm trying to range check a user supplied command line parameter in a C++ program and I'm not sure how to do it.
If I enter a number that's higher, it gets converted to a lower number.
What's the preferred method to do the below? Is there a constant that I can reference? And if so, is there a better way to do this rang... | Clearly, any number more than 5 digits is bogus, and atoi will handle any number less.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc, char** argv)
{
if (argc < 2) {
cout << "Usage: " << argv[0] << " <port number>" << endl;;
return 1;
}
int32_t port = atoi(... |
67,040,862 | 67,187,916 | Set object as External without allocating memory | I would like to return an object which has its own object template, but am not sure how to do this without allocating memory for that object. This is because I don't know how/when to delete this memory.
Here is what I have so far:
auto objectTemplate = MyObject::GetObjectTemplate(isolate);
auto context = isolate->GetC... | It looks like there is no way to avoid allocating memory, but the memory can be garbage collected by using v8::PersistentBase::SetWeak().
|
67,040,941 | 67,040,991 | How do I pass in a function to a constructor that will then be set to a variable? | I don't understand what I'm doing wrong. I'm trying to pass a function into a constructor, set that function to a variable, and then call that variable at a later time. (like a callback)
The error I'm getting is that "no matching constructor" since void isn't the callback... but I thought the callback was just a method... | There are several problems here.
typedef void *callback();
This declares callback to be a function that returns a pointer to void.
Cars(callback* method);
Therefore, the constructor takes a pointer to a function that returns a pointer to void. Your obvious intent is to use a pointer to a function that returns a void,... |
67,041,099 | 67,066,575 | MFC MDI Toggling a tab in the output window without having to restart (in my case) | So I'm using the MFC wizard created output pane and everything works as I want it. What I'm trying to figure out is how to hide/show a specific tab with the user selecting it from the menu. I have two tabs, one is status, one is debug...I have a user menu option to turn the Debug on/off and I do this by using a switch ... | You don't have to Remove and add Tab. Show/Hide Tab using ShowTab() is suitably.
Here the example with ShowTab. Because the Tab can dymamically be moved anywhere, you must search the desired Tab for sure.
void COutputWnd::OnOutputtabsDebug()
{
// Toggling OutputTab
CString strDebugLabelShould;
strDebugLabelShould... |
67,041,130 | 67,041,196 | i could not solve this [Error] 'rand' was not declared in this scope in dev c++ | void Setup() {
gameover = false;
dir = STOP;
x = width / 2;
y = height / 2;
fruitX = rand() % width; //display fruit in a random place
fruitY = rand() % height; score = 0;
}
| Please use #include <stdlib.h> at the top of c code.
|
67,041,322 | 67,041,476 | Is it possible to navigate around the circular dependency? | Strange and potentially stupid question.
As a mini project, I've been working on creating a Ptr class to duplicate the mechanism of a pointer - the user should theoretically be able to use this class just like a real pointer without issue and without needing to interact with "actual" C++ pointers (besides some obvious ... | Your problem is not circular dependency but the fact that your Ptr class contains an element instead of a pointer. So your tree_node needs to contain inside two whole copies of itself! That it is not technically possible.
To make the code make sense and compile you just need to make Ptr into an actual wrapper of a poin... |
67,041,520 | 67,041,639 | What's the best way to have a "multitype" member variable in a class? | I'm currently working on adding new functionality to an already defined class in our codebase, and I'm running into issues due to not having encountered a problem like this before (I'm still fairly new to C++/coding). Below is a simplified version of the class:
class Foo {
public:
Foo();
~Foo();
Input ReturnInpu... | Assuming a given Foo object doesn't need to be able to switch from holding-a-Fizz to holding-a-Buzz at runtime, C++ templates would give you the flexibility you need without the code duplication of writing both a FooFizz and a FooBuzz class:
template <class T> class Foo {
public:
Foo();
~Foo();
Input ReturnInput... |
67,041,811 | 67,041,860 | Assigning value to vector index | This is the part of my code. I am assigning values to vector v by two different ways. while it is working fine with k[0]=a and k1=b but When i am using push_back function then the vector k returns value 0. what is the difference between these two?
class Solution{
public:
vector<int> sumClosest(vector<i... | By doing the following, you are making a vector whose size is 2, and every element in the vector will be initialized to 0.
vector<int> k(2);
By using the push_back method, you are pushing a new element to the back of the vector, which effectively increases the size of the vector increase by 1.
If you want to push two ... |
67,042,118 | 67,042,231 | What is the correct syntax to call the constructor of the parent class in a derived class with templates in c++? | My class needs to call the constructor of his parent class. But I am having issues with that, due to the fact that they are template classes.
The code of my derived class is given below:
template <class CTHIS, typename T>
class genericalMethodClassWithSeveralInternalParametersClass:public genericalMethodClassWithIntern... | The only place where you can call a base class constructor is in the constructor initializer list:
genericalMethodClassWithSeveralInternalParametersClass(float (CTHIS::*_funcVersionWith2Paramaters)(float, myNUpleType<T>) const, const CTHIS *_thisPar, myNUpleType<T> _fixedParam)
:genericalMethodClassWithInternal... |
67,042,220 | 67,042,265 | how can i generate hex file from cpp file with avrdude | I have a string code.
void setup() {
pinMode(5, OUTPUT);
}
void loop() {
digitalWrite(5, HIGH);
delay(1000);
digitalWrite(5, LOW);
delay(1000);
}
I want to create a hex file from that string code using avrdude.
Is there a command to do this?
Thanks.
| You're confusing some things here
this is an Arduino sketch, not a .cpp file, you'll need the Arduino framework and most importantly a compiler to compile this
avrdude is not a compiler so you cannot turn source code into binaries with it.
AVRDUDE is a utility to download/upload/manipulate the ROM and EEPROM content... |
67,042,750 | 67,043,039 | Should set::equal_range() return pair( set::lower_bound(), set::upper_bound() ) | Yeah, I know, I should have a repro, but the repro is annoying to produce. Before I produce one (and maybe give clang a bug) I want to ensure that my understanding of how things should work is correct.
MSVC: Returns set::equal_range() as {lower_bound(),upper_bound()}.
Clang: Returns set::equal_range() as {lower_bound... | Any custom comparator that is used for std::set should satisfy Compare requirements (strict weak ordering + equivalence). You have UB in your code, and the difference you see is the consequence of that UB. In your example, the elements are pairs (a, b) and the comparator (let's call it less) is (a, b) < (c, d) iff b < ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.