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 |
|---|---|---|---|---|
65,290,229 | 65,290,602 | Change output order from vector and my map c++ | I am new to coding in c++ and need help now. I have made this program that reads how many times a word occurs in a text file and then print it. But my probmlem is that I want the word which occurs most in the top of the list produced by cout, now the word "the" is printed last but I want it to be first in the list and ... | There are multiple possible solutions to your issue. (i) Using a (reverse) loop or iterator to go through the final vector, end to start, (ii) directly sorting from largest to smallest (I suppose val_lt does a "less than" comparison, so you want to use a "greater than"...) .
Easiest change to your code would just be t... |
65,290,309 | 65,323,679 | Using UTF8 in Postgresql ODBC connection | I'm trying to insert some UTF-8 strings into PostgreSQL database. I'm using Visual C++ and MFC (this bit probably not important) and a project setting "Use Multi-Byte Character Set" (trying to switch database in an old legacy app). So when I execute some INSERT command with some text in Cyrillic "АБВГ" I expect to see ... | Change your ODBC DSN connection string to include this: ConnSettings=SET CLIENT_ENCODING TO 'UTF8';
|
65,290,728 | 65,290,815 | Are left out fields by C++ 20 designated initialization guaranteed to be zero initialized? | When using C++ 20 designated intializers it is not required to specify a value for every field:
struct Foo
{
int i;
void* p;
};
can be initialized like this:
Foo bar = {
.i = 22
};
Are the left out fields zero-intialized? So in this example is p guaranteed to be set to nullptr?
|
Are the left out fields zero-intialized?
In this case, yes. The rule is (from [dcl.init]/5):
For a non-union aggregate, each element that is not an explicitly initialized element is initialized as follows:
If the element has a default member initializer ([class.mem]), the element is initialized from that initialize... |
65,290,854 | 65,297,014 | Read message up to % character | I have a char array:
char arr[] = "%RED**dsa0x0%xcа%wq233SSS%(dsa........";
The array must be read from the % sign to the next %. That is, the message begins with % and has an unknown length (there can be no % in the middle of the message).
Here is the code:
void SaveMessToVec(const string& str)
{
tail = tail + st... | If you can use vector and string you can use this function.
std::vector<std::string> split(const std::string& s, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter)) {
if(token.size()!=0)
... |
65,290,961 | 65,291,623 | Can I succintly declare std::unique_ptr with custom deleter? | I am dealing with C types which have a new_ and free_ methods associated.
The type signature of new_ may vary, but the free_ is always a void free_something(something*);
Currently, I am declaring my unique_ptrs this way, which seems overly verbose:
std::unique_ptr<qdr_link_t, decltype(&free_qdr_link_t)> link{new_qdr_li... | Let the language do the hard work!
#include <memory>
struct qdr_link_t;
qdr_link_t* new_qdr_link_t();
void free_qdr_link_t(qdr_link_t*);
template <typename T, typename Deleter>
auto make_unique_ptr(T* raw, Deleter deleter)
{
return std::unique_ptr<T, Deleter>(raw, deleter);
}
//std::unique_ptr<qdr_link_t, declty... |
65,291,188 | 65,291,320 | #define a template method | I would like to add debug within a template function, however not looking at re-editing the whole code.
Would one be able to
#define theFunction<T>(size) _theFunction<T>(size, __FILE__, __LINE__)
template<class T> T* _theFunction(int size, string file, int line)
{
if (fails) {
pri... | Something along these lines, perhaps (not tested):
struct TheFunctionHelper {
std::string file;
int line;
template<typename T>
T* invoke(int size) {
return _theFunction<T>(size, file, line);
}
};
#define theFunction TheFunctionHelper{__FILE__, __LINE__}.invoke
|
65,291,278 | 65,291,832 | Arduino servo and DC motor not working properly | I'm very new to the Arduino world but I have some experience of programming in other language.
I'm trying to make my first robot car, I have 2 DC motors connected to a L298N module, all connected to a 9V battery and an Arduino Uno.
The DC motors are connected to port 5,6,7 for motor 1 and port 8,9,10 for motor 2.
The c... | Have you tried to use another pin instead of pin 13 to control servo? Pin 13 is not recommend to control the servo because there is a LED connected to pin 13. Try pin 3 because it has PWM and it has no pull up resistor connected.
|
65,291,536 | 65,291,689 | How to project elements nestedly in c++20 constrained algorithms? | Suppose I have a std::vector of std::pairs, then I can using c++20 constrained algorithm's projection facility to sort elements according to sub-object:
std::vector<std::pair<int, std::string>> v;
// sort by std::string
ranges::sort(v, {}, &std::pair<int, std::string>::second);
but how to do nested projection like thi... | The projection is just an arbitrary callable. Providing a pointer to member is convenient if that works. But if it doesn't, just use a lambda:
ranges::sort(v, ranges::less(), [](auto const& elem) { return elem.second.size(); });
|
65,292,041 | 65,292,209 | Returning a function's static array to another array in the main() function | I figured out how to make this one work already but can't explain in details what is so different in these two codes here.
Incorrect code:
const int nRows = 2;
const int nCols = 2;
int * colSum (int [nRows][nCols]);
int * rowSum (int [nRows][nRows]);
int main() {
int my2Darray[nRows][nCols] = {{10, 20}, {30, 40}}... |
Was I just decaying to the first element of totalsByColumn by using the dereference operator on my first block of code?
Yes.
I feel like there might be a quicker way of adding the columns and rows together
Certainly. Also ways that are thread safe unlike your solution. A simple way is to use an output iterator to w... |
65,292,674 | 65,296,963 | How to export only a subset of header-only boost libraries? | From the boost library, I only require circular_buffer for an android project (maybe some other later, but it will always be header-only). Thus, I would like to create a distribution containing only the required files.
I tried using the official distribution, and executing :
./bootstrap.sh --includedir=.. --with-librar... | Bootstrap and b2 are only required for building library binaries. As you said, you will use header-only only, so that's not required.
You can just zip up the boost/ include folders and be happy.
In theory you can prune the set of includes with BCP: https://www.boost.org/doc/libs/1_75_0/tools/bcp/doc/html/index.html
How... |
65,292,744 | 65,292,958 | how to terminate cin taking a value on space intead of carriage return because it cause the program to go to next line and I want it on the same line? | #include <iostream>
int main()
{
int int1, int2;
std::cout << "Enter pair of integer e.g (Integer1,integer2) : ";
std::cout << "( ";
std::cin >> int1;
std::cout << ",";
std::cin >> int2;
std::cout << " )\n\n";
}
Actual output: Enter pair of integer e.g(Integer1,integer2) :(1
,2
)
I want... | #include <iostream>
int main()
{
int int1, int2;
std::cout << "Enter pair of integer e.g (Integer1,integer2) : ";
std::cin >> int1 >> int2;
}
If you type two numbers without a space, you will get their values. You lose the "()", but do you really need them?
Here's an example where the user is required t... |
65,292,785 | 65,293,037 | C++17 static template lazy evaluation | Considering the following example:
#include<iostream>
template<int n>
struct fibonacci {
static const int value = n < 0 ? 0 : fibonacci<n-1>::value + fibonacci<n-2>::value;
};
template<>
struct fibonacci<1> {
static const int value = 1;
};
template<>
struct fibonacci<0> {
static const int value = 0;
};
... |
I am familiar with lazy evaluation in C++, and would expect that the second branch of the if statement the generic fibonacci template would not be evaluated, when an argument < 0 is passed.
It doesn't need to be evaluated. But we aren't dealing with evaluation here. We are dealing with template instantiation. You use... |
65,293,052 | 65,293,178 | How to swap partition in array from one point to another | I am doing a task for my project in college and in the implementation of the list using arrays (sequential implementation), I need to do a task where all elements move from the left partition to the right partition, while elements from the right partition switch to the left partition.
For example, for the initial list ... | You can simply use std::rotate to do this:
std::rotate(L, L + current, L + numberOfElements);
|
65,293,561 | 65,293,907 | decltype on the variable of reference type with curly braces | Consider the following code:
#include <type_traits>
int main() {
const int& p = 42;
auto v1 = decltype(p){};
static_assert(std::is_same_v<decltype(v1), int>);
decltype(p) v2{};
static_assert(std::is_same_v<decltype(v2), const int&>);
// auto v3 = X(const int&)X {};
}
Type of v1 is deduced... | (To the downvoter(s): if you downvoted because you think quoting Scott Meyers is not equivalent to quoting the standard, oh well...)
As you can read from Effective Modern C++ (augmented with the part of the errata that you can reach by searching for Case 2: at that link, and that just makes the following read simpler, ... |
65,294,024 | 65,303,766 | C++: syntax error detected by MSVC only using Boost::asio | I'm making a basic client-server architecture in C++ using Boost::ASIO.
MSVC reports a syntax error: '.' (C2059) at this line:
void
Server::start()
{
m_stopped = false;
listen_one();
m_runner = std::make_unique<std::thread>([this](){
io_service.run(); // <- syntax error: '.'
});
m_runner->detach();
}
... |
Can you try this->io_service.run()?
MSVC has been challenged with two-phase lookup for a very long time.
What exactly is "broken" with Microsoft Visual C++'s two-phase template instantiation?
http://blog.llvm.org/2009/12/dreaded-two-phase-name-lookup.html
Two-phase name lookup support comes to MSVC (2017)
Perhaps t... |
65,294,117 | 65,294,926 | My input is not showing in c++ at end of program | Guys i made this program. It is working as expected but at the end of my program it is not showing my num variable input.
please help.
Here's code:
#include<stdio.h>
int main(){
int f;
int num;
printf("WELCOME TO THE GAME\n\n");
printf("enter F for starting the game\n");
scanf("%d\n\n",&f);
... | when you input your character, there are two things that happen:
scanf will try to read a number that you input for the first argument
when the number is not in the right format, it will parse the second character to your second scanf.
So when you type F, then hit enter, the first F will be parsed as a number to the f... |
65,294,331 | 65,294,578 | Line and circle intersection points | I have a circle with center at (0, 0) and a line given by the equation y = kx. I need to derive a formula to find the intersection points of this line with a circle. I know the equation shown at the screenshot, but I have a problem with converting the equation of a line from the form y = kx to the form Ax + By + C = 0
| For circle radius R centered at (0,0) we can easily find two intersections with line of form y=kx:
fi = atan(k)
x1 = R * cos(fi)
y1 = R * sin(fi)
x2 = - R * cos(fi)
y2 = - R * sin(fi)
Or in terms of k without trig. functions:
coeff = R / sqrt(1 + k^2)
x1 = coeff * k
y1 = coeff
x2 = - coeff * k
y2 = - coeff
The first ... |
65,294,610 | 65,294,785 | C++ project can't read file when building with CMake | So I have written a C++ project which reads a file into a string.
//func to read file into string
std::string readFile( const std::string& fileName )
{
std::ifstream ifs( fileName );
return std::string((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
}
//func call in main
std... | As said in the comments, CMake created a subfolder in which the output file was located. The test.txt file was in the source folder and therefore out of range. When I changed the working directory to the source folder the program worked.
Thank you for the quick help.
|
65,294,611 | 65,295,824 | d3dx12.h gives a bunch of errors | I'm trying to learn DirectX 12 and i found out these tutorials on github. I downloaded everything and i tried to run the HelloWindow project. I linked the d3d12.lib in Debug->Options->Linker->Input. Unfortunately, it gives me a bunch of errors from d3dx12.h. For most of them, Intellisense says to include d3d12.h even i... | You are using the 'latest' copy of D3DX12.H which requires you use the 'latest' version of the Windows 10 SDK (19041). If D3D12_RESOURCE_DESC1 is undefined, you are using an older Windows 10 SDK.
Note that there are three different options for fixing this mismatch:
Install the latest Windows 10 SDK (19041). For VS 201... |
65,294,697 | 65,294,819 | Can I perfect forwarding an lambda function without knowing the capture? | Here's the snippet that I am trying to make it work
#include <functional>
#include <stdio.h>
#include <utility>
void
bar(std::function<void(int* a)>&& aFunction)
{}
void
foo(std::function<void(int* a)>&& aFunction)
{
bar(std::forward(aFunction));
}
int
main()
{
int b = 123;
foo([b](int*) { printf("Calling \n")... | This is not a use case for std::forward in the first place; foo's aFunction is not a universal/forwarding reference, so std::forward doesn't apply.
You just want to unconditionally move the r-value reference to pass it along to bar; changing the code to:
bar(std::move(aFunction));
is sufficient to make that work.
|
65,294,714 | 65,295,503 | Wxwidgets || Add class and methods | I need to rebuild this code by adding a class with methods. How do I add a class if Zad2frame is already a class?
The first class is supposed to handle addition of complex numbers, the second subtraction etc.
I have all the code in an external file, Zespolone.h(necessary).
#ifndef ZESPOLONE_H_INCLUDED
#define ZESPOLONE... | With C++ each class is usually stored in two files. The header file containing the declaration of the class. For example: MyNewClass.h. And a cpp file containing the implementation of the class. For example: MyNewClass.cpp.
So in this case to use MyNewClass you would have the line #include "MyNewClass.h" near the top o... |
65,294,775 | 65,294,976 | Superclass member pointer becomes null when accessed by subclass | I've been recently doing a lot of reading and decided to try and implement a simple State pattern to try and see how things fit together.
However, I've ran into an issue I've never come across before: The Scene's subclass (Start) doesn't seem to inherit the value of a pointer set by the superclass' constructor.
Here's ... | You have two members variables Scene::game and Start::game. You never set Start::game. By default, game resolves to Scene::game and the base class's variable is shadowed. Turn on compiler warnings, maybe the compiler will warn about it, not sure in this particular case.
Fix:
Game::Scene::Start::Start(Game *game): Scene... |
65,294,813 | 65,295,160 | Class template for 2 dimension array that might be used with sever data types in main() | I have to create a class template for 2 dimension array; every variable in the array would get a random value [65;90], I need to find the MAX value in the array. But in class template data type should be unspecified, so later I could use it with any - int/char etc in main().
I have tried several ways to initialize the ... | I think that this is what you want
#include <iostream>
#include <cstdlib>
using namespace std;
template <typename T>
class Array {
private:
T **ptr;
public:
Array(T arr[][12]);
void print();
};
template <typename T>
Array<T>::Array(T arr[][12]) {
ptr = new T *[7];
for(int i = 0; i ... |
65,294,898 | 65,295,029 | Change C++ display text with HTML txt file? | I want to be able to change C++ display text from an HTML txt file, is this possible to do?
| your issue is your using pack and grid. pack and grid do the same thing but grid lets you choose where to put it. you can only use one or the other in a canvas. also you had hello and goodbye in the same spot on grid(). heres your fixed code:
from tkinter import *
from tkinter import ttk
label = None
def change1():
... |
65,294,975 | 65,295,304 | unresolved external symbol WSASetSocketSecurity | I'm trying to add some security to a socket connection. I am linking with ws2_32.lib. This is a test program that illustrates the problem. Its a windows c++ console app, compiled for x64. It compiles properly but won't link.
What am I missing?
Thanks,
Gerry
#include <iostream>
#include <WinSock2.h>
#include <mstcpip.h>... | As written in the Requirements section of the documentation of the WSASetSocketSecurity function, you need to link with Fwpuclnt.lib.
|
65,295,727 | 65,296,056 | Call from C# to C++ fails to pass parameters correctly | I have a very basic call from C# to C++. The function call takes three parameters:
extern "C" int CLIENT_API example(const char, char * const, const unsigned int);
The C# code imports that function as:
[DllImport("my.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int example(in sbyte id, byte... | The in modifier makes the argument a read-only ref argument. It's not the same as the [In] attribute, which is a marshalling hint.
You're passing 0 and bufferSize, and C# is taking their addresses (the literal 0 by way of a temporary variable) and passing those.
You're getting varying values because the address is dif... |
65,295,895 | 65,296,073 | Implicit function-to-function-pointer conversion not working for std containers (e.g. vector) | I've recently learned that C++ can perform implicit function-to-function-pointer cast whenever it found necessary. For example, in my example below, my_func_1 and my_func_2 are equivalent. However, vector_1 and vector_2 are not, and in fact, vector_2 will give a compile error. Similar compile errors also happen for oth... | In this declaration:
vector<my_class()> vector_2;
the type used to instantiate the vector is myclass(), which is a function type. Specifically it's a function that takes no arguments, and returns a my_class.
A function type is not copy-assignable, as can be seen from this test:
static_assert(not std::is_copy_assignab... |
65,295,907 | 65,296,057 | Is the order of writes to separate members of a volatile struct guaranteed to be preserved? | Suppose I have a struct like this:
volatile struct { int foo; int bar; } data;
data.foo = 1;
data.bar = 2;
data.foo = 3;
data.bar = 4;
Are the assignments all guaranteed not to be reordered?
For example without volatile, the compiler would clearly be allowed to optimize it as two instructions in a different order like... | c
They will not be reordered.
C17 6.5.2.3(3) says:
A postfix expression followed by the . operator and an identifier designates a member of a structure
or union object. The value is that of the named member, 97) and is an lvalue if the first expression is
an lvalue. If the first expression has qualified type, the resu... |
65,296,122 | 65,296,894 | Using return statement in a for loop | I have a class TemperatureCalculator that computes which kind of day it was and which one was the hottest. It operates on a vector. The vector is filled by the user's input. Everything works fine except the function klimaTag().
I know why it doesn't work the way it should but I don't know how to fix it without using st... | First, how to fix it. I will try to keep as much of your code as possible so you can see the changes that matter the most.
In klimaTag:
std::string klimaTag(int index) {
float temperature = temperatures[index];
if (temperature >= 25 and temperature < 30) {
return "Sommertag";
}
else if (temperat... |
65,296,125 | 65,296,214 | How do I define multiple variables from cin and getline? | cout << "Please enter your date (mm_dd_yyyy" << endl;
getline(cin, month, day, year);
How do I define several variables (in this case 3) using cin? My homework assignment requests me to be able to get the variables if I type in something such as: "6 10 1973". Anyone know how to achieve this?
| It seems simple enough
int month, day, year;
cin >> month >> day >> year;
PS you don't define variables using cin. The variables were defined when you wrote int month, day, year;. cin >> assigns values to variables by reading from the standard input.
|
65,296,986 | 65,297,294 | Exiv2 won't persist XMP to an image. image->writeMetaData() writes no metadata. Where is my error? | when I try to add XMP metadata to a file using exiv2 as library it just won't stick. After executing my code the file was modified, but has not changed in size and contains no XMP metadata. The following code is my testcase.
string fileName = "test.png";
vector<string> keyWords;
keyWords.push_back("keyword 1");
keyWord... | If you use exiv2 libaries with vcpkg and need XMP support make sure to install it like this not forgetting the xmp in brackets...
vcpkg install exiv2[xmp]:x64-windows
|
65,297,508 | 65,298,955 | Inconsistent string encryption result between program and Shell | I've wrote the below code snippet that passes a string to openssl by echo'ing, using popen; however the result is different than if I manually pass the arguments in PowerShell. Any help is appreciated...
void encrypt_message(const char * message_in, char * encrypted_return)
{
char encryption_cmd[1024] = { '\0' };
... | echo 'this' does different things in cmd.exe vs. PowerShell:
In cmd.exe, the command output is verbatim string 'this' , including the single quotes and the trailing space, plus a trailing newline.
Unfortunately, cmd.exe's echo echoes any quoting as specified; generally cmd.exe does not understand single-quoting ('..... |
65,297,549 | 65,297,601 | C++ : Program crashes when using a set method | So basically I'm trying to fill my array with some data but apparently I'm doing a mistake .
The problem was when using the method setName() . Somehow the program crashes afterwards . What am I doing wrong here ?
This is my program :
using namespace std;
class CEvent
{
public:
CEvent() = default;
~CEvent(){};
... | The member Sched was never initialized to point to anything! The line Sched->Schedule[3][2] = new CEvent(); is also liable to segfault, you may have gotten lucky. Your fix might be:
CBooking() : Sched(new CBlock()) {}
for example.
|
65,297,576 | 65,315,564 | How to use MAXIMUM_ALLOWED properly? | I have created a small framework that provides a unified API to multiple file systems/APIs (namely Win32, Posix, NFS). Said API is somewhat similar to Posix -- to access a file you need to "open" it providing a hint for intended purpose (r, w or rw). Something like open_file("/abc/log.txt", access::rw).
Supporting Win3... | Edit: Here is another reason why reopening file is not a good idea.
There is no way to use MAXIMUM_ALLOWED reliably -- R/O files and volumes cause it to error. Poorly designed feature.
Another approach is to get minimum access and "expand" it as required (by re-opening file with new dwAccessRequired flag). This does no... |
65,297,760 | 65,297,840 | String initialisation containing zero --> compiler bug or intended behavior? | I try to define some hard coded utf sequences.
like
static std::string const cUTF_16_BE_BOM = "\xFE\xFFTest";
static std::string const cUTF_16_LE_BOM = "\xFF\xFETest";
static std::string const cUTF_8_BOM = "\xEF\xBB\xBFTest";
static std::string const cUTF_32_BE_BOM = "\x00\x00\xFE\xFFTest";
stat... | These will call the std::string constructor with a const char*: The length is already lost, and the equivalent of strlen (std::char_traits<char>::length) is called to get the size.
Normally, you would use std::string_literals::operator""s to not lose the '\0' characters, but that might not be feasible in the :: scope. ... |
65,297,871 | 65,297,982 | How do I set the owner (or parent) of a Dialog Box? | I have six windows that can all generate a dialog box. The dialog box needs to know which of the six windows generated it. I believe I should be able to call GetParent(hWnd), or GetWindow(hWnd, GW_OWNER) from within the dialog box, but both calls return the overall project window, instead of the third arg I passed into... |
both calls return the overall project window, instead of the third arg I passed into DialogBox
The owner of a dialog box must be an overlapped or pop-up window. If OP's six windows are child windows, then the hWnd passed to DialogBox will be used to locate an eligible ancestor to use as an owner, instead, presumably ... |
65,298,007 | 65,298,125 | Assign array field within struct | recently i started working on C++ code and i was trying to communicate with an external library which has a struct defined as follows
struct StudentsInformation {
int student_count[10];
double total_marks[10];
double section_marks_average;
double class_marks_average;
};
I was trying to create a object ... | This should compile fine, in either/both C and/or C++:
#include <stdio.h>
struct StudentsInformation {
int student_count[10];
double total_marks[10];
double section_marks_average;
double class_marks_average;
};
int main(int argc, char *argv[]) {
struct StudentsInformation si = {
{1, 2, 3, 4, 5, ... |
65,298,720 | 65,298,872 | How to enable or use auto vectorization along with auto parallelization in Microsoft Visual Studio 2017 or 2019? | I am trying to test out auto-vectorization on the for loop below. I am unable to get the auto vectorization to work. The code is shown below.
float dotproduct(float a[], float b[], int size) {
int x = 0.0;
for (int i = 0; i < size; i++) {
x = x + a[i] * b[i];
}
return x;
}
int main() {
cons... | There is no vectorization report because you compiled in Debug mode (/Od), in which case autovectorization is not applied because optimizations are disabled. So, switch to a Release build.
/O1 and /OS would cause a report with failure reason 1404.
/Ox and /O2 will attempt to autovectorize, but with /fp:precise (which y... |
65,298,810 | 65,298,947 | Empty braces magic in initializer lists | Consider the following minimal example:
#include <iostream>
struct X {
X() { std::cout << "Default-ctor" << std::endl; }
X(std::initializer_list<int> l) {
std::cout << "Ilist-ctor: " << l.size() << std::endl;
}
};
int main() {
X a{};
X b({}); // reads as construct from {}
X c{{}}; // reads a... | A nice trick to do to get information about what the compiler does, is to compile using all errors:
-Weverything. Let's see the output here (for d only):
9.cpp:16:6: warning: constructor call from initializer list is incompatible with C++98 ... |
65,299,429 | 65,299,551 | is there a way to use set with online comparator? | i want to make a RedBlackTree using set or multiset with a comparator lambda function,and that function using an array(globally for simplicity)
the array is changing while program is running
#include <iostream>
#include <set>
using namespace std;
int v[10];
auto x = [](pair<int, int> p1, pair<int, int> p2) { return p1.... |
the array is changing while program is running
You are not allowed to have a comparator function that changes its behavior like that.
In your example, set is constructed before v[2]=-100; assignment, and it happens to just maintain its order after you make the assignment, but this is not guaranteed behavior.
As an as... |
65,299,537 | 65,299,671 | Failing to link fcgi library with g++ in multipass | My code:
#include <fcgi_stdio.h>
int main() {
int count = 0;
while(FCGI_Accept() >= 0) {
printf("Content-type: text/html\r\n");
printf("\r\n");
printf("Hello world!<br>\r\n");
printf("Request number %d.", count++);
}
}
In a fresh instance of multipass, I installed gcc, g++ ... |
The order matters: libraries follow input files
Like it was mentioned in the comments, it was indeed the case. I didn't know that and I totally missed that it was in the right order in the dockerfile. It was a really simple thing indeed but thanks to S.M for his quick response in pointing out the silly mistake. Hope ... |
65,299,972 | 65,301,252 | How to use Unicode in C++ Setfill() | Update #2: Unicode cannot be used in a Setfill. Searching for alternatives now.
Thank you to everyone who helped!
Update: Thanks to jkb I realized I was using a pointer. However, now I am still stuck on how I would put unicode into a char in order to use in SetFill(). That is my new question.
Original Question:
I am a... | Unicode has various formats. UTF-8 is a format that encodes most typical English characters in a single byte. However, to encode many of the tens of thousands of Unicode characters requires more than a single byte.
However, the setfill() adapts to the stream it is used with. cout is not a wide character (UTF-16, 16 bit... |
65,299,975 | 65,300,205 | Using C++, trying to find the largest word in a vector using a for-loop and std::max | Using C++, I'm trying to put together a for loop that finds the largest word in a vector of strings. I know its possible to do this by comparing word lengths. So this is just wondering about some minutiae and learn a few things about C++, I can't figure out why this won't work:
#include <iostream>
#include <vector>
#... | std::max compares things with a normal comparison, which for string, compares their dictionary order, not their length. So all the results in your loop are as expected.
|
65,300,264 | 65,300,360 | Maintaining multiple class instances (objects) wihout destructor calls in c++ | I want to make many objects of type "Student" and store them so they can be used throughout the program. I'm also required to print out messages when a student is created and destroyed, but when i put the "destroyed" message in the destructor it'll appear whenever I change instance to create the next student cause the... | The destructor you see from the loop is not the array elements being destructed, but rather the temporary object that you create by Student("example", 1,1).
The statement
S[i]=Student("example", 1,1);
is essentially equal to
Student temporary_object("example", 1, 1);
S[i] = temporary_object;
If you want to create fiv... |
65,300,685 | 65,300,944 | Read raw as string then reinterpret as float[] | I'm trying to write and then read a file in a simple format: 3 lines for an ull (unsigned long long) and two float[].
I'm not sure why but I can't get the expected values.
vector<float> flowX{};
vector<float> flowY{};
void Save(string filename)
{
ofstream fileTarget(filename);
fileTarget << flowX.size() << end... | The correct way to write was to use fileTarget.write() (which add charaters) instead of fileTarget << e (which add bytes):
//for (const auto& e : flowX) fileTarget << e; // adding text
for (const auto& e : flowX)
fileTarget.write(reinterpret_cast<const char*>(&e), sizeof(float));
Checking with hd:
00000000 38 0a ... |
65,301,055 | 65,641,764 | Is there any way to detect error in windows batch file? (c++ code compilation) | I have written the run.bat file to compile as well as run my c++ code through the windows terminal.
The file contains only two commands:
g++ %1.cpp -o %1.exe
%1.exe
But I can't figure out how to stop the execution of the second command if the code has some compile-time errors. Is there any solution available? Pleas... | I have read many blogs and I came up with this solution.
g++ %1.cpp -o %1.exe
if %ERRORLEVEL% GEQ 1 exit/b
%1.exe
Thank you everyone for helping me :)
|
65,301,158 | 65,301,288 | std::enable_if to filter out the argument with the type of char* | Why char* pstr="hello"; pushArg(pstr); still invoke such template?
You see there is &&(!std::is_same<char, typename std::remove_cv_t<std::remove_pointer_t<T>>>::value) already.
template <typename T,
typename std::enable_if<(!std::is_same<lua_CFunction, T*>::value)
&& std::is_... | First, you have tagged your answer with C++11 but you use std::remove_cv_t from C++14.
In C++17, your function would look like this:
template <typename T,
std::enable_if_t<
std::is_pointer_v< T >
&& !std::is_same_v< std::string* , T >
&& !std::is_same_v< char , typ... |
65,301,287 | 65,312,541 | When binding constructor getting an error: missing 'typename' prior to dependent type name in C++ | How to bind a constructor in C++?
In one class, I have template class with constructor like as shown below:
namespace EMRProcess
{
template<typename T>
class CEMRImpl
{
CEMRImpl(EMRProcessSR::CWebHandler<T>* pHandler_,
CSocketRemover* pSocketRemover, const std::string& strID, cons... | What you are attempting to do with std:::bind()'ing a constructor will never work as-is, as it is illegal to take the address of a constructor. But a lambda can be used anywhere that std::bind() can be used (in fact, a lambda is almost always preferred over std::bind()), so have a lambda call the constructor normally a... |
65,301,436 | 65,301,485 | Is the definition of array dimension in c++ primer different from others? | In the Array chapter (p.113, 5th edition) of C++ Primer, it states:
An array declarator has the form a[d], where a is the name being defined and d is the dimension of the array. The dimension specifies the number of elements and must be greater than zero.
An later example from the chapter:
int a2[] = {0, 1, 2}; // ... | Dimension == Length in this case
|
65,301,559 | 65,699,550 | Getting server IP within wasm application | I use C++ and Qt 5.15.x. I've built WebAssembly version of my desktop application.
The application is loaded using URL like "http://192.168.21.55:5555" (intranet application). I'd like to extract server IP address within WebAssembly application. How can I achieve it?
| There is no solution for ip extraction,
but I've found the way to get host and port (host is equal to ip in my case).
#include <emscripten/val.h>
emscripten::val location = emscripten::val::global("location");
auto host = QString::fromStdString(location["host"].as<std::string>());
auto port = QString::fromStdString(loc... |
65,301,883 | 65,302,370 | what is the right way to call to constructor in c++? | Communicator communicator = Communicator();
Communicator communicator;
What is the difference between these 2 calls?
| The difference is in copy elision. Before C++17, in the line
Communicator communicator = Communicator();
a temporary Communicator object was created and then used to copy-construct communicator. A compiler could optimize this out but it had to check that that copy or move constructor can be invoked (public, not delete... |
65,301,944 | 65,313,267 | #include not finding files while the Visual Studio autocomplete suggestions can find the files | I am trying to include Glad (generated from here with the GL3.3 api (having similar include problem with GLFW as well)) as such
#include <glad/glad.h>
I feel like this should work since I have my additional include directories for the file in the project as
vendor\Glad\include
where my VS solution has the file struct... | Alright so I figured it out finally, I'm not happy with how I had to do it but I guess it works so I'll move on unless anyone has suggestions. So, the problem came down to that I was including the headers in a static lib I was making then used that static lib elsewhere. (I hadn't realized this was a problem otherwise I... |
65,302,441 | 65,302,490 | Will unsuccessful call alter by-reference passed result? | Not sure if this question is plain C++ or library specific.
I want to know, if functions, that return success code and output their result to a passed reference alter output reference in case of failure?
The library used is CGAL
using namespace PMP = CGAL::Polygon_mesh_processing;
Mesh out;
bool valid_union = PMP::core... | There's nothing special about returning a true or false value from a function; i.e. whether your function returns success or failure has no meaning whether it changed the arguments:
bool do_something(int& a, int& b) {
a += ++b;
return false;
}
still changes a and b, no matter whether you return false or return... |
65,302,807 | 65,304,565 | Private Vector in Header file: How to Get and Set values | I'm trying to declare a vector containing user objects in the header file, but I'm unsure of how to use the setter and getter functions to push values objects back to the vector or call them again.
class userbase
{
public:
userbase();
virtual ~userbase();
//FUNCTION DECLARATIONS
voi... | Getters/setters are quite often misunderstood. The aim of using such functions is encapsulation which means restricting access to your data or exposing certain functions.
The reason why we don't make private members public in the first place is because there are some operations that we don't want users of our class to ... |
65,302,889 | 65,302,920 | Segmentation fault when trying dynamically allocate 2d char array | I have written the next similar example when I get a segmentation fault error
{
const char** var = NULL;
const char* tmp = "Hello! How are you?";
var = (const char**)malloc(5 * sizeof(char*));
for (int i = 0; i < 5; i++)
{
var[i] = (char*)malloc(50* sizeof(char));
strcpy((char*)va... | This walks off the end of the array:
for (int i = 0; var[i]; i++)
Accessing var out of bounds is undefined behaviour, which can lead to a crash. You won't get a nice, neat value when you exceed the bounds like you might in JavaScript, Python or Ruby, you get problems. Unfortunately there's no checks for this, so you m... |
65,303,192 | 65,304,897 | "vector iterators incompatible." How can I pass it as a parameter to the function? | Why do I get the error "vector iterators incompatible" when I want to run the function "klimaTag()"? I want to give it the iterator of the vector temperatures. How can I do that? I only want to loop over the vector in the main function.
#include <iostream>
#include <vector>
class TemperatureCalculator {
private:
s... | You return copy of vector in get_temperature, and so use iterator of temporary vector in
std::vector<float>::iterator i = t.get_temperature().begin()
Solution is to return reference:
class TemperatureCalculator {
private:
std::vector<float> temperatures;
// ...
public:
const std::vector<float>& get_temperature... |
65,303,323 | 65,303,391 | How to explain "x = (a = 3, b = ++a)" in c++? | There are complete codes. And the output always is "4 4 4".
#include <iostream>
int main() {
int a = 1;
int b = 2;
int x = (a = 3, b = ++a);
std::cout << a << ' ' << b << ' ' << x << std::endl;
return 0;
}
| The expression (a = 3, b = ++a) is evaluated from left to right and the value is b = ++a which itself has the value b. That is assigned to x. In other words x will be the same as b.
Furthermore the expression separator operator , is a sequencing point, meaning that a = 3 completes prior to the evaluation of b = ++a.
+... |
65,303,602 | 65,305,833 | See whether it is possible to perform an operation like i am doing with functions and structures | #include<iostream>
using namespace std;
struct user
{
string name;
int age;
string address;
};
user fun(user u);
void show(user u); //is it possible to perform this
int main()
{
user u;
fun(u);
show(u);
}
user fun(user u)
{
char chr;
cout << "Enter name ";
cin >> u.name;
cout << "Enter age ";
... | You issue in not in show (even if you can pass argument by const reference instead of by value), but in fun which has several flows.
Should be:
void fill_user(user& u) // pass by reference
{
char chr;
cout << "Enter name ";
cin >> u.name;
cout << "Enter age ";
cin >> u.age;
cout << "Enter address ";
cin >... |
65,303,779 | 65,307,404 | Template substitution failure with empty parameter pack using a Y-combinator | I am trying to make a function that will read from a pipe to a buffer using boost::asio::posix::stream_descriptor. I use async_read_some rather than boost::asio::async_read because it is important for me to be immediately notified as soon as a chunk of data is read. What I want to do after reading data from the pipe is... | You have several issues:
First, there is a mismatch between return type/noexcept and function body:
miss Fn in the formers
template<typename Fn>
constexpr auto yCombinator(Fn&& fn_) noexcept {
return [capture = std::tuple{std::forward<Fn>(fn_)}](auto&&... args_) constexpr
noexcept(std::is_nothrow_invocable_... |
65,303,941 | 65,304,755 | Google test, Typed test, C++ | I am having trouble running a typed test for my struct.
So consider in my test.cpp I have a template struct
template<typename T>
struct Something {
T value;
// Constructors
};
Now I declare typedefs as mention in documentation.
using MyTypes =
testing::Types<char, unsigned char, short int, unsigned short... | You're not deriving Something from testing::Test.
It should look like this:
template<typename T>
class Something : public testing::Test {
public:
T value;
// ...
};
Then inside TYPED_TEST you don't need to create an instance of this class, you already have it:
TYPED_TEST(Something, Arithmetics) {
EXPECT_E... |
65,304,024 | 65,304,184 | std::search to find a rightmost subsequence | I am trying to find a rightmost subsequence in a range with std::search and std::make_reverse_iterator.
However the iterator returned always point to the start of a range. What am I doing wrong?
TEST(basic_test, find_from_right)
{
std::vector<uint8_t> array{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::array<uint8_t, 2> ... | I think this could solve your problem (if you are okay with C++17):
From https://en.cppreference.com/w/cpp/algorithm/find_end:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v{1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4};
std::vector<int>::iterator result;
std::vector<in... |
65,304,566 | 65,309,057 | Sort elements of secondary diagonal in ascending order C++ | As I think, I need to transform function printSecondaryDiagonal (that actually print elements of secondary diagonal) into one-dimensional array and then sort its elements in ascending order, right?
P.S. Two-dimensional array in the beginning must be necessarily a dynamic one. Also, cannot do it using vector. Only mallo... | The elements of the secondary diagonal can be extract with one for loop as I will show. The secondary diagonal will be save in an 1-d array `secDiag[i]`. Then, using `std::sort` in `algorithm` head file to sort this array in ascending order.
void printSecondaryDiagonal(int** arr, int rows, int columns) {
cout <... |
65,304,787 | 65,305,058 | Can't align properly using setw manipulator | I can't align the output of my program.
I want to keep the same names and get the right spacing.
The code is provided below.
I also tried using left but it still does not work.
The output I am expecting:
The output I am getting:
//taking name and votes recieved
for (i = 0; i < 5; i++)
{
cout << "E... | setw needs to be invoked before the field you wish to apply the fixed length to. That includes the names. If you want to keep the names left aligned you can use
std::cout << std::left << std::setw(20) << name /*<< [...]*/;
As a side note you should avoid using using namespace std;. The reason is that std contains a lo... |
65,304,938 | 65,305,412 | undefined reference to some OpenGL functions if they haven't been called in main | if I define a function, for example void draw(), containing glClear, glDrawArrays or glDrawElements (possibly the case for some other OpenGL functions as well) in a separate file to the main file, and then call draw() from the main function, there is an undefined reference error to the GL function that is used inside d... | This is because -ldraw is last in the libraries. Each library is added to the binary to sort out unresolved externals, and then offers new dependencies. Given -ldraw is last, it can't add new dependencies, which get resolved.
Move -ldraw to first of libraries.
g++ -o a.exe main.cpp -I./include -L./lib -ldraw -lglew32... |
65,305,000 | 65,305,151 | Why can we access private data members class using pointers, without using members friend function other members in the class? | As you know, private members can only be accessed by other members in the class
class DateClass // members are private by default
{
int m_month; // private, can only be accessed by other members
int m_day; // private, can only be accessed by other members
int m_year; // private, can only be accessed by othe... | Actually the behaviour of using the pointer obtained by the statement
int* ptr = (int*)&t;
is undefined. (Technically this is a strict aliasing violation).
C++ is littered with undefined constructs - which is one thing that makes the language fiendishly difficult to master. Given you're just setting out leaning C++ (... |
65,305,176 | 65,305,710 | C++ accept() of winsock2.h keeps giving 10038 error | I am facing an issue with the accept() function in the below code. It keeps giving me 10038 error. I read about the error 10038 (WSAENOTSOCK). But I can't find the exact issue here. Similar Linux code works fine as the server code.
PS: I am running this in Visual Studio on Windows.
#include "stdafx.h"
#include <winsock... | The error code WSAENOTSOCK seems fairly self-explanatory. You have...
int listenRes = listen(serverSocket, 10);
followed by...
int clientSock = accept(listenRes, ...
So you're passing the value returned by listen as the socket parameter to accept. Your accept call should be (untested)...
int clientSock = accept(ser... |
65,305,207 | 65,305,606 | Cast a vector and write it in a C++ stringstream | In the toy program below, I write and read a vector of doubles with a stringstream. However, how can I write v as a vector of (rounded) uint in ss, so that when w is read the output of the program is 3?
#include <sstream>
#include <vector>
#include <iostream>
int main() {
std::vector<double> v = {0.1, 1.2, 2.6};
... | This code reads the vector, rounds the values, and writes them out one at a time. The reverse when reading back from the stream.
#include <sstream>
#include <vector>
#include <iostream>
#include <cstdint>
#include <cmath>
int main() {
std::vector<double> v = {0.1, 1.2, 2.6};
std::vector<double> w;
std::str... |
65,305,230 | 65,328,567 | clang-format main include sorting with folders prefix | I am trying to get clang-format to recognize the main include for foo.cpp in the following setup:
project/my_lib
├── CMakeLists.txt
├── include
│ └── project
│ └── my_lib
│ └── foo.hpp
├── src
│ └── foo.cpp
└── tests
└── foo_test.cpp
And foo.cpp has the following content:
#include <project/anot... | Just as a quick update, which kind of solved my issue: if the include uses regular quotes (") then clang-format bundled with Visual Studio seems to pick up the "main" header and order it accordingly.
Not ideal, but still a working solution.
|
65,305,326 | 65,308,666 | C++ SFINAE double nested initializer_list vs. variadic template constructor | Problem
I am writing a small math library that has Vector and Matrix classes. I'd like to make it convenient to intialize objects of these classes with strict rules for how they can be initialized.
The Vector class constructor already works as i intended. It is restricted such that only the correct size N is accepted a... | To have you desired syntax, you might do:
template <typename ... Us,
std::enable_if_t<sizeof...(Us) == N && (std::is_same_v<Us, T> && ...), int> = 0>
Matrix(const Us (&... rows)[M]) {
// ...
}
|
65,305,779 | 65,308,208 | Concurrent program compiled with clang runs fine, but hangs with gcc | I wrote a class to share a limited number of resources (for instance network interfaces) between a larger number of threads. The resources are pooled and, if not in use, they are borrowed out to the requesting thread, which otherwise waits on a condition_variable.
Nothing really exotic: apart for the fancy scoped_lock ... | Locking destructor coupled with missed NRVO caused the issue (credits to Secundi for pointing this out in the comments).
If the compiler skips NRVO, the few lines below if will call the destructor of b. The destructor tries to acquire the mutex before this gets released by the unique_lock, resulting in a deadlock.
Borr... |
65,305,907 | 65,311,991 | Why are my textures not rendered in greater detail in my DirectX11 game? | I am trying to write a small 3D game in C++, using DirectX 11. This is absolutely the first time I have attempted to write a game using only a graphics API. I have been following the tutorials on the website Rastertek.com up to Tutorial 9 for ambient lighting.
After implementing movement and collisions for the player, ... | You need to generate mip maps for the texture you load. Check the DDSTextureLoader.h/cpp and WICTextureLoader.h/cpp here.
For example, to load the .dds image with mip maps, you would use:
HRESULT DirectX::CreateDDSTextureFromFileEx( ID3D11Device* d3dDevice,
ID3D11DeviceContext* ... |
65,305,980 | 65,306,021 | How can i correctly create a vector of arrays? | I'm new to c++ and i'm trying to create a std::vector of arrays, but whenever i push_back a new element it seems that all of the previous elements get overwritten with the new value i just added.
(I need to use the c++ default arrays rather than std::array or other containers because i need to pass them to a function t... | On each iteration of the loop, you're not pushing back the array, rather you are pushing back a pointer to an array with automatic storage duration which then goes out of scope. (Conceptually a new array is created on each iteration although in practice a compiler will optimise that out.)
So you end up with a std::vect... |
65,306,167 | 65,306,381 | Why does an unsigned int of bit-field become a signed int after shift operation in C++? | The test code:
struct A
{
uint32_t lo : 16;
uint32_t hi : 16;
};
int main()
{
A a{};
a.lo = 0xFFFF;
auto b = a.lo << 16;
cout << b << endl;
return 0;
}
The output is:-65536, and the type of b is int but not uint32_t.
I have found that, uint16_t and uint8_t will also become signed int after... | It's part of the standard integral promotion.
[expr.shift]
1 The shift operators << and >> group left-to-right
The operands shall be of integral or unscoped enumeration type and
integral promotions are performed. The type of the result is that of
the promoted left operand.
[conv.prom]
5 A prvalue for an integral bit-f... |
65,306,362 | 65,307,418 | What are legal addresses for binding a QUdpSocket? | I tried to bind my socket to some random address 10.1.1.1:12001, and got QAbstractSocket::SocketAddressNotAvailableError.
Than i wrote a simple code:
for (int i = 0; i < 256; i++) {
QHostAddress address0(QString::number(i) + ".0.0.1");
quint16 port = 12101;
QUdpSocket* m_socket = new QUdpSocket();
if (m... | You are not allowed to bind the socket to an arbitrary network IP address. You can only do it with an IP address of one of your network devices or some special IP addresses like 0.0.0.0. By default you always have the 127.0.0.1 but surely you have another network address in your computer.
By the other way if you want t... |
65,306,387 | 65,306,505 | C++ auto deducing not working in class constructor | I have two classes:
class string_keys_management {
public:
string_keys_management(const string_keys_management&) = default;
string_keys_management(string_keys_management&&) = default;
string_keys_management& operator=(const string_keys_management&) = default;
string_keys_management& operator=(string_key... | You are missing one more pair of brackets:
multimap<std::string> mp = {{
{ { { "key1", "key2", "key3" }, "description1" }, "value" },
{ { { "key4", "key5", "key6" }, "description1" }, "value2" }
}};
|
65,306,562 | 65,307,841 | Should template types parameterized by local static variables from the same template function compare equal? | Consider the following program (godbolt):
template <typename, typename>
struct is_same { static constexpr bool value = false; };
template <typename T>
struct is_same<T, T> { static constexpr bool value = true; };
template <typename T, typename U>
static constexpr bool is_same_v = is_same<T, U>::value;
using uintptr_... | I believe the behavior of clang/gcc is in violation of the standard (possibly an improper as-if optimization?), per [intro.object] (emphasis mine)
Unless an object is a bit-field or a subobject of zero size, the address of that object is the address of the first
byte it occupies. Two objects with overlapping lifetimes... |
65,307,231 | 65,307,927 | Template specialization for container type | I would like to have separate specializations for a function when the type is a container vs. non-container types. For example:
template <typename T>
void print(const T& t) {
cout << "non-container: " << t;
}
template <>
void print(const ContainerType& container) {
cout << "container: ";
for (const auto& t : con... | A quick version might be
struct low_priority_tag {};
struct high_priority_tag : low_priority_tag {};
template <typename T>
std::false_type is_container_impl(const T& t, low_priority_tag);
template <typename T>
auto is_container_impl(const T& container, high_priority_tag)
-> decltype(std::begin(container), std::end(co... |
65,307,248 | 65,307,290 | Is it legal to call resize(0) on an empty std::vector? | I have the following code:
std::vector<int> v; // v has no elements
int size = getSomeNumber(); // this function may return any number that is >= 0
v.resize(size);
As you can see, getSomeNumber may return any positivie number or 0.
Instead of checking if size > 0 before calling resize, I would rather simply call it im... | Indeed it is legal to call resize(0) on an empty std::vector.
Although std::vector::clear does the same thing, and is clearer.
Note that you can regard the behaviour of v.resize(v.size()) to be a no operation. The C++ standard states that the complexity has to be linear (n.b. not necessarily proportional) in the differ... |
65,307,825 | 65,318,758 | Error 8007017c using CfCreatePlaceholders after Windows update KB4592449 | I'm using the Cloud Mirror sample and I could create placeholders correctly before the Windows Update KB4592449. But after this update I can't create placeholders for the second or higher folder level in the base directory path, using the CfCreatePlaceholders function as is used in the sample, the error code 8007017c i... | I can reproduce this issue on OS Build 19042.685.
The following is an example workaround (temporarily) you can refer to:
Change these code lines of CloudMirror:
std::wstring relativeName(sourceSubDir);
relativeName.append(findData.cFileName);
To
std::wstring relativeName(findData.cFileName); // relativeNa... |
65,307,986 | 65,308,096 | What does sbrk(0) point to when initializing static variables? | In the sbrk(2) manual,
it states that
Calling sbrk() with an increment of 0 can be used to find the
current location of the program break.
How does this work when sbrk(0) is used to initialize a static variable?
Say,
static void* current_heap = sbrk(0);
This curiosity stems from the typical compilation steps of C/C+... | In C, this code is not valid:
static void* current_heap = sbrk(0);
Because an initializer for an object with static storage duration must be a compile time constant, which this is not. So this code will fail to compile in C.
For C++, the function will be called when the program runs at some point before main is calle... |
65,307,990 | 65,309,452 | Some bugs in singleton mode written in C++ | #ifndef CONFIG_CPP
#define CONFIG_CPP
#include <mutex>
using namespace std;
class Config {
public:
static Config* GetDefult(){
if (p_instance == nullptr){
mutex_.lock();
if (p_instance == nullptr){
p_instance = new Config();
}
mutex_.unlock();
}
return p_instance;
}
pri... | Static data members have to be initialized outside the class declaration in a source file. They have a global scope and generally it is not a good idea to mix multi-threaded code with static.
class Config {
...
};
Config* Config::p_instance = nullptr;
|
65,308,007 | 65,308,178 | Why is std::is_move_constructible<S>::value == false despite S move-constructing just fine? What is the correct behavior? | This following code move-constructs S via const &&.
Yet it returns 0, indicating S is not move-constructible!
What is the correct behavior of each of the 2 marked constructions in main according to the standard?
If returning 0 is the correct behavior, what is the rationale behind it?
(Why shouldn't it reflect whether... | Though the standard deems S(const S&&) to be "a move constructor" and you may think that would be the end of it, is_move_constructible actually requires that your declaration of s3 is valid in C++14 and earlier; i.e. that a move constructor will be chosen for that declaration.
From cppref:
If T is not a referenceable ... |
65,308,058 | 65,310,021 | If template parameter AA is a templatized class A<T> itself, is it possible to get the template parameter (T) of this templatized class? | Consider the code below:
template <typename T>
class A{
...
}
template <class U>
class B{
...
}
int main {
B<A<int>> a;
...
}
How can I get the template parameter of A (int in this case) inside B, if A<int> is the template parameter for B?
I could parametrize B as follows, but I feel like I am sending an unnecessary... | There are several ways, depending of that you might change:
Quick way, specialize B
template <class> class B;
template <class T>
class B<A<T>>
{
// Use directly T
//...
};
Add info in A directly (as std containers do with value_type)
template <typename T>
struct A
{
using my_type = T;
};
// Then in `B<... |
65,308,131 | 65,308,281 | How to change a pixel in a JPEG | So I have a photo named blank.jpg that contains only black pixels and I want to modify some specific pixel (let's say the pixel with the coordinate (x,y)), from black to white. To be more specific, I have a list of pixels and I want to modify those pixels from black to white, creating an image, and exporting it to imag... | You can use boost::gil (Generic Image Library)
https://www.boost.org/doc/libs/1_39_0/libs/gil/doc/html/g_i_l_0164.html
You can also select one of the alternative libraries in this link :
https://cpp.libhunt.com/boost-gil-alternatives
|
65,308,173 | 65,308,643 | How to compare the type in a constexpr? | Is there a way that I could make a better comparison for the first and last if? For instance, if I wanted a different behavior for float and double. Is there a way to compare using the actual type (not its size in memory) inside constexpr? Here is the code I have:
void print(T val)
{
if constexpr (sizeof(T) == 1) {... | Yes!
You're looking for std::is_same_v:
void print(T val)
{
if constexpr (std::is_same_v<T, char>) {
printf("%c", val);
}
else if constexpr (std::is_integral_v<T>) {
printf("%d", val);
}
else if constexpr (std::is_same_v<T, float>) {
printf("%f", val);
}
printf("\n");... |
65,308,501 | 65,309,015 | Cannot open source file mscorlib.tlh | I am trying to import "mscorlib.tlb" inside my C++ project, but I keep getting this error:
cannot open source file "C:/Users/MyUsername/source/repos/DLL_Loader/.net compatibility/mscorlib.tlh
I am trying to import it this way:
#import "mscorlib.tlb"
just like MSDN suggests to do (https://learn.microsoft.com/it-it/dot... | Since C:/ is already the highest position in a Windows file system, C:/../ does most likely not go where you want to be.
It seems your include path is messed up and maybe you have to remove the C: to make it a relative path.
|
65,308,734 | 65,309,552 | conflict data type quint16_be from QtEndian with stdint.h | I want to use qint16_be, quint16_be, quint32_be etc. as a data type for big endian
what I am trying is something like this
#include <QtEndian>
typedef quint16_be uint16_t;
And I am getting error
C:/Qt/5.15.2/mingw81_64/include/QtCore/qendian.h:429:28: error: conflicting declaration 'typedef QBEInteger<short int> qint1... | Here we go: an MCVE for qToBigEndian():
#include <QtCore>
int main()
{
const uint16_t sample = 0x0201;
QByteArray data((const char*)&sample, sizeof sample);
qDebug() << data;
const uint16_t sampleBE = qToBigEndian(sample);
QByteArray dataBE((const char*)&sampleBE, sizeof sampleBE);
qDebug() << dataBE;
}
O... |
65,308,814 | 65,308,882 | std::move in function parameter will not use again? | I know if you use std::move(s), then the s can not use again, But I have some questions.
If I don't do move constructor/assignment operator, Does the variable still exist?
// not do assignment
void test2(string &&t) {
return;
}
void test1(string &&s) {
test2(std::move(s));
}
int main()
{
string s("123");
... |
I know if you use std::move(s), then the s can not use again
That's not really true.
After an object of a standard library type has been moved-from, unless otherwise stated its state is "valid but unspecified", so indeed it's best not to use it again unless you know you've put it back into a useful state (e.g. .clear... |
65,309,052 | 65,359,284 | Should I trust profiling inside or outside of callgrind for a function that calls glibc's sin()? | I'm working on an audio library in which the sine of a number needs to be calculated within a very tight loop. Various levels of inaccuracy in the results might be tolerable for the user depending on their goals and environment, so I'm providing the ability to pick between a few sine approximations with differing accur... | When you run a program under Callgrind or any other tool of the Valgrind family, it is disassembled on the fly. The intermediate representation is then instrumented, and translated back to the native instruction set.
The profiling figures that Callgrind and Cachegrind give you are figures for the simplified processors ... |
65,309,208 | 65,309,792 | How to access a private variable in a class without using allocation? | I'm trying to better understand the memory allocation / pointers etc..
As you can see on "test" Method , I tried to access the Name of CTest class so that I can fill it in my Schedule array . Is there a possiblity to access the CTest class without allocation ( CTest * Test = new CTest(); ) . I mean is it possible to us... | If you want to give CEvent an existing CTest object then pass it as a reference in the constructor:
class CEvent
{
public:
CEvent(CTest &test): test(test) {}
void setTestName(std::string str){test.setName(str);}
std::string getTestName(){return test.getName();}
private:
CTest &test;
};
...
CTest test... |
65,309,212 | 65,309,684 | How to convert percentage to z-score of normal distribution in C/C++? | The goal is to say: "These values lie within a band of 95 % of values around the mean in a normal distribution."
Now, I am trying to convert percentage to z-score, so then I can get the precise range of values. Something like <lower bound , upper bound> would be enough.
So I need something like
double z_score(double pe... | I say you were "close enough".
#include <iostream>
#include <boost/math/special_functions/erf.hpp>
#include <cmath>
double z_score(double percentage) {
return sqrt(2) * boost::math::erf_inv(percentage / 100);
}
int main() {
#define _(x) std::cout << x << " " << z_score(x) << "\n"
_(68.27);
_(95.45);
... |
65,309,585 | 65,309,675 | Finding certain characters in a line of string | I want to be able to a string that contains certain characters in a file that contains one string per line.
#include <iostream>
#include <fstream>
#include <string>
int main(){
string line;
ifstream infile;
infile.open("words.txt");
while(getline(infile, line,' ')){
if(line.find('z')){
cout << line;... | Problem:
In your file the strings aren't separated by a space (' ') which is the end delimiter, they are separated by a end of line ('\n'), that is a different character. As a consequence, in the first getline everything goes to line. line contains all the text in the file, including z's, so all the content is printed.... |
65,309,676 | 65,309,849 | What is the best data structure to store 1 key and 2 values in C++? | I want to store data that looks like this:
NAME SURNAME BIRTHDATE
e.g.:
{{"Anna", "Smith", "16/06/1965"}
{"Bob", "Smith", "26/07/1982"}}
I think I can make a struct myself like this:
struct PEOPLE {
string name;
string surname;
string birthdate;
};
But is there any data structure I can use for this purpo... | You could try using map or multimap, with name as key and a struct (with surname, birthdate, and whatever else you want in it) as value, but note that however you do it, in your application you will probably want the key to be unique for every entry, and name will possibly not be.
|
65,309,782 | 65,309,908 | is_floating_point specialization for user defined type | Can I define is_floating_point for user defined class? I tried this. But is_floating_point returns false.
class Test
{
public:
Test() { x = 0; }
private:
float x;
};
template<>
struct is_floating_point<Test>
{
static constexpr bool value = true;
};
void main()
{
std::cout<<std::is_floating_point<Test>:... | No. std::is_floating_point<T> is defined to return true when "T is a floating point type", and the standard then states that "There are three floating-point types: float, double, and long double.
Doesn't leave any wiggle room.
|
65,310,179 | 65,310,259 | initialize double nested std::array from variadic template array reference constructor | Problem
I have a Matrix class that is able to do some math. It holds its data in a double nested std::array as a variable. I have a constructor that takes an array reference as a variadic template. I did this so i could add some SFINAE more easily (omitted here).
#include <array>
template <std::size_t N, std::size_t M... | With the not shown constraint than sizeof..(TArgs) == N and types are T, you might store address of rows in array pointer and then work normally
template <typename... TArgs>
Matrix(TArgs const(&&... rows)[M]) {
using Arr = const T (*)[M];
const Arr args[N] = {&rows...}; // or const T (*args[N])[M] = {&rows...};... |
65,311,502 | 65,311,550 | How to initialize vector of a vector with custom values? | vector < vector <int> > g;
g.resize(n + 1);
I want to initialize n + 1 value all with -1. I know how to do it for a single vector but how it happens in this one.
| You can nest initializations:
std::vector<std::vector<int>> g(n, std::vector<int>(m, -1));
This will declare g as a vector with n elements, where each element is a vector with m elements, where each element in those sub-vectors is -1.
|
65,311,650 | 65,312,398 | lvalue and rvalue getter, is it possible to remove them? | Let's say we have this simple class
struct MyClass {
const std::string &getString() const & {
return m_string;
}
std::string getString() && {
return std::move(m_string);
}
private:
std::string m_string;
};
As we can see, the m_string acts as a non mutable variable in the sense t... | You can implement this behavior using a template wrapper type. It seems you want a type that works well with copy and move construction and assignment, but which only provides const access to the wrapped object. All you should need is a wrapper with a forwarding constructor, an implicit conversion operator and derefere... |
65,312,029 | 65,313,821 | C++ stdlib map::at function not working like I expect for struct key | I'm programming an assignment for my algorithms class. I have a struct
struct Node
{
int firstPosition;
int secondPosition;
string firstColor;
string secondColor;
bool operator<(const Node& n) const {
return (firstPosition < n.secondPosition);
}
bool operator==(const Node& n) const... | The problem was not the way the map.at() function works, it was that my less than operator in my struct was declared incorrectly. It compared different values from two Nodes instead of the same value.
This website helped me realize.
https://www.techiedelight.com/use-custom-objects-keys-std-map-cpp/
|
65,312,246 | 65,312,764 | C++ - How to delete a max element from queue | As you can see from the title I want to remove a element from a queue which is implemented using arrays.
So for example if I have:
array[]={1,5,4,3,2}
I want it to look like this
array[]={1,4,3,2}
I need to delete it from a queue but above is just a simple version of what I am trying to do. Here is the rest of the co... | If you want to use queue.
First you have to create a temp variable which will store all your element data.
for(int i = 0; i < capacity; i++) {
if(max < elements[i]) {
max = elements[i];
}
temp[i] = elements[i];
}
Then you have to create a bool isTrue variable becuase after you find the max element you have t... |
65,312,489 | 65,312,939 | Access Violation in calling glGenBuffers() | I'm trying to develop a game engine and was adding a batched rendering feature. I have 2 problems here,
Have some unusual access violation errors.
I initialized the Buffer classes as a member variable of the Renderer class
Scope<VertexBuffer> vertex = CreateScope<OpenGLVertexBuffer>(ME_MAX_VERTEX_BUFFER_SIZE, GL_DYNAM... | template<typename T>
using Ref = std::shared_ptr<T>;
template<typename T>
using Scope = std::shared_ptr<T>;
template<typename T, typename... Args>
Ref<T> CreateRef(Args&& ... args) { return std::make_shared<T>(std::forward<Args (args)...); }
template<typename T, typename ... Args>
Scope<T> CreateScope(Args&& ...args... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.