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 |
|---|---|---|---|---|
68,583,480 | 68,583,803 | How to annotate a ternary expression with `[[likely]]`? | In C++20, is there a way to annotate a ternary expression with [[likely]]/[[unlikely]] to hint the compiler which of the two outcomes is more likely?
The following syntax doesn't seem to work
condition ? [[likely]] function1() : function2()
Is there a different syntax to annotate ternary expressions? Or will I have to... |
Is there a different syntax to annotate ternary expressions?
No, there is no way to annotate a ternary conditional expression with the [[likely]] attribute.
Or will I have to use an if instead?
Yes. Or alternatively, you can omit the attribute.
For what it's worth, it is possible using the GNU extension:
__builtin... |
68,583,568 | 68,584,050 | Why doesn't ranges provide a type erased view for non-contiguous ranges? | I would like to have a function that will take any range/view of a fixed value type.
int main()
{
std::array<std::pair<int, int>, 2> a{...};
std::array<std::pair<int, int>, 3> b{...};
generic_fun(a);
generic_fun(b);
};
Of course I could do
template <std::ranges::range R>
requires std::same_as<std:... | range-v3 has this under the name any_view<Ref, Cat>, where Ref is the range's reference (not value_type) and Cat is the iteration category (which defaults to input). That would let you write a function like:
int sum(any_view<int const&> v) { // <== not a function template
int s = 0;
for (int i : v) {
s ... |
68,583,581 | 68,589,113 | How can I use equality in xt::filter? | the following code,
#include <iostream>
#include "xtensor/xadapt.hpp"
#include "xtensor/xarray.hpp"
#include "xtensor/xindex_view.hpp"
#include "xtensor/xio.hpp"
#include "xtensor/xmasked_view.hpp"
#include "xtensor/xview.hpp"
using namespace std;
int main() {
xt::xarray<float> a = {{1, 2, 3}, {4, 2, 6}, {9, 0, ... | You can use xt::equal(a, b) instead of a == b. I.e.
xt::filter(a, xt::equal(a, 2)) = 10;
does what you want.
|
68,583,911 | 68,584,087 | C++ Module in Python - Get the runtime path? | In a regular C++ exec, I can get the full path of the exec with
// Read path to executable
char cpath[PATH_MAX];
ssize_t count = readlink("/proc/self/exe", cpath, sizeof cpath);
But if I call it in a Python script, the same thing returns
/usr/bin/python3.6
What if i wanted the full /usr/bin/python3.6 /home/user... | Almost the same.
ifstream cmdline("/proc/self/cmdline");
std::string cpath;
std::getline(cmdline, cpath);
|
68,584,594 | 68,584,759 | Calling a protected constructor from a derived constructor | I have a base class with a protected constructor because this class should not be directly instantiated.
class Transform {
protected:
Transform();
~Transform() {}
public:
glm::vec3 some_member; // value will be initialized in the constructor
... // many other members
... |
I'm surprised that the base class constructor is not called by default in the derived constructor
If a base class has an applicable constructor, then it will be called. If there is no applicable constructor, then it must be called explicitly or the derived constructor will be ill-formed.
Some examples:
class Base1 {
... |
68,584,785 | 68,585,724 | Parallelization of dependent nested loops | I aim to compute a simple N-body program on C++ and I am using OpenMP to speed things up with the computations. At some point, I have nested loops that look like that:
int N;
double* S = new double[N];
double* Weight = new double[N];
double* Coordinate = new double[N];
...
#pragma omp parallel for
for (i... | The problem is that there is a data race during updating S[i] and S[j]. Different threads may read from/write to the same element of the array at the same time, therefore it should be an atomic operation (you have to add #pragma omp atomic) to avoid data race and to ensure memory consistency:
for (int j = 0; j < i; ++j... |
68,585,034 | 68,585,863 | Different versions of g++ have inconsistent result of overload resolution | When I used g++ 5.4.0, the sample code below worked as expected, but after I updated the g++ to 10.2.0, the result was changed.
I also tested the sample code on clang++ 11.0.1, and the result was the same as g++ 5.4.0.
I have searched some relevant questions but did not get a valid answer.
As I know, the overload funct... | This is definitely a GCC bug:
template <class T>
class Derive : public Base {
public:
operator const T&() const override {
using Y = std::string;
static_assert(std::is_same<T, Y>::value, "");
std::string static res;
res = Base::operator const Y&();
res = Base::operator const T&();
retur... |
68,585,661 | 68,587,854 | Given an array,find the number of element it can divide or divided by the remaining elements of the array | Input Array: int A={2,3,4,5,6} , array is not always sorted.
output Array:{2,1,1,0,2}
since we can see A[0] can divide 4 & 6 so it has output 2.
A[1] can divide only 6 ,it has output 1.
A[2] is divided by 2,so has output 1.
A[3] is not able to divide or being divided so has output 0.
A[4] is being divided by 2 & 3,s... | I'm not sure if it's possible for your problem but how about something like
namespace {
std::unordered_map<int, std::vector<size_t>> const factors{
{1, {1}},
{2, {1}},
{3, {1}},
{4, {1, 2}},
{5, {1}},
{6, {1, 2, 3}},
};
}
std::vector<int>solve(std::vector<int> &A... |
68,585,729 | 68,585,870 | Getting index of the current element in custom comparator function for `std::upper_bound` | I am trying to use std::upper_bound to find the upper bound of an element inside std::vector<double> xpositions. The index of each element in xpositions needs to be used to index a multidimensional array. I tried
upper_bound(xpositions.cbegin(), xpositions.cend(), value,
[](const double& element, const doub... | Elements in vector are stored in contiguous area, simple pointers arithmetic will do the job:
const auto index = &element - &xpositions[0];
also you need to capture xpositions by reference in your lambda.
If you want to use distance you have to pass non-const iterators of vector to upper_bound, and predicate should ta... |
68,586,341 | 68,587,299 | error in map with custom data structure as value | I am trying to define an undirected weighted graph with vertexes as a string but having trouble with adding edges. I tried this method with normal map<string, vector<int>> and it works fine but with map<string, vector<structure>> it doesn't work.
Here's my approach:
#include <bits/stdc++.h>
using namespace std;
class ... | I think you have a mixed array with hashmaps, in your case std::unordered_map is enough. We don't need to use array of std::unordered_map or std::vector<std::unordered_map<std::string, AdjListNode>>.
Then the fixed code:
class Graph {
int V;
map<string, vector<AdjListNode>> mp;
public:
Graph(int V);
void adde... |
68,586,930 | 68,587,950 | Enable static checks for constant evaluation | I like to have some sort of static (compile-time) check, if a type is initialised with a constant.
Below is a test code.
The type C is just a test to see if/when constant-evaluation is triggered.
The type D is more to be a real example of what I want to do:
Runtime: if D is initialized with the wrong value, the value ... |
D d{42}; // runtime assert, but should be compiletime error!
In the way you want it, it is not possible. Your method is fine - if your arguments are to be constant evaluated, do constexpr D d{42}. See explanation of is_constant_evaulated - I found https://gist.github.com/Som1Lse/5309b114accc086d24b842fd803ba9d2.
Y... |
68,587,980 | 68,588,081 | Forward declaration of two dependend classes with friend function | I have two classes. One depends on the other class and the other one contains a function that is friend to the first class. There's a lot of other stuff in this classes but this is what it boils down to:
class LightBase;
class Color
{
friend void LightBase::UpdateColor();
};
class LightBase
{
public:
... | It will work fine if you will change the arrangement a bit:
class Color;
class LightBase {
public:
void UpdateColor();
protected:
// Color has been declared
std::vector<Color> colors_;
};
class Color {
// LightBase has been defined
friend void LightBase::UpdateColor();
};
As ... |
68,588,088 | 74,532,230 | Is it possible to have create mock method for each argument from parameter pack? | Edit:
I have classes that receives messages:
class Foo {
public:
void receive(FooMessage& message));
// other messages
}
class Bar {
public:
void receive(BarMessage& message));
// other messages
}
and mock that test receiving those messages:
class Mock {
public:
MOCK_METHOD(void, receive, (FooMessa... | I managed to solve the problem by moving MOCK_METHODS to separate classes and using std::tuple in original class:
template<typename MessageType>
class SingleMessageTypeReceiver
{
public:
MOCK_METHOD(void, processMessage, (MessageType & e));
void subscribe(std::shared_ptr<MessageQueue> queue)
{
queue... |
68,588,461 | 68,592,058 | Why cannot concepts be passed to template meta-functions? | Consider any of the common type-level algorithms provided by libraries such as Boost.MP11, Brigand, etc...
For instance:
template<typename... Args>
struct TypeList;
using my_types = TypeList<int, float, char, float, double>;
constexpr int count = boost::mp11::mp_count_if<my_types, std::is_floating_point>::value;
// t... | The literal answer is that we have template template parameters but not concept template parameters, so you can't pass a concept as a template argument.
The other literal answer is that it was never part of the original concepts proposal and nobody has put in the effort to suggest it as an extension (although I've been... |
68,588,726 | 68,588,827 | Complex constant i in C++? | When writing C++ code, rather than:
double a, b;
...
std::complex<double> z = a + b * std::complex<double>(0, 1);
I would prefer to write something like:
std::complex<double> z = a + b * i;
I can see that C99 has macro I (https://en.cppreference.com/w/c/numeric/complex/I), but it can't be use with std::complex:
std::... | The custom literal i (e.g. 1i), see example in https://en.cppreference.com/w/cpp/numeric/complex
#include <complex>
using namespace std::complex_literals;
std::complex<double> z1 = 1i * 1i;
|
68,588,780 | 68,588,899 | What for is equals sign after a type in specialization struct? | I faced such a code:
template <int = 42>
struct Foo{
int x; };
Does it have sense, or it's complete nonsense?
| This is equal to
template <int I = 42>
struct Foo {
int x;
}
so a non-type template parameter of type int that is defaulted to 42 but as nobody is using I, it does not have any effect on the contents of the struct.
When declaring Foo as
Foo foo {};
this will result in Foo<T> being Foo<42> but one could also declare... |
68,588,847 | 68,589,044 | How do I call the constructor of a class' member? | I wanted to declare a QGraphicsView which has a previously declared member as an argument of the constructor, but the compiler interprets it as a function.
(Code for reference)
class Widnow : public QMainWindow
{
Q_OBJECT
// constructors, member functions, etc...
private:
Ui::Widnow *ui;
QTimer timer0... | The C++ compiler thinks that it is a method declaration where "wiev" as method that returns an instance of QGraphicsView. Use this way
class Widnow : public QMainWindow
{
private:
QGraphicsScene gaem;
QGraphicsView wiev; //this gets interpreted as a function
public:
Widnow() : wiev(&gaem)
{}
};
|
68,589,131 | 68,590,267 | Initialize static member of class which is itself a class in subclass | I have two classes of which one is a subclass of the other. The classes are layed out as a singleton. So the base class contains a static member which is set to the only instance of that class and can be refered to by a getter function (not relevant here, so I left it out). I now want to create the subclass in global c... | You need pointers or references for polymorphism. A LightBase member can only store a LightBase not one of its subclasses. Hence, it is not really the definition that is the problem, but rather your declaration is already off. In any case the definition must match the declaration.
You can use a std::unique_ptr:
#includ... |
68,589,314 | 68,875,532 | How to define a specialized class method outside of class body in C++? | I have a template class A<T> and its specialization for integral arguments. And both the class and its specialization declare the method foo(), which I would like to define outside of class bodies:
#include <concepts>
template<class T>
struct A { static void foo(); };
template<std::integral T>
struct A<T> { static v... | I'm pretty sure that both the MS and Clang compilers are in error here and GCC is compiling your code correctly. Until these bugs are fixed in the other compilers, I suggest to continue using the concept pattern instead of going back to outdated methods. Simply work around the bug using an additional class:
#include <c... |
68,589,407 | 68,590,927 | How do hello_xr (Openxr) sample retrieve the Vulkan API pointer for the Oculus Quest? | I always thought that on android platform we were supposed to load the pointer to Vulkan library using dlopen() and dlsym() (something like that:
libVulkan = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL);
vkEnumerateInstanceExtensionProperties = reinterpret_cast<PFN_vkEnumerateInstanceExtensionProperties(dlsym(libVulka... | When you want to call a function from some library, there are two ways to do it:
Tell the compiler you want to use the library. Then, just use the function.
Don't tell the compiler you want to use the library. Instead, call dlopen to load the library and then call dlsym to look up the functions in the library, and cal... |
68,589,463 | 68,589,494 | Why is it showing Run-time error in 3Sum problem on LeetCode? | I was solving this 3Sum problem on leetcode. The question states that:
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
This solution which I code... | nums.size() returns an unsigned integer, so (nums.size())-2 will be some large value due to wraparounding when nums.size() is less than 2.
You should use static_cast<int>(nums.size())-2 instead of (nums.size())-2 and static_cast<int>(nums.size())-1 instead of nums.size()-1.
|
68,589,509 | 69,532,240 | Change SACL on Named Pipe | I have C++ code that change SACL of a folder as it is expected. The things become strange when I want to change SACL of an exsiting Named Pipe, the code executes successful but when I check it via Get-Acl -Path \\.\pipe\lsass -Audit | fl it returns error number 87 which is ERROR_INVALID_PARAMETER and SACL does not work... | Actually, the code is doing it's job. Then you compile and run this, you will change SACL of a pipe as well as a file. My mistake was in this part:
explicit_access_listSACL[0].grfAccessPermissions = ACCESS_SYSTEM_SECURITY;
Which means that logs will be generate only when user will request ACCESS_SYSTEM_SECURITY rights... |
68,590,270 | 68,600,489 | Weird results when printing not existing list elements in C++ | So I am learning C++ at the moment and got some really weird results when I tried printing out element of a list of integers, that are actually out of range. (Don't ask why, I stumbled on that by accident)
This is my Code:
#include <iostream>
using namespace std;
int main() {
int nums[0] = {};
for (int i = 0... | The result of compiling your code to (my invented) machine code is something like this.
1 main:
2 reserve basePtr, 2 ; reserve 2 slots on the stack, and store in basePtr
3 mov nums, basePtr ; num points at the first local variable
4 mov [nums], 0 ; int num[1] = {0} - set num to zero
5 ... |
68,590,289 | 68,591,614 | Why is it possible to add functions to external library to access internal data | this week i needed a feature in our internal static library but i was too lazy to recompile the library so i just modified the header file and was able to get access to private members. The same was possible to do when the library is a Windows dll.
An example header might look like:
#pragma once
#ifdef DLL
#define DLL... | Changing a header in this manner and recompiling a part of the program with the changed header results in a violation of the "One Definition Rule" and thus is undefined behaviour.
This kind of violation could have been detected by a C++ implementation. Such detection is not very challenging technically. Basically, the ... |
68,590,407 | 68,590,599 | How can I remove a newline from inside a string in C++? | I am trying to take text input from the user and compare it to a list of values in a text file. The values are this:
That line at the end is the cursor, not a straight line, but it doesn't matter. Anyway, I sort by word and produce the values, then check the values. Semicolon is a separator between words. All the data... |
My efforts remove only the new line, but not the carriage return
The newline and carriage control are considered control characters.
To remove all the control characters from the string, you can use std::remove_if along with std::iscntrl:
#include <cctype>
#include <algorithm>
//...
lookContents.erase(std::remove_if(... |
68,590,453 | 68,590,697 | The problem of libstdc++‘s implementation of std::declval | Unlike libc++ or MSVC-STL that only declares the function signature of std::declval, libstdc++ defines the function body for std::declval, and uses static_assert internally to ensure that it must be used in unevaluated contexts:
template<typename _Tp, typename _Up = _Tp&&>
_Up
__declval(int);
template<typename _Tp>
_... | The example is ill-formed, because the restriction for std::declval is actually on the expression where declval is named, not on whether the abstract virtual machine would actually evaluate its call.
The requirement on std::declval is [declval].2
Mandates: This function is not odr-used ([basic.def.odr]).
where "Manda... |
68,590,640 | 68,599,059 | Inspect environment variables of a process from Visual Studio | In Visual Studio, I want to inspect environment variables of a process launched from it, like in Process Hacker or Process Explorer.
VS gives very advanced debugging capabilities, probably I'm missing something.
Background.
I've got a C++ program built by Visual Studio 2019.
It fails if launched from the Visual Studio ... | In the debug mode, you can save a process dump (Debug - Save Dump As - Minidump with heap) and then inspect this .dmp file with a hex editor (or Notepad if file is small) searching for an environment variable name.
|
68,590,986 | 68,593,664 | How to be notified if someone tries to create a mutex which you already use? | Given my set of 2 different applications, named App1.exe and App2.exe.
When both try to create a mutex with the same name, as explained below.
In App1.exe, which starts before App2.exe:
int main()
{
std::wstring m = L"Local\\MyMutexName";
HANDLE hMutex = CreateMutexEx(NULL, m.c_str(), CREATE_MUTEX_INITIAL_OWN... |
is there a way for App1.exe, which was started before App2.exe, to be notified or receive an event that App2.exe, which started after App1.exe, tried to create a mutex with the same name?
No, there is no such event/notification.
I need to know when App2.exe accesses the mutex of App1.exe so that I will execute a spe... |
68,591,212 | 68,591,247 | C++: for-loop is optimized into endless loop if function return statement is missing - compiler bug? | Take the following minimum example:
#include <stdio.h>
bool test(){
for (int i = 0; i < 1024; i++)
{
printf("i=%d\n", i);
}
}
int main(){
test();
return 0;
}
where the return statement in the test function is missing. If I run the example like so:
g++ main.cpp -o main && ./main
Then the ... | Your function is declared as bool test(), but your definition never returns anything. That means you've broken the contract with the language and have be put in a time out in undefined behavior land. There, all results are "correct".
|
68,591,370 | 68,591,670 | std::condition_variable memory writes visibility | Does std::condition_variable::notify_one() or std::condition_variable::notify_all() guarantee that non-atomic memory writes in the current thread prior to the call will be visible in notified threads?
Other threads do:
{
std::unique_lock lock(mutex);
cv.wait(lock, []() { return values[threadIndex] != 0; });
... | I guess you are mixing up memory ordering of so called atomic values and the mechanisms of classic lock based synchronization.
When you have a datum which is shared between threads, lets say an int for example, one thread can not simply read it while the other thread might be write to it meanwhile. Otherwise we would h... |
68,591,487 | 68,603,141 | Boost write_xml to vector wrapped in back_insert_device yields 0 sized vector | In the code below, why does the vector 'v' have a size of 0? The code works fine if passing write_xml a stringstream. But I'd rather not have to pay the cost of string allocation when, eventually, dumping the text XML.
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#incl... | You forget to flush the stream. You can os.flush() or just let the destructor handle it:
Live On Coliru
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.... |
68,591,617 | 68,591,837 | C++ STL: Why allocators don't increase memory footprint of containers? | The following code snippet(see on godbolt) shows that big allocators won't increase the memory footprint of STL containers, but big comparators will. Why is it the case?
// compiled with x86-64 gcc 10.3, -std=c++17
#include <functional>
#include <iostream>
#include <memory>
#include <set>
struct MyLess : public std::l... | Your allocator is not being used.
By default, std::set receives std::allocator<int>, but it needs to allocate some kind of nodes, not ints. It uses std::allocator_traits::rebind to get a different allocator for its internal node type.
Pre-C++20 std::allocator has a rebind member type, which you inherit, and which std::... |
68,591,704 | 68,591,805 | Accessing member of class through shared pointer | I am facing a issue, when I try to access members of a class through a shared pointer.
The program runs fine and gives the expected output: "Name: Michel". But when I comment the line marked as COMMENT_THIS_LINE, it gives some junk value instead of Michel. Can anybody explain this behavior, and how I can get the correc... | The important bits are this:
std::string TestShared::getName(void)
{
return m_name;
}
And this:
Another an;
an.name = ts->getName().c_str(); // (*)
return an;
getName() returns a copy of the private string. c_str() returns a pointer to that temporary's internal character array. an.name stores that pointer, whic... |
68,591,739 | 68,606,693 | What factors determine which version of glibc is required for binary built with g++? | I manage a complex C++ project
I am getting field reports that a binary built on one system will not run on another
system because of glibc version mismatch.
I just want to verify: is the version of glibc required by the binary completely determined by which version of g++ is used to compile it?
In this case, the binar... |
I just want to verify: is the version of glibc required by the binary completely determined by which version of g++ is used to compile it?
Not at all. The version of GLIBC required at runtime is determined by several factors:
The version of GLIBC used at link time.
The features of GLIBC actually used (which in turn ... |
68,592,003 | 68,593,374 | Create Linegrid in Vulkan (line in x and y direction is missing) [fixed] | i created a method to create a 3D line grid.
i orientated my code on the example of 3D Game Programming with DirectX 12.
When I run my vulkan based application, I get a line grid, but the last line in x and y direction are missing (Link to image).
Can anyone help me fixing this problem.
My first thought are problems wi... | I mean, you have six indices per quad. Since it is a line list, that means three lines. Your second line is degenerate, so actually two lines. But quad is normally made of four lines. So unless the adjacent quad shares the extra lines, there will be nothing. And for the border quads, there are no adjacent quads. So the... |
68,592,023 | 68,592,118 | C++ Number Pattern Solution Using only Loops | Hello I tried searching the website to see if there are any similar questions, but I haven't found any. I do apologize if there is something similar. I'm supposed to code a sort of number pattern given an input as shown below without using lists, vectors, arrays, etc and only with loops (for, while, do-while)
Input: 5
... | You will have to print i i-1 times instead of once.
int count = 1;
int counter = 1;
while (count <= a) {
cout << count << " ";
count++;
}
cout << endl;
for (int i = 1 + counter; i <= a; i++) {
for (int k = 1; k < i; k++) // print i (i-1) times
cout << i << " ";
for (int k = i; k <= a; k++)
... |
68,592,063 | 68,592,235 | C++ Multidimensional Array Help: Iterate through to find user input & return if found it's other attributes | So I am extremely new to C++. I am not sure exactly what I am doing wrong. I have 6 items with 3 values each. A name, a customer id, and a number of punches. Essentially I want to be able to iterate through customer input to ensure that the ID they entered matches items in the second column and then return a string wit... |
You should use a structure to group some values.
You should remove the extra ; from the if and for lines.
You should use >> operator instead of << with cin.
You should declare the variable customerinput.
You will need << opetator between the strings and data to print.
It looks like the loop with j is not needed and ha... |
68,593,166 | 68,629,279 | How to get image with transparent background from FLTK Fl__Image__Surface? | I want to draw string or char (offscreen) and use it as Fl_Image or Fl_RGB_Image.
Based on this link I can do that easily with Fl__Image__Surface. The problem with Fl__Image__Surface is that it does not support transparency when I convert its output to image (Fl_RGB_Image) using image() method. So is there any way I ca... | If you prefer to do it manually, you can try the following:
#include <FL/Enumerations.H>
#include <FL/Fl.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Device.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Image.H>
#include <FL/Fl_Image_Surface.H>
#include <FL/fl_draw.H>
#include <cassert>
#include <vector>
Fl_RGB_Ima... |
68,593,206 | 68,621,715 | glfwCreateWindow() fails after installing cuda toolkit | My program that uses glew and glfw used to work finely on Ubuntu. I then installed cuda toolkit, and suddenly it fails because glfwCreateWindow() does not return a proper pointer to a GLFWwindow object.
I installed the cuda toolkit using the instructions in here:
https://medium.com/geekculture/installing-cudnn-and-cuda... | ok, so as @t.niese suggested in the comments, the solution was simply to restart the computer. I am relatively a beginner in Linux, but I heard that one advantage of Linux over Windows, is that with the former, one does not have to reboot after installing a package/software. Apparently, this is not always the case.
|
68,593,547 | 68,593,800 | How I can write in text file using CPP | Actually, I has four dimensional data with value into a text file "fourdimensionalM.txt" and I want to read data from txt file "fourdimensionalM.txt" which has
0 0 0 2 1
0 0 2 0 2
0 1 0 0 3
0 1 1 1 4
0 1 2 0 5
and want to write into new txt file the where the four dimensional matrix has no number. I write the code but... | If I understand your question correctly, you are given a file with select points values for R^4 and you need to produce the full hypercube with zeroes for places where you do not have a point.
If you can assume the input file is sorted lexicographically, you can do the following:
int ti, tj, tk, tl, tv; // target coord... |
68,593,838 | 68,619,163 | nettle curve25519 key exchange | I'm trying to understand how to implement key exchange using nettle's curve25519 functions.
I'm writing an software that establishes encrypted TCP connection with public key based authentication. The client and server programs share the same code base.
This is an hobby project to learn network and crypto programming. :... | Elliptic curves, generally, are used for key 'agreement' rather than key 'exchange'.
I don't know how much you know about this so I'll briefly explain:
RSA - we generate a random symmetric key, encrypt it with the public key of the recipient, who themselves later decrypts and uses it.
ECC (Elliptic curve crypto) - we... |
68,594,793 | 68,595,093 | Pass different classes as argument to a member function in c++ | I would like to pass different classes as an argument to a function, but I am not sure how to do it in c++. The classes I want to pass have member functions with the same name. I wrote my program in JavaScript:
class Calculator {
constructor(value) {
this.value = value;
}
// here I want to pass in ... | There's a few different to ways to tackle this problem depending on the specific needs of your program.
Here are the two techniques that are most commonly used:
1. Compile-time polymorphism with templates
This is appropriate, and generally preferable, when the type of the command is known at the call site. It involves ... |
68,594,813 | 68,594,890 | Invalid conversion from const char to int error on my project | #include <iostream>
using namespace std;
int
main ()
{
int number1, number2, sumatotala, choose, add, multiply;
add = "add";
multiply = "multiply";
cin>>choose;
cin>>number1;
cin>>number2;
if(choose = add) cout<<number1+number2;
if(choose = multiply) cout<<number1*number2;
return 0;
}
This i... | add = "add";
multiply = "multiply";
Here you need to either use numbers as values (because these are integer variables) or if you need them as strings, you have to remove them from the above line and write them like this:
std::string add = "add";
std::string multiply = "multiply";
|
68,594,899 | 68,596,017 | How do I get G++ to link my header files on Linux? | I have had this problem for a while where my Linux system can't seem to link any header files(and yes, I have checked: they all exist in the right locations). Here is a basic script called HelloWorld.cpp:
#include <iostream>
#include </usr/include/string.h>
int main(){
string hi = "Hello WOrld!";
return 0;
}
And this... | This seems like the best answer posted so far:
string.h is for C-style string routines like strlen. You want to include (no .h), and use std::string hi = "Hello World!"; -jkb
Thank you for answering my question.
|
68,595,094 | 68,603,095 | Read a sub json using boost property tree | I need to read a field in a JSON file which itself is a JSON. I need to read the JSON field in one go. Is there any way available? Sample JSON I am trying to read is provided below.
enter code here
{
"responses": [
{
"id": "1",
"status": 200,
"headers": {
... | The body is not a string.
So, getting the child object would be in order:
for (auto const& v : jsonBatchResponse.get_child("responses")) {
std::string strID = v.second.get<std::string>("id", "");
std::string strStatus = v.second.get<std::string>("status", "");
ptree const& body = v.second.get_chi... |
68,595,106 | 68,595,229 | Can I replace a single character in a string with 2 characters? | #include <algorithm>
#include <string>
void foo(std::string &s) {
replace(s.begin(), s.end(), 'S', 'TH');
}
I want foo(s) to replace each S in s with the two characters TH. For example
std::string s = "SAT";
foo(s);
std::cout << s << "\n" // THAT
However, the definition of foo gives me an error.
Error (active) ... | std::replace cannot do it, but you can use std::regex_replace instead.
#include <regex>
std::string s = "SAT";
s = regex_replace(s, std::regex("S"), "TH");
std::cout << s << "\n"; // output: THAT
|
68,595,189 | 68,595,815 | How does this alignment works? ((n + ZBI_ALIGNMENT - 1) & -ZBI_ALIGNMENT) | I'm trying to understand how this alignment works. It should align an uint32 address to its nearest 8 byte aligned address
static inline uint32_t
ZBI_ALIGN(uint32_t n) {
return ((n + ZBI_ALIGNMENT - 1) & -ZBI_ALIGNMENT);
Let's take n=10, and ZBI_ALIGNMENT=8. The nearest address should be 16
returns ((10 + 8 -1) ... | The key to this formula is that it is only valid if ZBI_ALIGNMENT happens to be a power of two, which is not a big deal because alignment requirements tend to fulfil that criteria.
A number being aligned to (aka being a multiple of) a power of two means that all bits smaller than that power of two are set to 0. You can... |
68,595,374 | 68,595,542 | Clear map of dynamic values in C++ | I've seen many sites talking about the correct way to implement a d'tor for a class that holds a map.
But not for the case where the values of the map themselves are dynamically allocated.
For example, let Manager be a class which hold map<int, User*> where User is some class which I'll allocate dynamically later.
By t... | Don't use pointers when you do not have to. The std::map already manages the lifetime of its elements for you:
struct User {
std::string name;
int id;
static int id_counter;
User(const std::string& name) : name(name),id(id_counter++) {}
};
struct manager {
std::map<int,User> users;
User& regis... |
68,595,453 | 68,596,104 | Why is Sublime Text not executing my program? Compiler issue? | Sublime Text not executing code: I have written a simple program in C++ that works perfectly fine in the Command Prompt and Visual Studio Code, yet fails to initiate any output when written in Sublime Text. The only output that it executes is, [Finished in 438ms] or something along those lines... Any help would be much... | It appears that your sublime installation may not be configured properly for c++ compilation. You have to hook up the Sublime to a compiler on your machine.
There are many ways to do so depending on your setup, but here is an example of one method.
https://www.programmersought.com/article/50631946316/
|
68,596,362 | 68,596,419 | Accessing variables from a struct included in a Class | I have a class, which includes a Struct. I've declared two variables of the given class and I can't access the variables from the struct Variables.
The class:
class Game
{
public:
Game( class MainWindow& wnd );
Game( const Game& ) = delete;
Game& operator=( const Game& ) = delete;
void Go();
private:
... | You don't need to prefix the variables with a type when you use them in an expression:
left.start = 100;
... since left and right are the variable names here.
|
68,596,373 | 68,596,560 | Inserting thread::id and class instance in a map | I have a class:
class IOWorker {
std::thread thread_;
boost::asio::io_service ios_;
boost::optional<boost::asio::io_service::work> work_;
Callback callback_;
// Map of thread::id and this class' instance
typedef std::map<s... | This seems way more complicated than it has to be.
If, as it appears to be the case, you only need to access the map at from thread::this_thread, the language already has a map<thread_id, T> built right in: thread_local.
class IOWorker {
std::thread thread_;
boost::asio::io_service ... |
68,596,494 | 68,596,555 | what really mean by Type Punning is an application of union? | what really means by type-punning in the union?
for example
#include <iostream>
using namespace std;
union test {
int x;
float y;
};
int main()
{
test t;
t.y = 1.5;
cout<<t.x;
return 0;
}
gives output as 1069547520
what does this value represent? how to predict this?
| Type-puning means reinterpreting the underlying bytes of one type as bytes of another. Unions can be (mis)used for this because all members share the same memory location.
Reading from non-active union member is undefined behaviour in C++.
It is allowed in C and GNU C++.
The correct C++ approach for trivially copyable ... |
68,596,544 | 68,596,590 | Why does it make a difference in the result whether I call the function "foo" or not? | I tried running the code with and without calling the function "foo" and it yields different results. I thought because the function was empty that it wasn't going to make a difference in the result but apparently I was wrong.
#include <iostream>
using namespace std;
#include <string>
class Product
{
private:
... | Because calling foo(p1, p2); causes a copy of p2 to be made, invoking the Product copy constructor and adding to total. This is because void foo(Product&, Product) takes its second parameter by value.
|
68,596,894 | 68,597,077 | How do i store a binary number in an array? | Ok, so i been working on this right here that is intended to be part of a encryption software that works synonymously like 2fa
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int RGX;
int box[32];
srand (time(NULL));
RGX = rand() % 100... | You can use a std::bitset instead of manually extracting bits and the array:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <bitset>
int main() {
srand (time(NULL));
int RGX = rand() % 100000000 + 9999999;
std::cout << "Random Generated One Time HEX #: \n";
std::cout << std::hex ... |
68,597,160 | 68,597,220 | Conceptualized `operator auto` in C++20 | Starting from C++20 we can precede auto keyword with the name of the concept to limit possible types. And in particular this combination is possible in class conversion operator auto, e.g.
template <typename T> concept x = true;
struct S
{
operator x auto() { return 2; }
operator auto() { return 1; }
};
int m... | This conversion function:
operator auto() { return 1; }
Means exactly the same as this converison function:
operator int() { return 1; }
We're deducing the return type from 1, this isn't a function template.
This conversion function:
operator x auto() { return 2; }
Means roughly the same thing as:
operator int() { ... |
68,597,562 | 68,597,643 | boost r-tree packing algorithm during insertion | The question is about the boost::geometry::index::rtree:
I know that the constructor: rtree(Iterator, Iterator) will create the tree using the packing algorithm, as stated in the documentation. I'm wondering whether the insertion which accepts the iterators: insert(Iterator, Iterator) will also use the packing algorith... | The packing algorithm is used if the R-tree is created from items given to the constructor. The balancing algorithm is used during splitting of nodes i.e. on insert() and remove().
So the answer is no. During insertion the packing algorithm is ignored.
|
68,597,951 | 68,601,293 | Connect not picking up variable changes | I am trying to program an app which includes an animation. At the moment I want to start/stop the animation with a click on a button.
My solution includes two connects:
The first connect registers a click on the button and changes the value of the boolean play
The second connect links a timer to the animation step an... | consider that in lambda body only a local name (variable) captured by reference(&) is allowed to be modified.
& before play means that it should be stored as reference, and if you don't put & before play means that it
should be stored as copy(implicitly will be captured by value).
by default lambda acts like const ... |
68,597,986 | 68,598,017 | no type named asio in namespace boost | I am attempting to write an asynchronous TCP server using boost::asio.
The using Tcp = boost::asio::ip::tcp directive is working correctly. However if I define
using Asio = boost::asio it doesn't seem to work. I get the error no type named asio in namespace boost. why is that?
Why is that?
#include <iostream>
#include ... | You need to do this:
namespace asio = boost::asio;
using foo = is for types, and namespaces are not types.
Ref: https://en.cppreference.com/w/cpp/language/namespace_alias
|
68,598,204 | 68,598,234 | "identifier not found" when trying to declare a list iterator | I am creating a Set class using the standard list container. When I declare the list iterator iter, I get an error:
C3861 'iter':identifier not found
I have found a few examples of other people declaring list iterators in this way, but I may be misunderstanding something about iterators.
#include <list>
#include <ite... | The compiler gets confused by that line because it doesn't know what list<T> will be before actually specializing the class with some T.
More formally you would say that list<T>::iterator is a dependent name.
The solution is to add a hint in form of the typename keyword to specify that the construct will refer to some ... |
68,598,645 | 68,599,756 | Declaring a pointer to a temporary buffer on the stack in a single line? | In the following code, getDriverNames() is declared as getDriverNames(char **names, long maxDrivers), where the names is required to be an array of 32-character string buffers to receive available driver names (I only care about the first available driver).
Is there a way to declare the names variable without the inter... | The getDriverNames() function expects a pointer to an array of pointers to arrays. It is going to follow the pointers. So no, there is no way to declare all of that inline, you need the individual arrays to be allocated before you can take their addresses.
names buffer
----- --------------------... |
68,598,784 | 68,599,190 | How to access template specialization objects through variables | The title may not express my meaning very clearly
Created a template class Map which the type is enum VertexType and specialize them
exist a vector container the VertexType
access different Map object through the element in vector
Question: how to access different template object through a variables instead of use swi... | Obvious Answer: No, template parameters are evaluated at compile-time. They cannot hold runtime values inside them (In your case, i is a runtime variable). As such, there is no straightforward way to tackle your problem.
Alternative: Well, technically, in your case, the closest you could do to achieve something like th... |
68,599,123 | 68,607,897 | Omnidirectional shadows for directional light | when using a shadow map, the light projection (orthogonal) is used in the following way (similarly for other planets):
const glm::mat4 lightProjection = glm::ortho(-saturn->GetRadius() * 3.0f, saturn->GetRadius() * 3.0f, -saturn->GetRadius() * 3.0f, saturn->GetRadius() * 3.0f, camera.GetNear(), camera.GetFar());
... | So guys, I solved the problem...
The idea is to render a scene component (planet, its satellites, rings, etc.) into a shadow map, then immediately into a regular buffer, and then clear the shadow map (depth buffer) so that the planet closest to the sun does not cover all the others, etc.
Cleaning is necessary because o... |
68,599,177 | 68,599,468 | What does * when using nullptr mean? | what does the * mean in
int* p = nullptr;
Also, it would be helpful if anyone can example what nullptr means. Is it equivalent to null? Sorry, I recently started learning c++;
|
what does the * mean in
int* p = nullptr;
* refers to a pointer-to-an object which holds a specific location/address in memory, in your case it is a pointer-to-an-int and so it refers to the address of an integer.
Also, it would be helpful if anyone can example what nullptr means. Is it equivalent to null? Sorry, I ... |
68,599,645 | 68,599,975 | Will reading out-of-bounds of a stack-allocated array cause any problems in real world? | Even though it is bad practice, is there any way the following code could cause trouble in real life? Note than I am only reading out of bounds, not writing:
#include <iostream>
int main() {
int arr[] = {1, 2, 3};
std::cout << arr[3] << '\n';
}
| As mentioned, it is not "safe" to read beyond the end of the stack. But it sounds like you're really trying to ask what could go wrong? and, typically, the answer is "not much". Your program would ideally crash with a segfault, but it might just keep on happily running, unaware that it's entered undefined behavior. Th... |
68,599,687 | 68,599,855 | Can anyone help me find what is wrong with my code? | I wrote the Quicksort code in c++ but it is not working. can anyone tell me what is wrong with this code? Whenever I am giving the input, it does not return any output.
example:
5
5 4 3 6 2
Process exited after 5.997 seconds with return value 3221225725
Press any key to continue . . .
why is it not returning any outpu... | It should be while(arr[i]<=pivot) instead of while(i<=pivot) same goes for j
int partition(int arr[], int i, int j)
{
int pivot=arr[j];
while(i<j) {
while(arr[i]<=pivot) {
i++;
}
while(arr[j]>pivot) {
j--;
}
if(i<j) {
swap(&arr[i],&... |
68,599,714 | 68,600,058 | Best way to find 'quite good' numbers up to 1 million? | I am working on an assignment involving 'quite good' numbers. The task describes them as:
"A "quite good" number is an integer whose "badness" – the size of the difference between the sum of its divisors and the number itself – is not greater than a specified value. For example, if the maximum badness is set at 3, ther... | If f is a factor of n then so is n/f (although when f is the square-root of n, f and n/f are the same factor). So you can make the code a lot faster by counting factors only up to sqrt(number), and then when you find one also include the matching factor number/factor (except for the square-root case).
for (int factor =... |
68,600,510 | 68,601,085 | How to implement the two member functions (push_front and the destructor)? | I am trying to implement two member functions, i.e., push_front and the destructor. I have written the code of the push_front function. But I seem, I am doing wrong anywhere. How can I fix this issue? How can I insert a node in front of Linked-List properly?
template <typename T>
class Node {
public:
Node():next_p_... | The first Node constructor takes the value and next pointer, use that to create the new node in one step.
You shouldn't dereference head_ptr_ when using it as the next pointer. It's already a Node*, which is the correct type for head_ptr_.
void push_front( T v ){
Node *new_node = new Node(v, head_ptr_);
... |
68,600,593 | 68,601,027 | sum up vectors in a matrix, element by element in c++ | Is there a simple method in C++ that allows to sum up the vectors componing a matrix element by element? I mean, if I have the matrix M[3][4], I want the sum[3] vector with this components:
sum[0]=M[0][0]+M[1][0]+M[2][0]
sum[1]=M[0][1]+M[1][1]+M[2][1]
sum[2]=M[0][2]+M[1][2]+M[2][2]
I find out that exists this method f... |
Is there a simple method in C++ that allows to sum up the vectors componing a matrix element by element? I mean, if I have the matrix M[3][4], I want the sum[3] vector with this components:
sum[0]=M[0][0]+M[1][0]+M[2][0]
sum[1]=M[0][1]+M[1][1]+M[2][1]
sum[2]=M[0][2]+M[1][2]+M[2][2]
Unfortunately, there is no simple ... |
68,600,649 | 68,600,953 | How to get the height from the top of character to its base line (i.e, its actual ascent) in QWidget? | I am experimenting to build a tool that can display modified text (i.e, with some additional stroke) on screen using QWidget. So, to put the stroke in its correct position, I need to know the ascent height of the character the stroke is being put on.
And I'm a tad stuck on retrieving the actual ascent of a character. I... | You can use QFontMetrics::boundingRect. The QRect returned will have its origin at (0, 0) with the ascent for character c represented by...
-QFontMetrics::boundingRect(c).top()
and, similarly, the descent by...
QFontMetrics::boundingRect(c).bottom()
|
68,600,793 | 68,600,812 | incrementing static member of a class in main - C++ | I am getting this error error: expected unqualified-id before ‘++’ token 29 | std::cout<<x::foo::++z;
basically I am trying to increment z from foo in main
#include <iostream>
namespace x {
class foo {
public:
void bar1(foo& f) {
++x;
}
friend void bar2(foo& f);
int x;
int y;
st... | You have to specify the operation first (the ++ operator), then specify the object on which to call the operator (the x::foo::z):
// Increment the x::foo::z
++x::foo::z;
// Equivalent to ++(x::foo::z)
|
68,601,094 | 68,601,150 | right operand of comma operator has no effect -wunused variable | While compiling simple cpp file I got an error. I want to write a function that changes celcius to farenheit.
double przelicznik(double n)
{
n = 1,8 * n + 32;
return n;
}
Also it doesn't give me a correct result.
| The code is.
n = 1, (8 * n + 32)
The comma operator is a fairly uncommon mechanism where multiple expressions can be done in sequence.
correct code.
n = 1.8 * n + 32;
|
68,601,659 | 68,601,827 | Why does double negation change the value of C++ concept? | A friend of mine shown me a C++20 program with concepts, which puzzled me:
struct A { static constexpr bool a = true; };
template <typename T>
concept C = T::a || T::b;
template <typename T>
concept D = !!(T::a || T::b);
static_assert( C<A> );
static_assert( !D<A> );
It is accepted by all compilers: https://gcc.god... |
Here the concept D is the same as the concept C
They are not. Constraints (and concept-ids) are normalized when checked for satisfaction and broken down to atomic constraints.
[temp.names]
8 A concept-id is a simple-template-id where the template-name is
a concept-name. A concept-id is a prvalue of type bool, and do... |
68,601,692 | 68,607,779 | Symbol lookup error when calling pango_cairo_create_layout |
Noob alert! I'm not exactly competent with C/C++ programming
Hi, I'm working on a C++ NodeJS addon, in which I'd like to use Cairo/Pango, but I'm having a number of linking issues. I can reasonably assume they're linking issues, as I had a similar one, calling a Cairo function. I was able to resolve it by adding -lca... | Add pangocairo to your pkg-config invocation:
LIBS=$(shell pkg-config --cflags --libs cairo pango pangocairo)
It's a separate library and you are missing it.
|
68,601,994 | 68,602,028 | Assigning strlen(s) value to an integer is varying the output, WHY? | char s[100];
cin>>s;
int x=strlen(s);
if((x-2)>=9)
cout<<s[0]<<x-2<<s[x-1]<<endl;
else
cout<<s<<endl;
output for inputting 'a' is 'a' BUT
char s[100];
cin>>s;
if((strlen(s)-2)>=9)
cout<<s[0]<<strlen(s)-2<<s[strlen(s)-1]<<endl;
else
cout<<s<<endl;
OUTPUT of this program for same input 'a' is a18446744073709551... | strlen returns size_t - an unsigned type.
According to integral conversion rules, the type of strlen(s)-2 remains unsigned, which overflows for any strlen(s) less than 2, wrapping around and giving a large positive value (264-1 in your example).
When you first assign strlen(s) to an int variable, the value is converted... |
68,602,236 | 68,602,618 | Faster way to copy vector elements to different structure of vector C++ | I have a one dimension vector of integer that stores table data. Which I want to transform into a multidimensional vector (e.g. a vector of int vectors).
This is what I tried:
std::vector<int> lin_table = {1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4, 1,2,3,4}
std::vector<std::vector<int>> multi_table;
int num_cols = 4;
for (int... |
I have a one dimension vector of integer that stores table data. Which I want to transform into a multidimensional vector (e.g. a vector of int vectors).
Since you insist on performance, as already stated many times here before, it is better to create a class that wraps around a std::vector which emulates what a two-... |
68,602,375 | 68,793,289 | Is there any rule about why is the redefinition of the enumerator ill-formed? | Consider this example
enum class A{
a = 0,
a = 1
};
The compilers will report an error, which is the "redefinition of enumerator 'a'". However, [basic.def.odr#1] does not have any requirement for the enumerator
No translation unit shall contain more than one definition of any variable, function, class type, e... | Original answer
Yes, as of now, the One Definition Rule in the C++ standard doesn't include enumerators.
However, the "the second a is a redeclaration of the first a" explanation doesn't work too.
From [dcl.enum#nt:enumerator-list] we can know that an enumerator-list is a list of enumerator-definition, so they're all d... |
68,602,470 | 68,602,645 | Why accessing variable declared locally from outside is working? | In tree, while taking input (inside takeInput function), tree node was made using dynamic allocation, but I tried doing it statically, but as tree node were declared inside a function locally it should have not worked because its a local variable (I was expecting a error). But Why am I able print it even after that:
NO... | Your code is equivalent to
A foo() {
A a;
a = bar();
return a;
}
a is just copied into the return value (That copy might be avoided too). Replace A with treeNode<int> and the semantics remain the same.
Why then the dynamic code?
I'm guessing the code version using dynamic allocation was probably coded up t... |
68,602,484 | 68,602,512 | G++ raise compile errors instead of warnings for narrowing conversions | I want to get compile errors instead of warnings for this code:
#include <iostream>
int main(int argc, char ** argv)
{
float a = 1.3f;
int b = 2.0 * a;
std::cout << b << "\n";
}
If I compile it with:
g++ test.cpp -o test
I have no errors.
But If I compile the same code with:
g++ test.cpp -o test -Wconve... | Use -Werror= to treat specific warnings as errors only:
g++ test.cpp -o test -Werror=conversion
|
68,603,478 | 68,604,640 | Solving 935B - Fafa and the Gates in Codeforces | I have a question about 935B - Fafa and the Gates in CodeForces. My code is working for the first test cases but it’s getting stuck on test case 20, this is the code I used, could someone please tell me what I’m doing wrong here? Thanks!
#include <iostream>
#include <string>
using namespace std;
int main(){
long l... | Aside from the i<=a issue I called out in the comments above, there's another issue.
Even if you fix the for loop to be stop after i<a, then this statement:
if (x == y && s[i] == s[i+1]) total += 1;
Will still reference an invalid index at s[i+1] since i+1 is an invalid index on the last iteration of the array.
On eac... |
68,604,307 | 68,604,399 | Following c++ code works in leetcode but not in my vscode, why? | I am currently working on a leetcode question, and try to track down the code process in my end, this is my solution:
#include <iostream>
#include <vector>
#include <stack>
#include <utility>
using namespace std;
vector<int> direction{-1, 0, 1, 0, -1};
int maxAreaOfIsland(vector<vector<int>>&grid){
int m = grid.s... | The linker error (not the warning) is what is causing the build to fail (scroll sideways!):
[...]crt0_c.c:(.text.startup+0x2e): undefined reference to `WinMain'
occurs in MinGW gcc when your code lacks either a main() or WinMain() entry point. As yours does. I guess leetcode (which I have never heard of or used) pro... |
68,604,352 | 68,604,969 | Why AVR-GCC compiler throws an error when overloading with the same variables but as PROGMEM? | My question is more like: Why the compiler "thinks" that a "PROGMEM variable" is the same as a "plain Variable"? is it because PROGMEM-keyword is "just" a macro and nothing more? or is it for some other reason too? and is there any workaround..?
ISSUE demonstration:
Lets consider the below example:
class object {
publi... | You can't expect the compiler to treat linker sections as type qualifiers, but you can define an overload for a const int*, which is pretty close to the semantics of PROGMEM (a ROM location).
I wonder what you plan on doing with a const int* though. All you will ever be able to do is read it, so it's basically equivale... |
68,604,515 | 68,606,610 | Given and unsorted array arr , of size n of non-negative integers, find a continuous subarray which adds to number sum. Help in getting output | #include <iostream>
using namespace std;
int main()
{
int n;
n=4;
int arr[n]={1,2,3,8};
int sum;
sum=5;
int curr=0;
cin>>sum;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
curr+=arr[j];
if(curr==sum){
cout<<i;
}
cout<<curr<<endl;
}
}
}
For the given question I need ... | I think your code only needs some minor modifications. You should add
some code to handle the case where your running sum is greater than the target sum, and you should also re-initialize your running sum correctly.
There may be some efficient solution that is faster than O(n^2), which I am not aware of yet. If someone... |
68,604,776 | 68,610,620 | I wanted to implement a BST and tried using vector for input | I wanted to implement a BST class with a vector and somehow its not working. I just wanted to know the reason why its not working.
The main reason that I can think of that root in the BST always remain NULL.
I wanted to experiment ways to use classes in data structures.
#include<iostream>
#include<vector>
using namesp... | The reason is that root is never assigned another value after its initialisation to NULL. Passing root as argument to the insert method can never alter root itself, as it is not the address of root that is passed, but its value.
Some other remarks:
insert always starts by creating a new node, at every step of the recu... |
68,604,902 | 68,605,565 | Casting pointer to different pointer causes wrong virtual function to be called | #include <iostream>
struct A {
virtual void a() {
puts("A");
}
};
struct B {
virtual void b() {
puts("B");
}
};
struct C {
virtual void c() {
puts("C");
}
};
struct D : public A, public B, public C {
virtual void c() {
C::c();
puts("cd");
}
};
... |
Can someone explain why this would change what virtual function is being called?
Generally, a C-style cast between pointer types won't change the value of the pointer and so will have no effect. There is, however, one exception.
A cast between a class and a parent or child class can change the value of the pointer. F... |
68,604,999 | 68,605,048 | Why aren't C++ Lambda Expressions Working? | I'm using Mac OS. I've installed the most recent Xcode Command Line Tools.
I'm trying to learn C++. I've been working through some code examples, but programs with lambda expressions won't compile for some reason.
I've attached some example code and the error message below.
#include <cstdio>
int main() {
... | if you are compiling with g++, by default it is using c++98. And the 'auto' type specifier is a C++11 extension. so you need to tell the compiler to use the c++11/17.
compile your srcs using the following:
g++ -std=c++11 yourfile.cpp
|
68,605,385 | 68,605,533 | For loop exit condition with map iterator | I have a std::map<str,int> my_map
Right now, the key-value mapping looks like this -
{["apple",3],["addition",2],["app",7],["adapt",8]}
Objective:
Calculate the sum of values of keys with a given prefix.
Example : sum("ap") should return 10 (3 + 7).
I could implement it with two loops and an if condition. But, I'm try... | The loop is completely correct, but not so readable at first sight.
We have std::map which is an associative container and sorted according to the compare function provided. For your map (i.e std::map<std:.string, int>), it will be sorted according to the std::string (i.e key).
So your map is already ordered like :
{["... |
68,605,410 | 68,605,691 | Problem with C++ class instance not being recognized | This is for "homework" but this is not an algorithm question, but rather a programming issue. As part of a project for my Data Structures class, I have to write a class to act as a database. That part is done. I am not asking about the algorithm, but rather, trying to isolate what is clearly a stupid bug on my part.... | You declare two independent mydb objects.
Either perform all actions in the try-catch block, or move connecting to another function.
PeopleDB connect(const std::string& infilename) {
try
{
cout << "Attempting to import DB entries from "<< infilename << endl;
PeopleDB mydb(infilename);
co... |
68,605,531 | 68,670,325 | conan install --build fails due to mismatching versions even after changing default | I am using conan to handle dependencies and I have already been able to compile and run the project by running individual steps like source and build.
I however want to be able to install and build in a single step, and for that purpose I do:
conan install . -if build -s build_type=Debug --build
In which case for some ... | If you don't tell CMake about the compiler you want to use, it will try to discover it in the project(...) call. If they don't match, a check performed by a Conan macro will fail.
Typically, if you want to use a compiler version different from the default you need to inform CMake about it. One of the most common ways t... |
68,606,517 | 68,606,557 | Cleaning the memory that Stockfish uses without closing the main program | I am trying to implement Stockfish to my own project by a static library. But I have encountered a problem. Stockfish uses some global variables in the namespace of "Stockfish" and at somepoint in my project I want to destroy everything that I use from Stockfish and re-initialize later.
For example, Stockfish stores th... | The tooling doesn’t make it easy to free the memory used by a specific library.
Static library boundaries are not recorded, and do not exist at runtime (except maybe in debug symbols).
The allocator does not generally record where an allocation was made.
The same is true of namespaces. Namespaces do not exist at run... |
68,606,596 | 72,222,589 | Is there a mistake in this code example in Stroustrup's "Programming Principles and Practices" book? | I came across this code example in chapter 18 of Stroustrup's "Programming Principles and Practices with c++ 2nd ed." Book.
vector& vector::operator=(const vector& a)
// make this vector a copy of a
{
double* p = new double[a.sz]; // allocate new space
copy(a.elem,a.elem+a.sz,elem); // copy elements
delete[] elem; ... | You are correct, and so is JeremyFriesner's comment, which points out that it should be:
std::copy(a.elem, a.elem.sz, p);
|
68,606,772 | 68,606,846 | In C++, and within the following constraints, how do I declare an array of size x where the value of x changes on each iteration? | I have a small program which needs to do as I have stated in the title. It will run case iterations of the outer loop (see below). Upon each iteration, it uses cin to read into sz which represents the amount of integers that need to be stored in array.
My issue is that the template declaration statement for an array ne... |
In C++, and within the following constraints, how do I declare an array of size x where the value of x changes on each iteration?
You cannot use std::array for this purpose. You must allocate the array dynamically, because the size of all other arrays must be compile time constant. The most convenient way to create a... |
68,606,787 | 68,606,893 | overloaded bool conversion and dereference object pointer | class D{
bool var;
public:
D(bool x): var(x) {}
operator bool(){return var;}
};
int main() {
D* temp1 = new D(false);
cout << *temp1; //0
D* temp2 = new D(true);
cout << *temp2; //1
return 0;
}
I'm trying to overload bool conversion for object D. Then I discover that there is a rela... | You're printing the result of converting your D objects to bool:
Dreferencing a D* give you a value of type D.
When you write cout << *temp1, the language looks for an operator<< overload that takes a std::ostream as its left-hand operand and an object of the type of D as its right-hand operand.
There is no such over... |
68,606,862 | 68,606,936 | Is explicit static_cast required for nuneric function return value? | For example, I would like to saturate cast a signed char value v, to an unsigned value.
Is there any difference for the following two implementations? One is without explicit static cast, the other is with.
unsigned char saturate_cast_to_uchar(signed char v)
{
return std::max(static_cast<int>(v), 0);
}
unsigned ch... |
Is there any difference for the following two implementations?
There is no difference in the behaviour. Implicit conversion from int to unsigned char has exactly the same behaviour as static cast from int to unsigned char
|
68,607,151 | 68,607,242 | Prime number (Recursive method) in C++ | i made this code to find if a positive integer n is prime or not. But it doesnt work (we i run it, it doesnt return anything). I have a similar code for python and that works fine but this one in c++ it doesnt, i dont know why.
#include <iostream>
bool isPrime(int num, int count=0, int div =1) {
if (div>num){
if... | As already stated, the culprit is this line:
return isPrime(num, count, div++);
div++ is a post-increment operation, so the value is div is returned first and then div is incremented, which causes your function to go into infinite recursion because div will always remain 1 in all recursive calls to isPrime(...).
You c... |
68,607,406 | 68,607,579 | Should I use a constructor only for variable initialization in C++? | I am new to OOP in C++. I have a class that doesn't need to run any code neither does it need any parameter when the object is created, should I still write a constructor only for the initialization of the variables.
I can do this:
#include <iostream>
class Something
{
private:
const char* msg = "Hewwo World"; // ... |
const char* msg = "Hewwo World"; // i can initialise here
To be precise, you aren't initialising there. You're defning a default member initialiser. This initialiser will be used when you initialise an instance without providing an initialiser for that member.
should I still write a constructor only for the initial... |
68,608,133 | 68,608,184 | Why is my Insertion bubbling a higher value to the start? | I used insertion sort to sort a string consisting of '+' separated digits. The digits can only be 1, 2 or 3. While I thought the code would work perfectly, it is giving me some weird outputs.
#include <iostream>
#include <string>
typedef long long ll;
using namespace std;
int main(... | while (key > 0 && s[i-2] > value)
You have used s[i-2] instead of s[key-2] in your code,this means as your numbers shift all the way to the left if value is smaller than s[i-2] instead of stopping once the number to the left is <= it.
TL;DR Change s[i-2] to s[key-2] and you'll be fine.
|
68,608,245 | 68,609,162 | How to efficiently transfer the contents of an std::queue to another in C++98? | In C++11 or higher, one can efficiently transfer all the contents of one std:queue instance to another std::queue instance through std::move(). The system I am working with, however, is only C++98. How can I do the same operation (efficiently) in C++98?
| For C++98 you'd need to reach into the the protected c member, and swap those containers. Swapping is meant to be fast and exception safe (and indeed is for standard containers), and is the idiom one would use prior to the addition of std::move.
You can do that with derivation, and pointers to members.
template<typenam... |
68,608,555 | 68,608,709 | Why does my algorithm to rotate array right by k times without extra array running in O(n) work only for small arrays and not for big ones? | I am trying to solve the Monk and Rotation problem given on HackerEarth (here) and I know other algorithms in the market that can do the work for me but I tried to make a new efficient algorithm for rotating array elements to the right by k times without using another array and without using any custom library function... |
Why my custom made algorithm [...] works only for small arrays and not for big arrays?
Because it is not guaranteed that with repeated i = (i+k)%n increments you will visit all elements.
More specifically, this will only work when n and k have no common divisor (other than 1).
For instance, if n = 4 and k = 2, then t... |
68,608,672 | 68,608,742 | unpack a parameter pack of pairs into an array and a tuple | So i have a list of pairs where the first member is a constant integer and the second is a type, is there anyway to unpack it into an array of the first member and a tuple of the second members?
struct MA {}
struct MB {}
struct MC {}
template <int I, class T> struct MyPair{};
How can I make a template meta function su... | Just define two helper metafunctions to get I and T:
template<class> struct GetFirst;
template<int I, class T> struct GetFirst<MyPair<I, T>> {
static constexpr int value = I;
};
template<class> struct GetSecond;
template<int I, class T> struct GetSecond<MyPair<I, T>> {
using type = T;
};
template<class... MyP... |
68,609,060 | 68,609,218 | Initialization in C++ | What is the difference between direct initialization and uniform initialization in C++?
What is the difference between writing
int a{5}; // Uniform
and
int a(5); // Direct
| In this particular example there will be no difference due to the type and the value choosen: int and 5.
In some other cases what initialization means does depend on whether we use {} or (). When we use parenthesis, we're saying that the values we supply are to be used to construct the object, making a computation. Whe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.