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 |
|---|---|---|---|---|
62,093,655 | 62,095,945 | Retrieving address of "inner" classes of a class | I have a virtual base class called ValuationFunction which basically just contains parameters and can output a value based on some calculation. All of the derived classes behave mostly the same way apart from one, which is called FunctionCombiner and looks like this:
class FunctionCombiner : public valuationFunction
{
... | If I understand you correctly, you want to compare shared pointers to see if they contain the same stored pointer? Then it's trivial: just use the == operator.
Internally operator== for std::shared_ptr is implemented as:
lhs.get() == rhs.get()
i.e. it checks the stored pointers are the same.
Demo
What you could do is... |
62,093,709 | 62,093,793 | class to class type conversion through constructor method output is 5500 why not 5555 | Output is 5500, but why not 5555?
class product {
public:
int b;
};
class item {
public:
int a;
item(product& obj)
{
cout << a;
}
item() {}
void display()
{
cout << a;
}
};
int main()
{
item obj1;
product obj2;
obj1.a = 5;
cout << obj1.a;
obj1.di... | The program has undefined behavior because the used data member a is not initialized.
This conversion constructor
item(product &obj)
{
cout<<a;
}
that is used in this assignment statement
obj1=obj2;
to convert the object obj2 of the type product to an object of the type item does no... |
62,093,765 | 62,100,755 | OpenCV copying subsection of an image | What I'm trying to do
I'm trying to paste a subsection of one image onto another for part of a project I'm working on. When I tried to view what I had so far, I saw that calling imshow() on both images to check doesn't actually show that both of them have the same BRG values at the points that they should.
What's wron... | It should be cv::Vec3b instead of uchar for a color image.
Instead of looping over pixels, you can use optimised built-in functions.
cv::Mat secondIMG(firstIMG.rows, firstIMG.cols, firstIMG.type());
cv::Rect rect(0, 0, secondIMG.cols, secondIMG.rows); // x, y, width, height
firstIMG(rect).copyTo(secondIMG);
// or
cv:... |
62,094,224 | 62,123,762 | SFML - Projectile slow down with different direction | I am creating a Tower Defense game, I created a program which create a projectile starting from a turret and sends it on the enemy as soon as he is in its range of shooting. The projectile moves in the direction of the enemy but on certain directions the projectile is more or less rapid.
Here is the code :
//initialPos... | I found the solution, here is the code :
direction = enemyPosition - initialPosition;
ndir = direction / sqrt(pow(direction.x, 2) + pow(direction.y, 2));
velocity = ndir * speed;
pform.move(velocity);
|
62,094,725 | 62,094,776 | Variable suddenly changes for no apparent reason when function is called | The variable indexMax changes to 3 regardless of the original value of indexMax, for no apparent reason when the function fibonacciGenerator is called.
And when I try to get the size of the array it outputs 2.
int fibonacciGeneator(int arr[], int n_1, int n_2, int counter, int index){
int x = counter;
x--;
... | int numArr[] = {1,1}; creates an array of two integers (it's type is literally int[2]) and it is absolutely impossible to resize it. Writing to index [2] is writing past the end of the array, which is illegal and undefined behavior. Anything can happen. It might overwrite variables, it might work, it might crash, it mi... |
62,094,857 | 62,095,135 | Concept for a function returning a templated entity | I've been experimenting with adding concepts to a constexpr json parser and am struggling to define the proper Parser concept. My first attempt:
using parse_input_t = std::string_view;
template <typename T>
using parse_result_t = std::optional<std::pair<T, std::string_view>>;
// A parser for type `T` is a function: pa... | Sure, you can do this.
Define a type trait to pull out the T from std::optional<std::pair<T, std::string_view>>:
template <typename T>
struct parser_type;
template <typename T>
struct parser_type<std::optional<std::pair<T, std::string_view>>> {
using type = T;
};
template <typename T>
using parser_type_t = typenam... |
62,094,880 | 62,095,088 | Calling parent move assignment operator when source object still needs to be used after | TLDR - Feel free to mark this as a duplicate if it is so; I will delete the question. However, I couldn't find anything after looking around for a bit.
Consider the following classes:
class Base
{
public:
Base(std::string var1);
Base& operator=(Base&& other) noexcept
{
if (this != &other)
... | Yes, this is safe.
First, note that the rule about not using a moved-from object is a default guideline for designing and using objects. It is not a rule of the language itself. It's the common practice for what class objects generally guarantee after they've been moved-from, including Standard Library class types that... |
62,095,110 | 62,095,216 | C++: Stroustrup iterator_traits example not compiling? | I'm trying to compile the code from Stroustrups C++ 4th Ed Page 124 and 125, section Iterator Traits. Unfortunately, the compilation results in numerous errors which look like they are in the template system. Does anyone know whats wrong with this code?
Thanks
#include <iostream>
#include <iterator>
#include <algorit... | You need to instantiate a vector<int>, but doing
std::vector<decltype(*beg)>
gives a std::vector<int&>.
Instead you should use the value_type of the iterator:
std::vector<typename For::value_type> v {beg, end};
Here's a demo.
|
62,095,373 | 62,434,953 | SFML texture not loading propely | I got class a with access to all standard SFML stuff:
class A{
public:
A(int type, Vector2f pos){
if(type == 1) tex.loadFromFile(path1);
else if(type == 2) tex.loadFromFile(path2);
//etc. etc.
shape.setTexture(&tex);
//then I set up the radius, and the position (from the constructor)
//I debugged this part and it see... | By calling shape.setTexture(&tex), a pointer to your Texture object is stored in shape.
The problem is that you are using std::vector to manage your A objects.
A std::vector manages an array on the heap. But this array is not dynamic, it cannot change its size. So, in order to increase its size, a vector allocates a co... |
62,095,402 | 62,095,461 | zlib inflation corrupts when using small buffers | I need to inflate big strings with zlib (around 500 KiB) and i noticed that when using a small buffer the output is corrupted (random letters get converted into giberish) but when switching to a large buffer the output is not corrupted.
This is my code:
std::string str;
std::lock_guard<s... | If inflate() writes all 1024 bytes to the char array, then the char array won't have any NUL-terminator byte, so when you do your str.append(buffer), what gets added to your inflated string will be the 1024 chars in the array, plus whatever garbage bytes happen to be on the stack after the array, until the first NUL by... |
62,096,299 | 62,096,367 | How do I write the body of a function in a dll, but have the prototype in my main program | Sorry if the question is rudimentory, I'm new to .dll-s. Basically I want to allow my function to have access to the same global variables it does in the main program it's originally defined in while actually being written in the .dll
example: I have a ListView object into which I am printing messages from within the f... | You are going about this all wrong. A DLL can't access variables that are outside of it, like in the main EXE, unless outside code gives the DLL pointers/references to them. Which won't help you anyway in the example you provided.
A better design is to not have the DLL access the variables directly at all. In your e... |
62,096,336 | 62,104,005 | Error code = 0x80070002 (MS Visual Studio) C++ for searching triplet data from one key element | enter image description here
How finding a map triplet pair with one element for example
(4,(?,?))
so i know that int 4 -> how can i find it because i get so much error and four hours of searching for possible solution to filter the coordinates with that key.
int k = *min_element(min1.begin(), min1.end());
auto it ... | int s = myninja.size();
int j = min1.size();
for (int i = 0; i < s; i++)
{
min1.push_back(myninja[i].first);
}
int mic = min1[0];
for (int i = 0; i <j; i++)
{
if (min1[i] < mic)
mic = min1[i];
}
cout << mic;
for (int i = 0; i < s;... |
62,096,444 | 62,096,546 | How implement SFINAE limited to few types, using template parameter pack | I need enable std::string and int, but using a parameter pack.
template <typename... ParamType, typename = typename std::enable_if<std::is_same<ParamType..., std::string>::value || std::is_same<ParamType..., int>::value>::type>
static inline void Log(const ParamType & ... args)
{
}
but i have errors when call
Log("he... | This solution uses a few C++17-ism (std::void_t). There are various implementations of them for earlier C++ standards floating everywhere, if needed:
template <typename ... ParamType,
typename = std::void_t<std::enable_if_t
<std::is_same_v<ParamType, std::string> ||
std::is_same... |
62,096,513 | 62,097,166 | Iterate matrix of vectors using c++ with auto range and structured binding? | I want to do something like this:
vector<vector<int>>& matrix; -> [[1, 1], [2, 2]]
for (auto [a, b] : matrix) {
...
}
This won't compile for me. Is this the correct way to do this? If not why?
| The above approach is only valid for iterating over the map in C++. If d is unordered map then it can be iterated through the below code
for(auto& [a,b] : d)
{
count<< "First" << a.first << "Second" << a.second <<endl;
}
To iterate over the vector> matrix as in this case the below code can be used,
vector<vector<i... |
62,096,519 | 62,096,715 | Does std thread constructor take variadic thread function? | I am trying to pass a variable count of callback functions (all of the same signature) to a thread function. I came up with the following code
using namespace std;
void callback(int i)
{
cout<<"thread "<<i<<" running"<<endl;
}
template<typename ...CallbackType>
void threadProc(int id, CallbackType ...callbackPack... | There is nothing wrong with your code. This seems to just be a bug in GCC, which has nothing to do with threads. A minimal test case that reproduces the bug is:
template <typename... T>
void foo(T...) {}
int main()
{
auto* pfoo = foo<void(int)>;
return 0;
}
It seems that GCC does not like the fact that foo h... |
62,096,669 | 62,096,992 | what is the scope of this variable in c++? | If i define a function like this
std::string& returnstring(std::istringstream &ist)
{
std::string temp;
std::getline(ist,temp);
return temp;
}
and if i use this temp which is passed by reference to another function like this
void displaystring(std::string &temp)
{
std::cout<<temp;
}
would the string t... | Nope since the temp variable is local to the returnstring function and once the code is out of the retuernstring function the temp variable is no longer valid.
If at all you want to send the reference and get the answer then better option is to send the argument by reference as below,
void copyLineAsString(std::istrin... |
62,096,930 | 62,107,080 | Keeping track of the shortest path between two nodes using Dijkstra's algorithm | I am quite new to c++ and have been having trouble modifying Dijkstra's algorithm to keep track of the shortest path between two nodes, not just the shortest distance. I have it computing the shortest distance correctly. This is the function that calculates the shortest distance:
vector<vertex<T>> shortest_path(di... | You could make use of parent array to reconstruct the path starting from target node to source node, for example:
vector<int> path;
int idx = v_id;
while (idx != u_id) {
path.emplace_back(idx);
idx = parent[idx];
}
path.emplace_back(idx);
reverse(path.begin, path.end());
cout << "PATH: ";
for (int x : path) {
... |
62,096,997 | 62,097,077 | c++ error: "array must be initialized with a brace-enclosed initializer" | i need your help with this.
my function is: (the way it works is true)
#include <iostream>
using namespace std;
#define V 4
#define INF 999
int floydWarshall(int graph[][V]){
int dist[V][V], i, j, k;
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
... | You can't use C arrays like other variables or objects in many cases. You can't pass a C array by value to a function or return a C array from a function. It will decay to a pointer to the first element. Therefore std::array was introduced in C++. It does exactly what you expected from C arrays in your code:
#include <... |
62,097,216 | 62,097,544 | Splitting std::vector of size m into vector of vectors of size n | Given a vector [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
what are some possible approaches to construct [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17]], focusing primarily on readability?
At the moment, I have correctly defined the starting and ending indexes of all the subarrays,... | If you're just after some code that can split a vector into a vector of up-to-five-element vectors, this should do it. It's bigger than necessary only because of the test harness around it.
The "meat" of the code is the templated function makeVecOfVecs(), and the single-line call to it. It's quite handy to do this sort... |
62,097,271 | 62,099,229 | CStdioFile cannot work with files larger than 2GB? | I am using Visual C++ 2008. In VC++ 2008, CFile supports 2^64 huge files. So I think CStdioFile should also support.
However, when using CStdioFile::GetLength() on a file larger than 2GB, I get a CFileException, below is the code snippet:
void CTestCStdioFileDlg::OnBnClickedButton1()
{
// TODO: Add your control not... | CStdioFile exists primarily for a single reason: It's constructor taking a FILE* argument. The purpose of this class is to wrap a C Runtime file and expose it through a CFile-compatible interface. The implementation inherits all of the C Runtime limitations, in particular the file size limit of 2GB.
To address this, th... |
62,097,507 | 62,097,686 | How to get arbitrary alignment of array in VS2019? | This code does not give the correct alignment:
alignas(4096) int* p = new int[1024];
printf(“%x”, p);
This should print
0x......000
with three zeros at the end. I can’t get it to work. Is this even possible?
| Your current code is aligning the pointer int* to be aligned to a 4096 byte boundary. What you want to do is align the memory allocated by new to be aligned to the boundary.
The only standard way to do this is with C++17 or above, using either operator new with the std::aligned_val_t argument, or std::aligned_alloc. E.... |
62,097,536 | 62,097,747 | C++: regex matching code, printing multiple matches? | I'm using the following code which is similar to Stroustrup's C++ 4th Edition Page 127&128. Per output log below, it prints the first match, however not the match for the trailing -XXXX digits.
Does anyone know why the trailing digits are not matched and/or printed??
Thanks
#include <iostream>
#include <regex>
using n... | − is not -. That are two different symbols. You have − in the code and - in the input. Here I fixed the code:
#include <iostream>
#include <regex>
using namespace std;
int main(int argc, char *argv[])
{
// ZIP code pattern: XXddddd-dddd and variants
regex pat (R"(\w{2}\s*\d{5}(-\d{4})?)");
int lineno = 0;
... |
62,097,574 | 62,097,600 | How do you save links with g++/C++? | I am writing some OpenGL code, and my links to libraries in /usr/lib is getting quite unwieldly:
g++ Application.cpp -lglfw -lGL -lGLEW
I don't want to hunt around/can't remember the exact names of the libraries EVERY TIME i want to complile something, so in my project folder I have a file called linkingsNeeded.txt. T... | Learn to use some build automation tool such as GNU make or ninja.
You'll then edit your Makefile (with make); this could be inspirational and just build your program by typing make. Most source code editors (like GNU emacs) or IDEs can be easily configured to run make with a single keypress.
Of course you want to invo... |
62,097,727 | 62,097,802 | Index of the lower_bound of a value in sets and maps in c++ | Suppose I want to get the index of the lower_bound of a value in a set and if i type
cout<<set.lower_bound(number)-set.begin()<<endl;
It is showing an error: no match for ‘operator-’
The same goes for maps as well,
However for arrays and vectors if i use
lower_bound(begin,end,val)-begin
it is showing the index
W... | Yes, this because the operator - is not defined for the iterators of std::sets (bidirectional iterators) while it's defined for the arrays iterators (random access iterators).
Instead, you can use std::distance(), as follows
int main()
{
std::set<int> set {1, 2, 4, 5, 6};
int number = 3;
std::cout<<std::di... |
62,097,789 | 62,097,883 | Why `copy constructor` is used while `move constructor` has been removed? | As the subject,the related code is:
#include <iostream>
class ABC
{ public:
ABC()
{
std::cout<< "default construction" << std::endl;
}
ABC(const ABC& a)
{
std::cout << "copy construction" << std::endl;
}
ABC(const ABC&& a)
{
std::cout << "move ... |
As per some documentation,compiler provides a default move constructor.
Let's take a look at some documentation. The following is from cppreference.com.
If [conditions] then the compiler will declare a move constructor as a non-explicit inline public member of its class with the signature T::T(T&&).
You're right. T... |
62,097,816 | 62,097,835 | string value returning null value | In my code when i try to print the value of result inside the function str its showing null all the time. Could some pls give a input.
It showing correct value When i tried to display the value of result inside the for loop fir each iteration.
string str(string s, int mid){
string result;
for(int j=0;j<=mid;j++){
... | You can't resize the string using operator[]. You are writing out of bounds and causing undefined behavior. Use
result += s[j];
to add characters or initialize the string with the correct size
string result(mid, '\0');
or simply copy the string;
auto result = s.substr(0, mid + 1);
You could replace the function str... |
62,097,987 | 62,107,399 | Splitting a string_view using ranges | I have a string containing a sequence of numbers separated with the , character. To read values from the sequence into an array I created the following code the GCC 10 refuses to compile:
#include <ranges>
#include <string_view>
#include <charconv>
#include <array>
template<std::size_t Sz>
bool to_bytes(std::array<std... | After the adoption of P2210 as a defect report against C++20, views::split can now preserve contiguity, so the above code is now valid and compiles on gcc trunk.
Do I misunderstand that type of octet should meet the contiguous_range criteria as the string_view does?
Yes. octet is not a contiguous_range. The inner ra... |
62,098,758 | 62,098,888 | Problem returning double from a function in C++ | I have a function like:
double foo(int a, int b)
{
double r=a+b;
return r/2.0;
}
when a= 10000 and b= 10001 It works fine. Returns 10000.5
But when a= 100000 b= 100001 It returns 100000
I have tested with other numbers also. It only works when integers are less than 6 digits.(without using setprecision at outp... | C double or long double uses 6 digit precision in output by default. If you want to write 2000.007 it will give output 2000.01 which is rounded upto 6 digit. But in the memory it will have the correct value. So, the correct way of doing that will be
double foo(int a, int b)
{
double r=a+b;
cout<<setprecision(4)... |
62,098,868 | 62,115,374 | How to check for collisions with SFML (While using a Base class Entity) | class Entity
{
private:
//Functions
void initiVariables();
protected:
//Variables
float velocity;
sf::Sprite sprite;
sf::Texture* texture;
MovementComponent* movementComponent;
AnimationComponent* animationComponent;
HitboxComponent* hitboxComponent;
//Component Functions
... | You can do simple inheritance from the Entity class. I don't know why your program crashes when returning sf::FloatRect objects. This should also be the correct solution to this problem.
#include <SFML/Graphics.hpp>
#include <iostream>
class Entity : public sf::RectangleShape {
public:
bool isColliding(Entity con... |
62,099,038 | 62,099,152 | Why can't an inherited protected constructor be made public? | Consider:
class A
{
protected:
A(int) {}
void f(int) {}
public:
A() {}
};
class B : public A
{
public:
using A::A;
using A::f;
};
int main()
{
B().f(1); // ok
B(1); // error: 'A::A(int)' is protected within this context
}
Why can't an inherited protected constructor be made public, while... | Unlike other members, the accessibility of the using-declaration that introduced the inherited constructor is ignored.
[namespace.udecl]/19,
(emphasis mine)
A synonym created by a using-declaration has the usual accessibility for a member-declaration. A using-declarator that names a constructor does not create a synon... |
62,100,020 | 62,100,697 | Avoiding Template operator overload collisions for float and non float on the operator first argument | I have a situation where my template modulus operator does play nice between floats and integer-ish types.
As I recall there is a way to make it select the more specific one over the broader scope one, but i can't seem to find or remember how to do this.
Basically I have 2 methods which are coliding (redefinition err... | T_COORDS is a class template parameter, not a function template parameter, which means it makes no difference for partial ordering as the more general function is instantiated with T_COORDS=float anyway, and so it's exactly the same as the float one. You can, however, disable that function from overload resolution, uti... |
62,100,209 | 62,100,317 | Index of vector of strings in c++ | I have a vector of string including :- chemistry physics maths.
I want to access first character of each word ie c of chemistry p of physics and m of maths. How to do that?
| You can output the first index element through this process.
I have made a 2D vector and applied a for loop so each row of the vector's first element is printed.
#include <iostream>
#include <vector>
int main()
{
std::vector<std::string> vec = {"chemistry", "maths", "physics"};
for(int i=0;i<vec.size();i++)
... |
62,100,553 | 62,100,711 | How do I use C++20 in vscode? | I want to use C++20 in vscode as I'd like to use .contains on an unordered_set, but when I try it I get
error C2039: 'contains': is not a member of 'std::unordered_set
and I don't understand why as I 've already went on to c_cpp_properties.json and specified the use of c++20 but it still doesn't seem to work, and I ca... | You must add the msvc compiler option /std:c++latest to be able to use the unordered_map::contains() member function.
|
62,100,593 | 62,100,803 | Why does copy constructor not need to check whether the input object pointers to itself or not? | As the code below, the copy assignment operator has to check whether the input object pointers to itself or not. I wonder why copy constructor does not need to do the same check.
I am novice in C++.I would be grateful to have some help on this question.
class rule_of_three
{
char* cstring; // raw pointer ... | Self-assignment sometimes happens, it's a part of a normal use of a class.
Passing a not-yet-constructed object as a parameter to its own copy (or move) constructor is not normal. While not undefined behavior per se1, there are no good reasons to do it, and it normally doesn't happen. It can happen accidentally, or if ... |
62,100,958 | 62,101,348 | open a shell tab for each service in a docker compose file | I have a client-server (both written in C++) application that I am managing using docker-compose. I'm quite new in docker technology and I'm wondering if docker-compose up can do the following job for me:
run services
open a shell tab for each service in the docker-compose.yml file.
I need a separate shell for each ... | You can simplify this setup using Docker's native image system. Typically the instructions for compiling the application will be built into the Dockerfile, so running docker-compose up --build will recompile things. Docker's layer cache system makes this run very quickly if the application hasn't actually changed. O... |
62,101,082 | 62,897,394 | Runtime error "SIGCONT" while finding lapindromes using c++ | I was trying to solve lapindrome problem on codechef.
On my local ide the program ran as expected.
But while in codechef submission it is giving runtime error "SIGCONT".
#include<iostream>
#pragma GCC optimize("Ofast")
using namespace std;
int main() {
int t;
cin>>t;
do
{
string l;
cin>... | First thing I would like to point out that your code is wrong because for the test case rotor your code is giving NO as an answer, it should be YES.
Why getting the wrong answer?
In question it is given, if there are odd number of characters in the string, we ignore the middle character and check for lapindrome.
So, yo... |
62,101,117 | 62,105,329 | OpenGL program doesn't show a triangle | I am following a tutorial on OpenGL in C++ and for some reason the exact same code doesn't work for me.
It is supposed to display a triangle, but it doesn't show anything.Just a blank screen.
Here is the code:
#include<iostream>
#define GLEW_STATIC
#include"GL/glew.h"
#include"GLFW/glfw3.h"
static unsigned int compi... | The issue is caused by GLFW_OPENGL_CORE_PROFILE. If you use a core profile OpenGL Context, then you have to use a named Vertex Array Object, because the default VAO (0) is not valid.
Either use a compatibility profile:
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
or create a VAO before specifying t... |
62,101,121 | 62,101,230 | Arduino object constructor in class sets rubbish values | I am currently trying to create a class that has a member object with a non-default constructor for an Arduino project. The object is a pointer so that I can construct when MyClass is constructed (MyObjClass *my_obj;)
// MyObjClass:
class MyObjClass(){
const int param;
public:
MyObjClass(const int param): para... | You are holding pointer to MyObjClass and try to init him with some int, the
right way will be my_obj(new MyObjClass(param)).
Also I would suggest to use smart pointers to avoid memory leaks.
|
62,101,358 | 62,101,623 | Why need list argument in list splice func cpp | Why do we need a list argument in the splice func cpp? Why only iterators aren't sufficient?
Result is the same if I pass l1 or l2 as a second argument
l1.splice(st, l1, it, it2); or l1.splice(st, l2, it, it2);
prints 1 4 5 2 3
#include <bits/stdc++.h>
using namespace std;
int main()
{
// initializing lists and ... | This call
l1.splice(st, l1, it, it2);
invokes undefined behavior.
When you need to extract a range of elements then other data members of the list as for example size must be updated.
If you will execute for example this statement
std::cout << l2.size() << '\n';
you can get unexpected result.
Here is a demonstrative ... |
62,101,535 | 62,101,744 | Overloading [] and + simultaneously | I have class which has array inside.
Suppose we have class A and array12 inside it.
All I need to do is A[index]+value so I suppose add to array12[index] that value.
int &operator[](int index)
{
return array12[index];
}
But what I need write when I overload operator +?
How do I know element index when overloadin... | You can't directly overload an operator to solve this as operator+ takes only argument. This is not possible:
void operator+(int idx, int num) // error: 2 parameters
{
a[idx] += num;
}
One way to solve this would be to use a member currentIndex and a setter function. E.g:
void setCurrentIndex(int idx)
{
current... |
62,101,572 | 62,105,280 | Weird Behaviour of Merge Sort Algorithm in C++ | I have implemented a merge sort algorithm, but it has a very weird bug which is hard to explain so please look at the code and output.
CODE:-
#include <bits/stdc++.h>
using namespace std;
int merge(int *ar, int l, int r) {
int aux[r - l + 1], s1 = 0, s2 = (r - l) / 2 + 1;
for (int i = 0; i < r - l + 1; i++)
... | In the merge function, the test if (s2 > r) is incorrect. It should be if (s2 > r - l).
It is very confusing to pass r as the index of the last element. In C and C++, it is more idiomatic to pass the index of the element after the last one, so r - l be the length of the array. With this approach, there are no error-pro... |
62,101,576 | 62,103,349 | Using FetchContent_Declare together with CMAKE_ARGS | I'm using cmake v3.13 and I want to change my ExternalProject_Add() for the SEAL library to:
include(FetchContent)
# Get the seal library
set(SEAL "seal")
FetchContent_Declare(
${SEAL}
GIT_REPOSITORY https://github.com/microsoft/SEAL
GIT_TAG v3.5.2
)
FetchContent_GetProperties(${SEAL})... | When build some project at the top-level, you may pass a parameter to it using command line option
-D<VARIABLE>=<VALUE>
(ExternalProject_Add builds the project "as if" top-level, so the option passing is technically the same).
When build some project as a subproject using add_subdirectory approach, you may use the sam... |
62,101,728 | 62,101,891 | Returning a vector of references from a Class | I have a function called FunctionCombiner (of base type ValuationFunction) which contains other valuationFunctions like so:
class FunctionCombiner : public valuationFunction
{
public:
FunctionCombiner(std::vector<std::shared_ptr<valuationFunction>>& Inner_);
void ValueInstrument();
std::vector<std::string> ... | In order to store references in a std::vector you'll have to use an std::reference_wrapper.
#include <functional>
#include <vector>
int main( )
{
std::vector<int> ints{ 1, 2, 3, 4, 5 };
std::vector<std::reference_wrapper<int>> references;
for( auto& i : ints )
references.push_back( i );
auto&... |
62,101,948 | 62,103,157 | Using a template with lambda function pointer | I'm playing around with some C++11 features, and I encountered the following:
#include <iostream>
#include <vector>
template <class T>
void map(std::vector<T>& values, T(*func)(T)) {
for (int &value : values) {
value = func(value);
}
}
int mul2(int x) {
return 2*x;
}
auto mul3 = [](int value) {
... | The lambda can implicitly be converted to a function pointer, but that's not what's failing here. Rather, the compiler is failing to deduce T because the lambda-to-function-pointer conversion doesn't happen during deduction.
main.cpp:5:6: note: template argument deduction/substitution failed:
main.cpp:21:16: note: ... |
62,102,356 | 62,102,473 | In what order are the variables multiplied | In what order will the variables be multiplied.
int a = 5;
int b = 3;
a *= b;
is that
a = a X b;
or
a = b X a;
| The standard defines that a *= b is the same as a = a * b, unless the types have been overloaded.
See section [expr.ass] in the standard (section 5.17 Assignment and compound assignment operators in the C++11 version).
For a * b * c, the operation is grouped left-to-right, i.e. (a * b) * c. See [expr.mul]. This also ho... |
62,102,889 | 62,115,249 | How to convert Uint8List to C equivalent datatype using dart:ffi | I am trying to send an image to my Custom C++ code which I am planning to run using dart:ffi. I have successfully run the hello world problem where I send two integers and get the some of them as another intiger.
Now I want to send a whole image to it and process it on my C++ code. I am able to get Uint8List from the ... | You have to allocate, and then copy the data into, a Pointer<something>. Your exported C function can then have a something* argument. You will also need to pass the length of the data. As the goal is to construct a cv::Mat you might want to pass the geometry instead, and infer the data length from that.
So, if your ex... |
62,102,900 | 62,102,976 | How to access 2D vector having map? | int main()
{
map<int,string> my_map;
vector<map<int,string> > v_temp;
vector< vector<map<int,string> > > vectors;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
my_map.insert(make_pair(1,"sea"));
my_map.insert(make_pair(2,"ocean"));
... | vectors[i][j] is a map, which does not have a first or second. You want to loop over each pair of the map, and use first and second on it.
for ( size_t i = 0; i < vectors.size(); i++ )
for ( size_t j = 0; j < vectors[i].size(); j++ )
for ( const auto &pair : vectors[i][j] )
std::cout << "vectors... |
62,103,328 | 62,103,496 | OnVScroll : invoked from CSpinButtonCtrl or Vertical ScrollBar? | I have a derived MFC CFormView class (CMyFormView) and I must implement my own OnVScroll function.
My CMyFormView is used for several dialog box resources, mainly, to re-implement the OnCtlColor() function. Some dialogs contain a CSpinButtonCtrl control.
My problem:
When the OnVScroll function is invoked, I am unable... | If the OnVScroll handler is called via actions in a window's (framework-provided) scrollbar, then the pScrollBar parameter will be NULL; if it is from a control, then it will not be NULL. From the CWnd Documentation:
pScrollBar If the scroll message came from a scroll-bar control, contains a pointer to the control. If... |
62,103,456 | 62,103,642 | Is there a C++ preprocessor directive or similar that I can use to convert units | I am doing a bit of motor control, and instead of saying 39553 encoder ticks, it would be easier for my human brain to say 6.5 inches. I would like to save processor overhead by converting this at compile time. Is there a way to do this with preprocessor directives or templates maybe? Thanks.
| I would use a constexpr for this. As @ChrisMM mentioned, it is not preprocessor, but it will be evaluated at compile time rather than run time. If the values you gave correspond to the actual relationship between ticks and inches, you can use:
constexpr int toTicks(double inches) {
return int(6085 * inches);
}
By ... |
62,103,619 | 62,152,771 | How can I open a text file with my executable? | I want to right-click on a text file and "Open With..." it with my own program, but I can't find any information on how to do that. I want to make my program in C++ or with WinForms (C#).
I want to open that file and to use my program as an interpreter on a small "homemade programming language", so I want to pass the d... | I'm just gonna to answer your Question for C#. If you still need C++ support you can tell me.
Option 1 - Drop down:
So if you for example create a Console-Application in C# (Visual Studio), it will look like this:
As you can see in the Picture: the Program accepts Arguments (args String Array)
If you drag & drop your ... |
62,103,723 | 62,103,770 | glGetShaderInfoLog with string | I'm am doing a shader class which have a method returning shader's logs:
std::string Shader::GetShaderInfoLog(){
GLint TotalLenght=0;
GetShaderiv(GL_INFO_LOG_LENGTH,&TotalLenght);
std::string logs;
logs.reserve(TotalLenght);
glGetShaderInfoLog(name, TotalLenght, NULL, &logs[0] );
return logs;
}
... | reserve just increases the capacity of the string. But does not change it's size.
You need to resize it:
std::string Shader::GetShaderInfoLog(){
GLint TotalLenght=0;
GetShaderiv(GL_INFO_LOG_LENGTH,&TotalLenght);
std::string logs;
logs.resize(TotalLenght);
glGetShaderInfoLog(name, TotalLenght, NULL... |
62,103,842 | 62,104,866 | How to pass template arguments via constructor? | I'm looking for a way to pass the template arguments of a template-based class (the main class of the FastLED library on Arduino, to be specific) via the constructor of my own class (which should basically wrap the FastLED library). I want to specify the template arguments necessary to initialize FastLED in the main fu... | I suggest you look into the FastLED implementation, it is written exactly how you want to use your wrapper class. I am missing some libraries so I cannot tell if everything compiles, but the solution must be close to this
template <ESPIChipsets chipset, uint8_t data_pin, uint8_t clock_pin, EOrder rgb_order = RGB>
class... |
62,104,003 | 62,115,730 | I'm trying to retrieve data from qSQL database | But it does not get the data from the database. I'm do not want to retrieve the data to the table and want to display data in particular line edit. What is the error? Is there any modification?
This is the Code that I'm using:
void Userdetails::on_pushButton_4_clicked()
{
delete ui;
// database connection
... | This code has four main issues:
You have deleted the ui at the beginning of your code. Hence, the first line that calls ui-> will crash the program.
You have defined your query improperly. Also, your way to select a name for your connection is not right.
You have executed your query twice (one is enough).
You've not b... |
62,104,420 | 62,115,897 | Emit signal to update UI from thread | I have defined a new slot in a class that inherits from QThread:
class MyThread : public QThread
{
Q_OBJECT
public:
MyThread(QString fileName);
void run() override;
signals:
void addNewItem(int row, int col, QString text);
private:
QString fileName;
};
In the Dialog class I have defined slot tha... | You have connected signals and slots after the thread runs.
Replace worker->run() with worker->start(). The start member immediately calls run once the thread starts successfully.
Connect signals and slots as follows:
worker = new MyThread(filePath);
connect(worker, &MyThread::addNewItem, this, &Dialog::onAddNewItem)... |
62,104,460 | 62,104,633 | Wrong Values in For Loop C++ | I am trying to print the values stored in Array l[] and r[] from array a[].
When I am trying to print values of array l[] its showing me invalid values.
But when I comment down the line which are providing values in array r[] from a[] the values of array l[] are then showing correct values.
I am providing input value... | Here's your code:
for(int i=0;i<10;i++)
cin>>a[i]; // this one looks OK
for(int i=0;i<5;i++)
l[i] = a[i]; // this one looks OK too
for(int i=5;i<10;i++)
r[i] = a[i]; // you access 'r' beyond 5 that damages other vars
|
62,104,907 | 62,105,115 | Qt Quick2 Creating qmlRegisterSingletonType for Singleton Class Type | I am trying to create a singleton property using qmlRegisterSingletonType but when I try to access the object in the QML I am getting below error in the console logs:
qrc:/qml/MyQml.qml:21 Element is not creatable.
Below is my code:
// TestSingletonType.h Class
#include <QObject>
#include <QJsonObject>
#includ... | The error is clear: A singleton is not created in QML since it was already created in the callback (qmlInstance method), you just have to access the properties of that method. The typeName ("TestSingletonType") is the id.
Item {
// binding property
foo_property : TestSingletonType.foo_value
// update singl... |
62,105,010 | 62,107,405 | I have a question about C ++ boost :: asio and std :: async | I know that both are designed asynchronously.
What I'm curious about is the function callback when creating a thread using the above two.
Is it possible for a single thread to write and read asynchronously?
| Yes. In fact I have many examples of that on this site.
I wrote one yesterday that starts out with true single-threading:
How to pass a boost asio tcp socket to a thread for sending heartbeat to client or server
Note that you can easily also do multi-client servers on a single thread:
Boost.Asio: Is it a good thing ... |
62,105,109 | 62,105,180 | Cannot create and open File using file handling | I am writing a basic code but run into an error when trying to open a file. I've had a rough break and am having to start from the basics. Following is the part of the code where I run into the error:
int main()
{
string name;
fstream file;
cout << " Enter file name and type (E.g filname.txt) : ";
ci... | If the std::basic_fstream::open(std::string&) overload isn't available you are probably compiling using some C++ version prior to C++11.
Make sure you compile using at least C++11 and it should be fine.
|
62,105,665 | 62,106,463 | C++ Multithreading - Writing to different keys in same map causing problems | I have the following function running several times on 6 different threads, with the same nodeMap being passed to each function. I'm sure that the keys being read and written to on each thread are independent (no two threads will have the same histories). Despite this, occasionally this code will output "Preposterous".... | Thanks to everyone in the comments for helping me understand where I was wrong.
I created the following minimal reproducible example to test the issue:
#include <iostream>
#include <thread>
#include <unordered_map>
const int NUM_THREADS = 6;
void test(std::unordered_map<int, int>& map, int thread) {
for(int i = t... |
62,105,884 | 62,105,975 | C2675 unary operator caused by wrong scope | I am currently working on my own Vector class for the purpose of learning C++ and got stuck here.
The error happens in my implementation of the overloaded -= operator. Because the subtraction of two vectors is similar to adding two vectors but using the negative, I try to reuse the code from the += operator by utilizin... | There is a bug in your operator+=(const Vector3& v). It performs assignment, but not the addition.
As for the unary - operator, if you want to use it in the class body, it should be accessible from the class body. Basically, you need to define you unary - operator
Vector3 operator-() const noexcept {
return Vector3... |
62,106,223 | 62,106,485 | c++ function to find the sum of four minimum maximum elements in an array not working | I am solving a question in which i have to write a function which finds the maximum and minimum sum of any four integers in an array passed to it and then displays it.
here is my code:
void miniMaxSum(vector<int> arr) {
int minsum=0;
int maxsum=0;
int l1,l2,l3,l4;
int s1,s2,s3,s4;
... | void miniMaxSum(vector<int> arr) {
sort(arr.begin(), arr.end());
int sumMin = 0, sumMax = 0, len = arr.size() - 1;
for(int i = 0; i < 4; i++){
sumMin += arr[i];
sumMax += arr[len - i];
}
cout<<"minimum sum: "<<sumMin<<endl;
cout<<"maximum sum: "<<sumMax<<endl;
}
|
62,106,482 | 62,109,360 | Writing a parser in C++ to parse the given HTML entities | Recently, I faced a coding question in which we had to parse the mention HTML entities. These following entities needed to be parsed -
" to "
' to - '
> to >
< to <
& to &
⁄ to ⁄
There will be a string txt given which has to be parsed as per above rules. Following is my approach which works ... | Here's how I would suggest approaching this problem:
0) firstly I would just create a new string with the correctly formatted output. This is easier than having to modify the string in-place - you just build the string up bit by bit. Plus I don't know if modifying it in-place is beneficial anyway, every time you erase ... |
62,106,684 | 62,106,781 | C++: Matching regex, what is in smatch? | I'm using a modified regex example from Stroustrup C++ 4th Ed. Page 127 & 128. I'm trying to understand what is in the vector smatch matches.
$ ./a.out
AB00000-0000
AB00000-0000.-0000.
$ ./a.out
AB00000
AB00000..
It seems like the matches in parenthesis () appear in match[1], match[2], ... which the total match appe... | The type of matches is a std::match_results, not a vector, but it does have an operator[].
From the reference:
If n == 0, returns a reference to the std::sub_match representing the part of the target sequence matched by the entire matched regular expression.
If n > 0 and n < size(), returns a reference to the std::sub... |
62,106,919 | 62,107,194 | How properly instantiate static field tat is another class object | If I have in my .h file
class A
{
...
protected:
static std::mutex someMutex;
}
What is proper way to instantiate it in the cpp file?
Just to write
std::mutex A::someMutex;
? It works, but just such syntax where I basically declare a field twice feels a bit confusing, so I decided to doublecheck asking here, also m... | What you did is correct but these two notations are not exactly the same thing written twice.
Inside the braces of the class (in the .h file) this is a declaration.
It is a kind of promise saying "I swear this exists somewhere".
This can be seen in many translation units (i.e. .cpp files including this .h
file).
On the... |
62,106,963 | 62,107,828 | How to take subarray from 2d Boost.MultiArray? | I am working on a program where I need to use 2d Boost.MultiArray. I managed to initialize it and fill it with data. But I don't understand how to take subarray of size i,j if multiarray is of size m,n. Where i<=m and j<=n. Can anyone help me?
Code:
matrix_type matrix(boost::extents[width][height]);
read_matrix... | Documentation https://www.boost.org/doc/libs/1_73_0/libs/multi_array/doc/user.html#sec_generators
Boost.MultiArray provides the facilities for creating a sub-view of an
already existing array component. It allows you to create a sub-view
that retains the same number of dimensions as the original array or
one tha... |
62,107,094 | 62,113,849 | Calling a C++ function from python, using cython, with cythonize | I'm trying to learn Cython, and I want to call a simple C++ function from python
When building, I either have a uio.obj : error LNK2001: unresolved external symbol _just_a_func, or when I tried different combinations of cython prototypes, my just_a_func() function does not land in my module.
Here is all the code, setup... | Found a solution on https://dmtn-013.lsst.io/
This is the working solution
########################
### uio.h
########################
#include <string>
using namespace std;
int just_a_func(string s){return s.length();}
########################
### uio.pxd
########################
from libcpp.string cimport string
c... |
62,107,254 | 62,107,328 | Program is not asking 3 questions and uses my answer to the first question for the other two | I am trying to ask the user to enter the names of 3 of their friends, however, it only asks one question and writes the answer from my first one in the second and third.
#include <iostream>
using namespace std;
int main()
{
char first_name;
cout << "Please enter a name: ";
cin >> first_name;
cout << f... | You should probably be using string in your code to take the input of names. In names you are probably passing more than one character. The first one is read by first_name and any further character will be read by the following character, specifically cin>>second_name and cin>>third_name would read the 2nd and 3rd char... |
62,107,332 | 62,112,356 | Difference between dynamically allocated arrays and static arrays | I am getting an introduction to dynamic memory allocation, and I learned that a dynamic array ( the one like int *p = new int[n] \\ where n is the user input describing the number of elements is used when you do not know how many elements the user requires/ declaring an array of a size that the user wants. However, ins... | Now, people have already stated that int a[n] is not valid c++. But Perhaps I could help you with the answer you're looking for.
What is the advantage of dynamic arrays in this case then?
The syntax int a[n] is called a VLA (Variable Length Array). These are illegal in C++ but allowed in C. So let's focus on the tech... |
62,107,473 | 62,121,162 | I can enter the inputs but I'm not able to see the output when I run my code (CTRL+F5) in C++ in visual studio 2017 |
I can enter the inputs but I'm not able to see the output when I run my code (CTRL+F5) in C++ in visual studio 2017. This code is written to overload the operator *, ">>" & "<<" through the friend functions. one constructor initializes the vector elements to zero while the other constructor is used to initialize the e... | Probably your linker settings are incorrect. Go to menu item Project/Properties. Then in the dialog find Configuration Properties/Linker/System/Subsystem and make sure it says Console (/SUBSYSTEM:CONSOLE).
Evgeny is correct cin.get() is not guaranteed to halt your program because there are still characters waiting to b... |
62,107,547 | 62,107,618 | How to return referece to base class in C++ | I have a base struct which include 2 members of1 and of2.
The Derived class derived inherent it,
which has a function to return a reference to member of Base class.
I hope Derived can be used in the main as following:
struct Base {
public:
std::ofstream of1;
std::ofstream of2;
};
class Derived : public Base {
pu... | Base is a class and it is not an expression that can be returned.
You can get pointer to the current object with the keyword this. You can indirect through that pointer to get a reference to the current object. That reference implicitly converts to reference to base. So, correct solution is:
Base& write_file() {
re... |
62,108,100 | 62,108,334 | Variant with unique types | While writing a cpp library I ended up with possiblity that std::variants shall contain repeating types, that is for example, std::variant<int, double, int, std::string, int>. It may be useful in some occasions but in case of my library I find this unnecessary. And so I would like to filter type reptitions like this:
s... | #include <type_traits>
#include <variant>
template <typename T, typename... Ts>
struct filter_duplicates { using type = T; };
template <template <typename...> class C, typename... Ts, typename U, typename... Us>
struct filter_duplicates<C<Ts...>, U, Us...>
: std::conditional_t<(std::is_same_v<U, Ts> || ...)
... |
62,108,317 | 62,108,406 | C++ does not use the desired constructor | So there seems to be some problem with the solution to Problem 9-2 in the book "Object-Oriented Programming in C++, 4th edition" by Robert Lafore. So the problem is that if I would like to create a Pstring object with a statement like Pstring = "This is a string", the Pstring constructor will only call the constructor ... | In a function parameter, a T[] (where T is char in your case) is really a T*.
In C++, a string literal is a const char[N] fixed array, which decays into a const char* pointer to the 1st element. But you don't have any constructors that accept either of those types as a parameter. A const char* can't be given to a char*... |
62,108,384 | 62,152,984 | Not properly executed overridden code using an INET extended module | I have to extend the UdpBasicApp module from INET4 in OMNeT++ 5.6.1 (Ubuntu 18.04.4) and execute two overridden methods (initialize and handleMessageWhenUp).
It seems an easy task, and looked like it was all fine when I built the project (momentarily stored inside the "examples" folder in inet4) with no errors but, aft... | There are two independent faults here:
1.) You should NOT add C++ code into INET's examples folder. That folder is NOT designated as a source folder, so the build system will not pick up, build and link to the executable, meaning that your code is not present in the model. That's one reason why you are not getting your... |
62,108,669 | 62,108,856 | Finding permutation and combination in C++ | I want to find a series of numbers of dynamic length in C++. Suppose I have 2 groups of numbers: arr1[3] = {1, 3, 8} and arr2[4] = {2, 9}, then the expected output is:
'1, 2',
'1, 9',
'3, 2',
'3, 9',
'8, 2',
'8, 9'.
However, if there are 3 groups now : arr1[3] = {1, 3, 8}, arr2[2] = {2, 9} and arr3[5] = {1, 3, 9} then... | I used vector instead of arrays, as they are way easier to deal with.
The trick is to enumerate, in lexicographic order, the positions in the arrays, then display the values at those positions:
#include <vector>
#include <iostream>
using std::vector;
void permutate(vector<vector<int>> values)
{
// the positions i... |
62,108,844 | 62,108,943 | Conversion from int to char failed and console prints weird symbol | I am having a weird issue and I don't know how to explain it. When I run this code it prints this symbol -> .
This is my code:
#include <iostream>
int main() {
int num = 1;
char number = num;
std::cout<<number<<std::endl;
system("PAUSE");
return 0;
}
I don't understand why. Normally it shou... |
Conversion from int to char failed
Actually, int was successfully converted to char.
Normally it should convert the integer to char.
That's what it did. The result of the conversion is char with the value 1.
Computers use a "character encoding". Each symbol that you see on the screen is encoded as a number. For ex... |
62,108,938 | 62,161,573 | Qt infinite loop in another thread | I am trying to setup an infinite loop in another thread. The purpose is to download some data from an URL, send the data to the main thread and sleep for some seconds:
DataFetcher::DataFetcher(QUrl url, int fetchRateSec) :
url {url},
fetchRateSec {fetchRateSec}
{
}
void DataFetcher::run()
{
QNetworkAccess... | Per the discussion in the comments, it seems like the whole business of threading is not needed.
One of Qt's strongest attributes is that it is event-driven. You generally create a program by describing what you want to happen (slots) in response to certain events (signals). Explicitly waiting or sleeping is very rare ... |
62,108,958 | 62,109,011 | Accessing member variables with getters C++ | If I have this private map of scenes in my header file
std::map<std::string, Scene> scenes;
Should my public getter be like so?
std::map<std::string, Scene>* getScenes() { return &scenes; }
Still getting my head around pointers in c++ so apologies if it seems like a dumb question
| Unless you need to, returning a pointer to a member that isn't stored as a pointer isn't a great idea. Passing pointers around can get messy e.g. if the original object goes out of scope you'll end up with a dangling pointer. Returning by const reference should be your first port of call:
const std::map<std::string, Sc... |
62,109,023 | 62,109,333 | About directionality in a topological graph | I am solving this question on LeetCode.com. A statement in the question says:
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
My aim is to come up with a graphical representation. My question is, as per the above statement, shoul... | It doesn't matter. If you reverse all your edges and topological sort, the result that you'll get will be the reverse of some topological ordering of the original graph. Do it in whichever way makes the most sense to you.
|
62,109,026 | 62,109,205 | In a class, what is `using Base::BaseOfBase;` supposed to do? | Consider this code:
#include <iostream>
#include <type_traits>
struct A
{
A(int x) {std::cout << "A(" << x << ")\n";}
};
struct B : A
{
using A::A;
B(int x, int y) : A(x) {std::cout << "B(" << x << "," << y << ")\n";}
};
struct C : B
{
using B::A; // <--
// C() : B(0,0) {}
};
int main()
{
C... | The constructor is not inherited. Primarily because
[namespace.udecl]
3 In a using-declaration used as a member-declaration, each
using-declarator's nested-name-specifier shall name a base class of
the class being defined. If a using-declarator names a constructor,
its nested-name-specifier shall name a direct base cl... |
62,109,421 | 62,109,867 | Send string literal as argument in C++ template - Parameter pack | My function declaration and implementation.
It accepts variable number of arguments
template <typename... ParamType,
typename = typename std::void_t<std::enable_if_t<std::is_same_v<ParamType, std::string> ||
std::is_floating_point_v<ParamType> ||
... | The key expression is this disjunction:
std::is_same_v<ParamType, std::string> ||
std::is_floating_point_v<ParamType> ||
std::is_integral_v<ParamType>
You just need to add these terms:
std::is_same_v<std::decay_t<ParamType>, char const *> ||
std::is_same_v<std::decay_t<ParamType>, char *>
The usage of std::decay_t wi... |
62,109,526 | 62,109,643 | C++ friend template that use SFINAE | This is a simple question in fact. I have a template class with one parameter.
In an other object, I make it a friend of it, like this :
template< typename type_t >
class A
{
...
}
template< typename type_t >
class B
{
template< typename >
friend class A; // Works fine !
...
}
After that, I wanted to... | As StoryTeller said in the comments, a static_assert inside the class B or A might be a simpler solution. It will not use a second template parameter and will enable the familiar friend declaration.
However, if you still want to go through the SFINAE way, you can declare your friend using the full SFINAE expression in ... |
62,109,533 | 70,779,238 | uWebSockets concurrent sessions | for the sake of simplicity, let's assume I have only one uWebSockets instance running on my server:
struct UserData
{
uWS::WebSocket<true, uWS::SERVER> *ws;
bool logged_in = false;
ID user_id;
};
uWS::SSLApp()
.ws<UserData>(
"/*",
{
.open =
... | During the sleep, uWebSockets will not process other network connections.
Change the sleep to fast code that only gets a mutex, adds to a queue, and releases a mutex.
Make another thread (let's call it ProcessingThread) that gets the same mutex, removes messages from that queue, releases the mutex, and processes the me... |
62,109,647 | 62,109,742 | How to make a catch block with more arguments that i catch it from objects from classes for exceptions? | I have three exceptions classes in my code, so when i want to use more arguments (more different objects to catch i get an compile error) so how i can catch more exceptions?
i tried to do this
try{
User * u = new FacebookUser(username,password,email,friends,likes,comments);
network += u;
}
... | If you have multiple types of exceptions you want to catch, you need to catch them separately - otherwise, what would be in say ip if InvalidEmail was thrown?
Correct code will be like
try {
//...
} catch (const InvalidPassword& ip) {
//...
} catch (const InvalidEmail& ie) {
//...
} catch (const MaximumSize... |
62,110,010 | 62,110,033 | If I extract something from a stream, does the stream not contain what I extracted anymore? | If I have code like below and I store "This" in str first from stream streem:
using namespace std;
int main()
{
istringstream streem("This is the content in the stream.");
string str;
streem>>str;
cout<<str; //This will cout "This"
If I do streem>>str again and cout<<str again, this will display is.
So... | The answer is different for different streams .
The stringstream has a memory buffer and an indicator that remembers where you were up to on the reading. So the next read starts where the previous read left off.
File streams work in a similar way, they remember which point of the file they are up to. In both cases you... |
62,110,097 | 62,110,164 | C++: random number generation using Stroustrup example? | I'm using the random number generation from Stroustrup C++ 4th Ed. Page 129. Unfortunately, it does not appear to be random and keeps generating and int 1. Does anyone know why it's not generating a random number 1-6?
#include <random>
#include <iostream>
#include <functional>
using namespace std;
int main(int arg... | You have to seed your engine (re) with some random:
Replace:
my_engine re {};
With:
std::random_device rd; //Will be used to obtain a seed for the random number engine
my_engine re(rd());
|
62,110,515 | 62,116,279 | Eigen: dividing a vector by a scalar in two steps works but not in one step | So I'm trying to implement Power iteration to find the greatest eigenvalue and corresponding eigenvector in C++. I'm using the Eigen library. The weird thing is that, when I divide a vector by a scalar in a single line (marked in line (1)), it throws an error, and is as helpful as C++ errors can be:
No viable conversio... | Eigen distinguishes between 1x1 matrices and scalars, e.g., b.transpose()*b is actually a 1x1 matrix. There are some special cases where products resulting in a 1x1 matrix are implicitly convertible to a scalar, but the preferred way is to always use a.dot(b) for these products (if indeed you want to have a scalar).
M... |
62,110,985 | 62,111,081 | Add of std::valarray got different sizes with different operand orders | Add of std::valarray got different sizes with different operand orders.
Code is as the following:
#include <iostream>
#include <valarray>
using namespace std;
int main() {
std::valarray<float> v0{3.f, 0.f};
std::valarray<float> v1{0.f};
std::valarray<float> v2 = v0 + v1;
std::valarray<float> v3 = v1 + ... | operator+() does not perfom concatenation of two std::valarray<float> objects,
std::valarray<float> v2 = v0 + v1;
Here, since v1 is of size 1, it will add the only value in v1 to both the elements in v0, hence size stays 2.
std::valarray<float> v2 = v1 + v0;
But here, v1 is of size 1, it will add the first element 3... |
62,111,391 | 62,111,440 | Strange C ++ behavior when i using a template in which need to calculate the address of an array cell | I created a matrix class and for example a simple cleanup function
template<typename T>
class matrix
{
public:
matrix(int Lenght, int Height)
{
this->container = new T[this->lenght * this->height];
this->lenght = Lenght;
this->height = Height;
}
void Nulling()
{
siz... | In your constructor, the statement
this->container = new T[this->lenght * this->height];
Has undefined behavior, because you are using this->lenght and this->height before they have been assigned values, thus the size of the allocated array is indeterminate. You need to do those assignments first:
matrix(int Lenght, i... |
62,111,505 | 62,115,320 | Template metaprogramming to match function signature exactly | With template meta-programming it's possible to query properties of types. For example in the case below I'm checking if a certain type has a member function "foo" which takes in another type as the argument.
Is there a way to check if the parameter type is an exact match for the template vs. one that be converted to i... | You were almost there. I changed the test so that I take the address of foo and test the type of the resulting pointer-to-member by static_casting it to itself.
#include <type_traits>
#include <iostream>
using namespace std;
struct S2
{
int foo(float x)
{
return 0;
}
};
template <typename T1, typename ... |
62,111,745 | 62,113,642 | vector of strings and transform with C++20 ranges | What is wrong in the following C++20 ranges basic syntax (Ubuntu 20.04, gcc g++ (Ubuntu 10-20200411-0ubuntu1) 10.0.1 20200411 (experimental) [master revision bb87d5cc77d:75961caccb7:f883c46b4877f637e0fa5025b4d6b5c9040ec566]):
#include <iostream>
#include <vector>
#include <ranges>
[[nodiscard]]
auto f(const std::vecto... | There is nothing wrong with your compiler. Your code has Undefined Behavior. Views are lazy evaluated and require that the underlying container is still alive when you access them. What you have is akin to a dangling reference.
{"c", "dddddddd", "aaaa", "bb"} Here you create a temporary vector which dies at the end of ... |
62,111,768 | 62,111,800 | Split string into parts of equal length c++ | I want to iteratively break up a string of arbitrary length into substrings of length = 80 until the size of the final substring is either less than 80 or 0.
Assume the string is not divisible by 80 so length of final substring is not necessarily 80.
What am I doing wrong here?
#include <string>
#include <math.h>
str... | ceil(str.length()/80) is wrong because it's an integer division. ceil(str.length()/80.0) would work better. It feels wrong to be using floating point arithmetic at all however.
if(str.length()/80 >= 1){
sub = str.substr(i*80, 80);
}
if(str.length()/80 == 0){
sub = str.substr(i*80, str.length()%80);
}
Seems O... |
62,112,062 | 62,126,686 | Is there a way to specify custom locale directory for C++ program on macOS | In my mac, /usr/share/locale is the default locale directory where all the locales are placed. I want to specify a custom locale directory, so that a C++ program (i.e. libc/libc++) can pick up locale from there.
#include <locale>
int main() {
std::locale a("en_US.utf-8"); // OK.
std::locale b("en_US.utf8"); // Erro... | I got the answer of my question.
PATH_LOCALE=<new_path> ./binary
It works for mac (BSD).
Thanks.
|
62,112,273 | 62,112,412 | c++ std::future is not getting called | I am working with std::async and std::future in c++, but am having a bit of trouble.
When I run this code, i expect to see (in the stdout) "hello world" but, instead I get nothing:
#include <iostream>
#include <future>
using namespace std;
struct A {
future<string>* test;
};
string getStr() {
return "hello world"... | The future is destroyed as soon as callA() returns, so you have a pointer to an object that no longer exists. a.test->get() is therefore undefined behavior, and anything might happen -- including indefinitely blocking, or crashing, or actually printing the right result.
If you wish to return it from the function as a ... |
62,112,274 | 62,112,639 | How do I scrape status code from the log file? (in c++) | Each of the string in log file looks like this:
44.225.84.206 - - [12/Mar/2020:07:02:43 +0530] "GET http://example.com/ HTTP/1.1" 200 73 "-" "AWS Security Scanner"
I have to count the no of status code(here 200) in the file.
| You can use regular expressions through the std::regex library. "\".+\" (\\d+)" pattern matches any digit after any quoted string and a space. Since your status code is immediately after a quoted string "GET http://example.com/ HTTP/1.1" 200, it will match the first numeric characters till space, so 73 won't be matched... |
62,112,429 | 62,113,021 | How to read UTF-8 XML with RapidXML and use it with C++ | I work on a C++ application and implemented a translator class that uses data from a XML file to translate strings. I have now serious problems with special characters currently for German Umlauts ÖÄÜ for example...
On Visual Studio I see following in Debug view, it reads following sample string "Dateiäüö":
Because of... | After hours working on this issue the solution was quite simple.
Never trust your debugger!!! The problem was caused by wxwidgets... it displays the same chars as seen in my debugger, but if I put a utf8 to utf16 conversion before rendering of menu items, it displays the string correct!
The solution is to do not use sh... |
62,112,467 | 62,112,603 | Is the pointer passed to placement new a non-UB pointer to its object representation? | struct foo {
int a;
int b;
};
std::array<char, sizeof(foo)> buffer;
foo a {1, 2};
foo* b {new (buffer.data()) foo};
std::memcpy(buffer.data(), &a, sizeof(foo));
a == *b; // the important part
I know that the placement new leaves the values of b's fields indeterminate, but does the subsequent memcpy, through the... |
Placement new
If placement_params are provided, they are passed to the allocation
function as additional arguments. Such allocation functions are known
as "placement new", after the standard allocation function void*
operator new(std::size_t, void*), which simply returns its second
argument unchanged. This is ... |
62,112,521 | 62,112,744 | Error in C++17 fold expression to calculate factorial | The following program gives errors in both g++ and clang...
#include <iostream>
#include <utility>
using namespace std;
//Since C++17 one can use fold expression to calculate factorial:
template <class T, T N, class I = std::make_integer_sequence<T, N>>
struct factorial;
template <class T, T N, T... Is>
struct facto... | You used the wrong type for your result object.
std::index_sequence is a template that accepts only a pack of std::size_t. It doesn't accept a type parameter, because the type is fixed. It is an alias template for std::integer_sequence<std::size_t, Ints...>.
So you trying to specify a type as its the first argument in ... |
62,112,695 | 62,276,928 | undefined reference to soci::session::get_last_insert_id | So, I have downloaded soci 4.0.0 from souceforge and unpacked it into /tmp/.
Then:
cd /tmp/soci-4.0.0
mkdir build
cd build
cmake -G "Unix Makefiles" -DWITH_BOOST=OFF -DWITH_ORACLE=OFF -DSOCI_TESTS=ON -DWITH_SQLITE3=ON -DSOCI_SQLITE3_TEST_CONNSTR="test.db" ../
make
make test
And I got:
Running tests... Test project /tm... | I found the error.
Instead of
g++ -std=c++14 -o socitest socitest.cpp -I../include/soci/ -I ../include/private/ -I/usr/include/ -L./lib -L/usr/lib/x86_64-linux-gnu -lsoci_core -lsoci_sqlite3 -lsqlite3 -ldl
it should be
g++ -std=c++14 -o socitest socitest.cpp -I../include/ -I./include/ -I/usr/include/ -L./lib -lso... |
62,112,726 | 62,112,823 | How is an int data stored on the memory in terms of bits? Is it not right-aligned? | I got really confused while I was trying some things out with fwrite function in C.
I read through the manual of fwrite here http://www.cplusplus.com/reference/cstdio/fwrite/
It says the functions writes the array byte by byte, so I tried to write an array of integers, expecting each integer in the array be split up to... | Looks like you are missing the terminology Endianess. Many systems save their words (4-bytes in a 32-bit system) in "Little Endian" order - that is "little end" first. This means the least significant byte (LSB) is first (lowest address), and it goes up from there. That's why 2 is first (lowest address, LSB) and 1 is s... |
62,113,089 | 62,113,257 | This program is accepting only 5 inputs while i am giving n=8 |
Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line.
code written by me:
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main()
{
int n;
int a[n];
float sum1=0,sum2=0,... |
This program is accepting only 5 inputs while i am giving n=8, kindly help me out to find the error
The int n; (in the function main()) declares a variable with automatic storage class and it has garbage value (unless you initialize it int n = 100;). So, it's undefined what value variable n will hold and since, you a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.