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,897,928 | 62,898,027 | In C++, I'm getting a compiler error that I can't make sense of | Here's my code, it just reverses the sentence:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence;
string reversedSentence;
int i2 = 0;
cout << "Type in a sentence..." << endl;
getline(cin, sentence);
for (int i = sentence.length() - 1; i < sentence.le... | Your reversedSentence string is empty, so indexing into it invokes undefined behavior. Instead, you can use push_back like this:
for (int i = sentence.length() - 1; i >= 0; i--)
{
reversedSentence.push_back(sentence[i]);
}
Also note that your loop condition needs to be modified. In case sentence is empty, you shou... |
62,898,089 | 62,900,254 | dynamic atexit destructor crash for inline map initialization | I have a common header file which will be used in my static lib, dll and exe. Static lib is linked to my exe and dll. And Dll will be loaded by exe.
For one of the requirements, I wanted to use a global map which will be used in both dll and exe but I could not since initialization is not allowed in header(got multiple... |
But I just replaced inline with static and it started working.
Using static bypasses the application-wide One Definition Rule (ODR). The ODR instead becomes compilation-unit specific. This means you'll have multiple instances of testCategoryMap spread across your application, none of which interfere with one another.... |
62,898,156 | 62,901,015 | FFmpeg: Is it better to make a application then using ffmepg directly | For all my IP camera streams, I use, under Linux, ffmpeg by a bash script which allows me at the same time to manage:
1/ Convert the RTSP streams to HTTP (HLS) for the "Live" and therefore which generates "m3u8" file and *.ts segments
2/ Backup the stream for archiving (in increments of 5 minutes), a cron remove older... |
would there be an interest (memory / cpu / speed) to develop a program
(C/C++/other?) to do the same thing by using the libraries of ffmpeg?
or the "gain" and the interest would be so minimal that it is not
worth the expenditure of energy and time?
Almost certainly not.
I very frequently write tools and utilities usi... |
62,898,319 | 62,898,849 | Win32 compiler option and memory allocation | I tried to compile the following code:
extern "C" {
#include "netcdf.h"
}
int main() {
const int Ntime = 336;
const int Nlon = 1442;
const int Nlat = 1021;
double* dhsum_vals = new double[Ntime * Nlat * Nlon];
}
When compiling with the 32-bit version, I get the error C2148 "total size of array m... | On Microsoft Windows, the virtual address space of a 32-bit process is limited to 2^32 bytes, which is about 4 GB. However, the higher 2 GB are reserved by the system, so that you effectively only have about 2 GB of address space.
Also, this address space is fragmented, so you will not be able to allocate 2 GB in one c... |
62,898,662 | 63,029,770 | Rewriting OpenCV C++ to EmguCV C# - how to work with pointers? | I'm trying to convert C++ code written OpenCV 2.x to Emgu.CV in C#.
I have a function in C++:
cv::Mat computeMatXGradient(const cv::Mat &mat) {
cv::Mat out(mat.rows, mat.cols, CV_64F);
for (int y = 0; y < mat.rows; ++y) {
const uchar* Mr = mat.ptr<uchar>(y);
double* Or = out.ptr<double>(y);
... | You can try converting inMat to an array inM, then calculating the values you need in another array Or, and finally converting the latter array to the output Mat outMat.
Note: I considered NumberOfChannels to be 1 as I think this will be always the case.
Mat computeMatXGradient(Mat inMat)
{
int x, y;
byte[] inM... |
62,898,835 | 62,899,984 | Converting a pointer to a range | This works:
const char* foo[] = {"This", "is", nullptr, "great"};
for (auto e : ::std::ranges::take_while_view (foo, // <- array
([](const char* s){return s!=nullptr;})))
std::cout << e << "\n";
This doesn't:
const char* foo[] = {"This", "is", nullptr, "great"};
for (auto e : ::st... | There is a way to assemble such a range from disparate parts, but you cannot implicitly treat a T* as one.
What you have to do is construct a subrange from a pointer, using unreachable_sentinel_t as the sentinel type. So you could code such a function as:
template<typename T>
auto inf_ptr_range(T *ptr)
{
return std::... |
62,899,128 | 62,899,585 | Sampling from a texture gives a black model using opengl and SOIL2 | I'm trying to texture a model but all I get is the model rendered totally in black.
i use SOIL2 library to load the image into the memory and
the following code shows Load function in my Texture class.
bool Texture::Load(std::string texturePath)
{
int channels = 0;
unsigned char* image = SOIL_load_image(... | Call glGenerateMipmap() after image upload (glTexImage2D()), otherwise it won't do anything useful since there isn't any image data in the texture yet to generate mipmaps from.
Or disable mip sampling by setting GL_TEXTURE_MIN_FILTER to GL_LINEAR/GL_NEAREST.
Also, be careful with GL_RGB & the default GL_UNPACK_ALIGNMEN... |
62,899,321 | 62,899,848 | Form minimum number from the given sequence of I's and D's | Given a sequence consisting of 'I' and 'D' where 'I' denotes increasing sequence and 'D' denotes the descreasing sequence. Write a program that decodes the given sequence to construct minimum number without repeated digits.
The digits should start from 1 i.e. there should be no zeroes.
Input: D Output: 21
... | ans.size() in C++ returns a size_t, which is unsigned (either 32-bit or 64-bit depending on your configuration). You can simply cast ans.size() to an int to fix your issue, like so:
for ( int i = static_cast<int>(ans.size()) - 1; i > static_cast<int>(ans.size()) - 1 - count; i-- )
Using a debugger, you could check tha... |
62,899,779 | 62,899,801 | How to compile and run both at the same time for a c++ code in linux terminal? | I am using Ubuntu(latest). If I have a test.cpp file in my home directory, I write two commands in terminal to compile and run this file.
prateek332@pp-pc:~$ g++ test.cpp
prateek332@pp-pc:~$ ./a.out
Is there a way to write these two command simultaneously (or maybe even a better way). I used pipelining but it doesn't... | g++ test.cpp && ./a.out
First compile and then, if it was successfull, run the code.
|
62,899,810 | 62,899,874 | string not outputting the data | I am reversing bits of an integer by first putting the bits in a string.
Why cout of nu_string is an empty string.
uint32_t reverseBits(uint32_t n) {
string nu_bits;
for(int i=0; i<32;i++){
nu_bits.push_back(n>>i)&1);
cout<<nu_bits<<endl; //prints nothing
}
//cout<<stoi(nu_bits); Thr... | push_back is for adding characters to a string, if the first character is 0 than the string is NUL-terminated and so will be empty.
You probably meant to do this: nu_bits.push_back('0'+((n>>i)&1));
|
62,900,257 | 62,900,349 | Undefined Reference when compiling C++ | My code is similar to this one, but the problem is exactly the same: I'm getting an "undefined reference to `Test1::v" in Test1.cpp and in Test2.cpp when compilling the program in VSCode. What am I doing wrong? I'm a bit new on c++ so I just downloaded an extension that made me a project in c++ automatically. When I ru... | You have declared the static vector in the header file, but you need to define it in a cpp file. Add:
vector<Test1> Test1::v;
to your test1.cpp file. You can learn more about definition vs declaration here.
Also make sure you read this: Why is "using namespace std;" considered bad practice?
|
62,900,329 | 62,907,041 | Why does sorting a vector with execution::par take longer than normal sort (gcc 10.1.0)? | Consider this code:
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <execution>
#include <functional>
#include <random>
#include <vector>
using namespace std;
using namespace std::chrono;
constexpr size_t NUM_OF_ELEMENTS = 30000000;
// execute lambda and print the execution time
void measure(functio... | running perf on your code, it looks like it spends a tiny bit longer trying to partition the data.
This is just one example, but i ran it several times and consistently the parallel version was taking longer to partition the data at multiple levels of the sort. Since its recursive, its hard to get an exact picture of h... |
62,900,649 | 62,900,794 | What is the right way to set MSVC_RUNTIME_LIBRARY for different configurations? | In the windows environment and Visual Studio 2019 IDE, what is the right way to set MSVC_RUNTIME_LIBRARY for two different configurations Test_Debug and Debug which are both DEBUG_CONFIGURATIONS?
Somehow this is does not work:
add_executable(foo foo.c)
set_target_properties(foo PROPERTIES
MSVC_RUNTIME_LIBRARY "MultiT... | If you set any property twice in the same set_target_properties call, you overwrite the previous setting. So, only the last setting is applied:
MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Test_Debug>:Debug>"
If you want to set the MSVC_RUNTIME_LIBRARY to MultiThreadedDebug when the configuration is Debug or Test_De... |
62,900,658 | 62,902,834 | How to Print Vertex Structure in a Loop | I'm looking to print the content of my Vertex Buffer. I'd like to loop through all the vertices and texture coordinates while printing to a console. Specifically I'd like to see both vertex location and texels (texture coordinates). How would this be accomplished in a loop?
//vertex structure
struct Vertex
{
XMFLOA... | There are a number of ways the code above can fail, so it's important to include the error-handling.
Also D3D11_MAPPED_SUBRESOURCE does not report the size of the vertex buffer in bytes through any of it's values, so you need to get it from D3D11_BUFFER_DESC via GetDesc.
DepthPitch is only a valid value if you are ma... |
62,900,710 | 62,900,962 | C++: TypeDef using Tuples | I am attempting to create a typedef using tuples here is my code.
#include <iostream>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_io.hpp>
#include "boost/tuple/tuple_comparison.hpp"
using namespace std;
typedef tuple<std::string, unsigned int, double> Person;
void Print(Person people)
{
};
int main... | Problem in your program that you use pesky using namespace std; statement so your typedef resolves tuple as std::tuple. Looks like you assumed that using boost::tuple; in main() allowed you to use one from boost, which is wrong. typedef is not a macro and name resolution there happens at time of declaration, not using ... |
62,900,780 | 62,901,197 | Failed argument deduction in views::take_while | I have this code:
for (auto e : foo | ::std::views::take_while([](const char* x) { return x != nullptr; }))
std::cout << e << "\n";
All is fine and dandy, but this lambda is a tat long and unwieldy. Since it occurs many times, I decide to have a named function object instead.
class non_null ... | std::views::take_while needs the call operator of the object being passed to it to be const-qualified in order for deduction to succeed:
struct non_null
{
template <typename T>
bool operator()(const T* t) const { // <-- const-qualified
return t != nullptr;
... |
62,901,136 | 62,908,949 | JNI - Class loading problem. DefineClass function doesn't seems to work | I'm trying to load specific classes using JNI. The problem is that DefineClass() function doesn't seems to work. And when I try to run function FindClass() it throws ClassNotFoundError. The class that I'm trying to load is a simple Main class with main method and "hello from world" in it. And it's package is correct.
T... | If DefineClass fails you should see if there are any pending exceptions.
The exception will probably be that your class file is malformed somehow, because you are opening your ifstream in text mode, where it happily replaces 0x0A bytes with a 0x0D 0x0A pair.
Use binary mode instead:
std::ifstream fl("C:/Users/Admin/Des... |
62,901,293 | 62,901,509 | Specifying void* parameter in derived function | I would like to do something that probably is not possible in Cpp, but I could not find a post about this specifically.
I want to have a derived class specify the type of a void* parameter on a virtual function.
I have a base class called interface with a send function.
// pure virtual
class Interface{
virtual bool... | @RSahu is correct, of course. You could still use a virtual method to do about the same thing:
class Interface {
virtual bool send(const void*) = 0;
};
struct Packet {
DataType data;
};
class SpecificInterface {
bool send(cont void*) override {
send(static_cast<DataType*>(data));
}
bool s... |
62,901,490 | 62,901,950 | Is it possible to create a new instance of base class based on a given identifier and vice versa in C++ | I have a base class and multiple subclasses extending it. My goal is to create a new instance of one of the subclasses based on the identifier and vice versa using C++. I have used a switch-case statement like this:
std::shared_ptr<base> create(int id)
{
std::shared_ptr<base> p;
switch (id) {
case 0:
... | C++ does not have metaclasses, like Java does. So the closest C++ equivalent of that Java code would look something like this:
#include <map>
#include <memory>
class Base
{
public:
...
virtual int getId() const = 0;
};
class Derived1: public Base
{
public:
...
int getId() const override { return 0; }... |
62,901,773 | 62,902,063 | Is the order of operations threadsafe? | I have an std::vector that is used to pass message to a thread. The vector is protected by a mutex:
vector<int> messages;
std::mutex m;
void postmessage (int msg) {
{
std::unique_lock Lock (m);
messages.push_back (msg);
}
}
When the thread is woken up, it grabs the entire message queue like this:
const ... |
Is this guaranteed to leave the vector in an empty state?
Yes, the returned value is move-constructed from messages, therefore messages is empty as you have correctly deduced.
This does not apply to all standard library types, so be careful -- some containers leave the source in an "unspecified but valid" state, wh... |
62,901,918 | 62,905,547 | Can Anyone reduce the Complexity of My Code. Problem E of Codeforces Round113 Div.2 | Link to The Problem: https://codeforces.com/problemset/problem/166/E
Problem Statement:
*You are given a tetrahedron. Let's mark its vertices with letters A, B, C, and D correspondingly.
An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time, he ... | Anytime you built into a recursion and you exceeded time complexity, you have to understand the recursion is likely the problem.
The best solution is to not use a recursion.
Look at the result you have:
3
6
21
60
183
546
1641
4920
⋮ ⋮
While it might be hard to find a pattern for the first couple terms, but it... |
62,902,085 | 62,902,207 | Can someone breakdown the syntax of this c++ template? | I have been working thought the c++ standard library in order to better understand the usage and syntax of C++ templates. I have been able to understand the basics of templating, but some of the more complex syntax has left me needing further explanation. The following snippet is from the Microsoft xutility library.
te... | The code in question:
_Ty (&_Array)[_Size]
is a reference to a compile-time deduced array of type _Ty with size _Size.
Due to the way operator precedence works in C++, the actual types themselves are named somewhat strange to avoid syntactic ambiguities -- which is where the round brackets around the & and name exist.... |
62,902,262 | 62,902,370 | it there any way to store lambda with captured parameters in a pointer | i have a problem with lambdas and is that i want to save them in pointers but create them using no constant variables.
// Example program
#include <iostream>
#include <string>
template<short n>
void speak(){
std::cout << "speak:[" << n << "]" << std::endl;
}
int main()
{
typedef void(*func)(void);
func p... | You use std::function instead of a pointer. Just include the header <functional>, and change
typedef void(*func)(void);
to
typedef std::function<void(void)> func;
and everything should work!
Not sure why you like to write (void) when () works too.
The reason you can't use a function pointer is because a function poin... |
62,902,907 | 62,903,097 | How to make a shortcut for a template function instance in c++? | I want to use boost::math::binomial_coefficient<double> in my module (cpp file). But instead of writing all that noise every time, I would like to assign it a simple name binom. But I struggle to find a decent way to do it.
#define for sure will do it, but it is recommended to avoid macros.
Wrapping it into my own func... | Instead of auto, use const auto or with recent compiler try static constexpr auto or inline constexpr auto.
Variable is still not good, as they remove overloads, default parameters, and may lead to unnecessary indirection.
Unfortunately, there isn't a good way, as far, as I know
using binom = boost::math::binomial_coef... |
62,903,016 | 62,903,037 | Error: 'reverse' was not declared in this scope | I created a program to reverse a sentence:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence;
string reversedSentence;
int i2 = 0;
cout << "Type in a sentence..." << endl;
getline(cin, sentence);
reversedSentence = sentence;
reverse(reversedSenten... | std::reverse() is defined in the algorithm header. Include that:
#include <algorithm>
Also, avoid using namespace std;.
|
62,903,138 | 62,906,954 | Is it possible to force multiple python processes to share the same memory via a C++ extension? | Here is my attempt:
int* globalvar = new int[8];
void cpp_init(){
for (int i = 0; i < 8; i++)
globalvar[i] = 0;
}
void writeAtIndex(int index, int value){
globalvar[index] = value;
}
int accessIndex(int index){
return globalvar[index];
}
BOOST_PYTHON_MODULE(MpUtils){
def("cpp_init", &cpp_init);
... | Processes can generally access only their own memory space.
You can possibly use the shared_memory module of multiprocessing to share the same array across processes. See example in the linked page.
|
62,903,465 | 62,903,703 | Does the method of assignment change how memory is allocated? | I had this done this assignment in the code:
const char* value = retCharPtrFunc();
Which had to be changed to:
const char* value;
if (true)
value = (retStringFunc()).c_str();
else
value = retCharPtrFunc();
And for some reason now this code is accessing more heap memory than before (using Address Sanitizer).
Heap memo... | As mentioned in the comments, you're calling .c_str() on a temporary string; the temporary gets destroyed and now the C string pointer is invalid.
You should save the result of retStringFunc() in a variable. And you need to ensure that this variable doesn't go out of scope while you're using value.
std::string s;
const... |
62,903,536 | 62,904,165 | Taking n lines from a file which contains m lines, repeating the file (lazily) if necessary | I'm looking for a way to use a text file to generate as much text as I need by simply repeating the as few times as needed.
In a purely functional language, like Haskell, the solution seems trivial: here I've posted the code for the review, and it is pretty short, even though I'm pretty sure it can be improved.
But in ... | Assuming file is some input stream, and you want to repeat the lines in file for n lines, you can use the range-v3 library like this:
namespace rv = ranges::views;
auto lines = ranges::getlines(file)
| ranges::to<std::vector<std::string>>;
auto result = lines
| rv::cycle
| rv::t... |
62,903,631 | 65,994,884 | Use C/C++ Macros to Generate Function Signature | I am attempting to use macros in C/C++ to generate some boiler-plate function declarations and definitions.
I would like a macro similar to:
DECLARE_FUNCTION(myFunction, int, A, int, B, char, C)
to generate the following code (please ignore the fact that this code seems pointless, it is just a simplified example)
void... | Based upon many of the other answers and comments, here is what I cam up with that solves my particular problem:
#define END(...) END_(__VA_ARGS__)
#define END_(...) __VA_ARGS__##_END
#define PARAMS_LOOP_0(type_, name_) PARAMS_LOOP_BODY(type_, name_) PARAMS_LOOP_A
#define PARAMS_LOOP_A(type_, name_) , PARAMS_LOOP_BO... |
62,903,653 | 62,903,752 | Multiple Member Constexpr Struc Initialization | I am new to constexpr, however, I believe that problem I am practicing is a good fit compile-time calculations. This is not for homework or anything, just practicing "Modern" C++.
Here is what I have so far:
Header (prime_app_lib.hpp):
// #pragma once for modern header files (.hpp)
#pragma once
#include <math.h>
stat... | The issue is all your members need to be initialized before entering the constructor body. So you could do:
constexpr PrimeData() : isPrime{} , primeValue{} {
// ...
}
or simply:
struct PrimeData {
bool isPrime[max_prime]{};
unsigned primeValue[prime_array_size]{};
// ...
};
Here's a demo.
|
62,903,982 | 62,923,622 | Trigger Keypress on Physical Keyboard | I want to trigger a Keypress on a Keyboard. On the physical keyboard - so that it has to travel through all the Kernel Filters with that specific keyboard as its source. Is something like that even possible?
I looked at DeviceIOCtrl and IOCTL_KEYBOARD_INSERT_DATA, but there are no docs to be found. Some say, it is not ... | I think I found a solution/hack that works for me. I was avoiding the magic unicorn described in the question and stuck to the driver I already had.
The first idea came, when I realized that I'm already able to inject keyboard strokes into Kernel-Land. Just not to a specific keyboard, but a random one. I initially plan... |
62,904,464 | 62,907,291 | cannot register structure as boost geometry 3D point | These declarations fail to compile
#include <boost/geometry.hpp>
namespace bg = boost::geometry;
struct c3d
{
double x, y, z;
};
BOOST_GEOMETRY_REGISTER_POINT_3D( c3d, double, bg::cs::cartesian, x, y, z )
compiler output:
g++.exe -Wall -fexceptions -g -m64 -IC:\Users\James\code\raven-set
-IC:\Users\James\code\bo... | You need to add #include <boost/geometry/geometries/register/point.hpp>. See this example.
|
62,904,511 | 63,066,437 | QTableView, glitch on showing hidden rows | I'm not sure either it's some kind of bug\glitch or I'm doing something wrong.
I have some hidden rows in the table and on click I want them to appear but result you can see on the picture below.
This effect occurs only when slider is scrolled till the end. Glitch disappears if I change focus to another window or whe... | After showing or hiding any rows make the model notify about the change in the layout to all views. You do that by calling layoutChanged.
void DumpsComparisonWindow::onTableClicked(const QModelIndex& index)
{
...
tableView_->showRow(index.row() + i);
...
table_->layoutChanged(); //add this
}
|
62,904,534 | 62,905,919 | Integrate a public but non static member function with ALGLIB | I am trying to integrate a member function of a class, and needs some help! I cannot declare the function static because this function uses non-static private members (more specifically use a private member which is another class). I am using C++17 and cannot downgrade
I write below a Minimum (Non) Working Example that... | I found a solution on http://www.newty.de/fpt/callback.html using a global variable (sorry...). I post here the code adapted to my question if anyone needs it:
#include <functional>
#include <iostream>
#include <cmath>
#include "integration.h"
class Foo;
class Bar;
void* pt2Object; // global variable which points to... |
62,904,840 | 63,176,395 | What does having "< >" around a pointer mean/do? C++ | I have my little code that needs to be solved/fixed but I'm struggling and getting stuck on problems too simple to be found with a simple Google search.
int vector, Shape, Shapes;
int Parameters;
int main()
{
string UserCommand;
vector <Shape*> Shapes;
vector <string> Parameters;
}
My question is what bas... | FOUND THE ISSUE. I simply created another header and cpp file, then deleted them both and visual studio woke up and removed the error. Weird
|
62,904,937 | 62,905,163 | Multiple member constexpr struct initialization based on a loop | Initial Question
I am trying to learn constexpr. I was stuck initially trying to initialize the struct but that was quickly answered. Now that I am looking at the result it seems like the struct is initialized to 0 and then is constant. I want the primeValue array to be correctly initialized with prime numbers. How do ... | Your code has two errors:
Your initialization is incorrect: in for (auto b : PrimeData::isPrime), b is a local bool variable and b = true simply overwrites the local variable. To update the original data, you must use auto& b : PrimeData::isPrime (and the same applies to the primeValue initialization loop, although si... |
62,905,887 | 62,908,491 | Accessing ARM peripheral registers through structures | I want to make my own library for ARM Cortex-M3 enabled devices. Currently writing to a register looks like this:
(*((unsigned int volatile * const)(0x400E0410))) = (1 << 11) | (1 << 12);
Where 0x400E0410 is the address of a 32-bit peripheral register (in this case the address of Power Management Controller's 'Periphe... | I'm not sure why I didn't think about this before, but volatile inside a function is only read by the compiler when you use that function. So I just made a struct using operator=(int) and operator int() overloads.
When using optimisation flags the compiler discards everything that the user doesn't use, which is exactly... |
62,906,482 | 62,931,092 | How do I determine a mapped drive's details | How do I determine a mapped drive's details like its actual path, FreeSize, and so on? So if I have a mapped drive on a machine called "MP" how can I using C++/Win32 or Qt determine the machine and path for the mapped folder and also other practical details?
I wanted to get extract information from the remote machine f... | You could use WMI class win32_logicaldisk in C++, here is the sample:
#include <stdio.h>
#define _WIN32_DCOM
#include <wbemidl.h>
#pragma comment(lib, "wbemuuid.lib")
#include <iostream>
using namespace std;
#include <comdef.h>
void PrintDriveDetails(wstring drive)
{
HRESULT hr;
IWbemLocator* pWbemLocator = N... |
62,906,520 | 62,909,235 | How do I statically link FFTW on windows? | During the setup of my project - when I knew even less than I do now about cmake - I was trying my hardest to link the FFTW library.
C:\\path\\to\\fftw-3.3.5-dll64 contains the .h files, .lib files (generated from .def files) and .dll files.
What I ended up doing was adding these links to my CMakeLists.txt:
add_execut... | The LIB files you generated from the DEF files are "stubs". They contain just enough code to load the DLL and call functions from it. They do not contain the actual FFTW code. You cannot statically link with these pre-built FFTW LIBs.
You will need to compile FFTW into a static library yourself first. It comes with a C... |
62,906,566 | 62,907,630 | Refactoring scoped enum bitwise operator code duplication | I have several scoped enums that can be used as bitwise flags. I've implemented the bitwise operator overloads identically for every type as exampled here:
ScopedEnumFoo& operator|=(ScopedEnumFoo& a, const ScopedEnumFoo& b) noexcept {
using underlying = std::underlying_type_t<ScopedEnumFoo>;
auto underlying_a =... | When you have identical functions operating on different types that is what a template generates so the the first step is to create a template:
template <class E>
E& operator|=(E& a, const E& b) noexcept {
using underlying = std::underlying_type_t<E>;
auto underlying_a = static_cast<underlying>(a);
auto und... |
62,906,602 | 62,906,655 | Retrieve the type of an unnamed struct for using it in a member function | How to get the type of an unnamed struct for using it in a member function?
struct {
using P = int; // What should be instead of int?
bool operator<(const P& r) {
return false;
}
} obj1, obj2;
int main() {
obj1 < obj2;
return 0;
}
| You can make the operator< a template, and constrain the type with std::enable_if. E.g.
template <typename P>
auto operator<(const P& r) -> std::enable_if_t<std::is_same_v<P, std::remove_reference_t<decltype(*this)>>, bool> {
return false;
}
|
62,906,684 | 62,906,811 | c++ sizeof - need help understanding | I am having trouble understanding a line of code. I see that an array is initialized as follows:
static const uint SmartBatteryWattHoursTable[1 << 4] = {
0, 14, 27, 41, 54, 68, 86, 104,
120, 150, 180, 210, 240, 270, 300, 330};
However I can't tell what the following code means:
int x = sizeof(SmartBatteryWatt... | The code is declaring an array of 16 (1 << 4) uint values.
The statement sizeof(SmartBatteryWattHoursTable) returns the byte size of the entire array, thus sizeof(uint) * 16 = 64 (assuming a 4-byte uint).
An array decays into a pointer to the 1st element, thus *SmartBatteryWattHoursTable is the same as *(&SmartBatteryW... |
62,907,138 | 62,916,809 | C++11: literal 7 is a prvalue? | I came across this article. And its example says:
int main()
{
int i, j, *p;
// Correct usage: the variable i is an lvalue and the literal 7 is a prvalue.
i = 7;
...
}
I wonder why literal 7 is a prvalue.
The standard [7.2.1.1.2] says:
A prvalue is an expression whose evaluation
initializes an object or ... | The standard quote you used describes the properties of prvalues, but does not define them. The definitions are scattered through the standard (and gathered on cppreference).
The definition for your situation is found in [expr.prim.literal]/1:
A string-literal is an lvalue, a user-defined-literal has the same value ca... |
62,907,193 | 62,907,408 | Left-handers, Right-handers and Ambidexters problem in codeforces gives me an error | when i submit it always give me wrong answer and i dont get where is the problem i succeed all 3 examples
https://codeforces.com/contest/950/problem/A
here is my code trying to solve the problem:
#include <iostream>
using namespace std;
int main() {
int l, r, a, sum, total;
cin >> l >> r >> a;
sum = l + ... | first find out the minimum of left and right, if 'a' is 0 this is the number a team can have, twice it, you get total players.
diff = max(l,r)-min(l,r)
if a >= diff, add a to minimum team to make both l == r and distribute the 'a' equally
else add 'a' to lesser team and that is the max you can have in the team.
in term... |
62,907,576 | 62,907,635 | How can I extract the pointer T from std::atomic<T>? | I have a some simple class:
class List {
List *next;
int value;
};
And a std::atomic<List *> Ltag. How can I extract the actual List * from Ltag?
I tried Ltag->value = 80 which didn't work. Casting didn't work as well.
| You can take advantage of the conversion operator of std::atomic.
(*Ltag).value = 80;
Or use load() to get the value explicitly.
Ltag.load()->value = 80;
PS: You're using std::atomic with pointer, that means there might be data race on the pointed object.
|
62,908,263 | 62,908,337 | Returning value of variable inside a struct when the struct is rvalue of an assignment | I have the following code:
class example {
int x;
inline void operator=(int value) { x = value; }
};
int main() {
example foo { 100 };
int bar = foo;
}
The int bar = foo; obviously doesn't work, because I'm trying to assign a variable of type example to a variable of type int.
Is it possible to retrieve t... | Add a conversion function to allow implicit conversion
struct example {
int x;
inline void operator=(int value) { x = value; }
operator int() const
{
return x;
}
};
int main() {
example foo { 100 };
int bar = foo;
}
|
62,908,579 | 62,908,815 | An integer won't double past a random number | I have recently started learning C++ and have made this small program
#include <iostream> // for std::cout << / std::cin >> / std::endl; / '\n'
#include <cstdlib> // for EXIT_SUCCESS and EXIT_FAILURE
int input()
{
int imp_num{ 0 };
std::cin >> imp_num;
return imp_num;
}
void output(int result)
{
std:... | The value 1231212123133333333333321 given by you is drastically larger than even uint64_t could hold (overflows). In my case, the maximum range of a uint64_t (occupies 8-bytes data) datatype is:
0 to +18446744073709551615
To know the limits in your platform, i.e. practically, take a little bit help of C++ library limi... |
62,908,875 | 62,909,473 | How can i use 6 byte integer data type in C? | I want to use 6 byte data type in c, but I cannot found how to do. Can you teach me how to use 6 byte integer data type in c?
I use dev c++, and codeblocks.
I want to use c, but i can also use c++.
Windows 64-bit
| There is a way to have exact number of bits for something in C, so in theory it's doable, but it will take more than 48 bits in memory.
To do so you can use bit fields from C, to do so you can:
struct your_type {
uint64_t your_value : 48;
};
With this you can create such struct, and access your_value which will hav... |
62,908,900 | 62,915,958 | Why doesn't std::exception have a move constructor? | The best practice regarding exceptions in C++ seems to be throw by value, catch by reference. I had a look at <exception> and cppreference and I see that std::exception has a copy-constructor but no move-constructor, why is this? Wouldn't having a move-constructor allow cheaply catching by value and thus simplifying th... | The descendants of std::exception do own data. For example std::runtime_error owns its what() message. And that message is dynamically allocated because it can be an arbitrarily long message.
However, the copy constructor is marked noexcept (implicitly) because the std::exception copy constructor is noexcept.
#include... |
62,909,005 | 62,909,328 | How to get the type of what it depends on from a dependent type in C++ | Suppose I define a type iterator inside type Container, so an object of this type would be Container::iterator. How can I get the type it depends on, which is Container?
struct Container
{
struct iterator {};
};
template<typename Cont>
auto getContainer(typename Cont::iterator&& iter)
{
return Cont{}; //return... | If you want to deduct the outer container type from the inner iterator type, you have to define the container type within the iterator:
struct Container {
public:
struct iterator {
public:
using container_type = Container;
};
};
Then you have to pass the iterator type to the getContainer function, ... |
62,909,240 | 62,909,674 | How do I split characters from a string in C++? | For example, if I want to separate "A123456789" into 10 different strings or as integers, How would I do it?
Like:
T129542154
into:
String s = T
int 1=1
int 2=2
int 3=9
int 4=5
int 5=4
int 6=2
int 7=1
int 8=5
int 9=4
I have Googled, but most of them are separating words from a phrase, or having some special character... | Since the input string is exactly 10 characters, consisting of a letter followed by 9 digits, you can very easily separate the individual characters into variables, eg:
std::string input = "T129542154";
std::string s(input, 0, 1);
int i1 = input[1] - '0';
int i2 = input[2] - '0';
int i3 = input[3] - '0';
int i4 = input... |
62,909,655 | 62,909,938 | C++ how do i make my function go in a different file, then include the function file in the main file? | #include <iostream>
using namespace std;
void calc () {
double num1, num2, result;
char op;
cout << "Enter your first number \n";
cin >> num1;
cout << "Now enter your second number \n";
cin >> num2;
cout << "And last but not least, what operator do you want to use? \n";
cin >> op;
if (... | So to move the calc function you just cut and paste it to a new file. The tricky part is combining the two files. To do that you create a header file and #include the header file in both your cpp files. The header file contains a declaration of the function. This is how the main file knows about the function in the oth... |
62,909,697 | 62,909,738 | Problem in compilation of C++ code to WASM using emcc | I am trying to compile the C++ code to WASM but facing problems in it. My C++ code included dlib and OpenCV libraries. I have successfully compiled OpenCV and dlib for C++ environment. Also, I have installed emscripten in my system.
The directory structure is
C Drive
|..
|-- dlib
|-- emsdk
|-- opencv
|-- cpp_project
n... | You have to change -I ../dlib ../opencv/build/include/opencv2/core.hpp to
-I ../dlib -I ../opencv/build/include
|
62,909,772 | 62,910,902 | Function pointers on a class's member function | void Parser::add_func_no_arg(void (Virtual_Machine::*f)(), std::string comand)
{
command_no_arg.push_back(comand);
func_no_arg.push_back(f);
}
void Parser::prepare()
{
//add_func_no_arg(Virtual_Machine::dump,"dump"); it work when i put it in static but i cant do that
add_func_no_arg(vm.clear,"clear"); ... | As written by IlCapitano you have to use a specific syntax to deal with pointer-to-members. Here is an example (compiled with g++ tmp.cpp -o tmp):
#include <iostream>
#include <string>
#include <vector>
class Virtual_Machine
{
private:
std::string name;
public:
Virtual_Machine(std::string n) :... |
62,910,172 | 62,910,842 | C++ template to check existence of friend function | I am struggling to get the following code to work. This prints "No setAttr" which feels unexpected.
Basically I have a method in Parent class which creates and instance of a child class and checks whether given type has a particular method or not. This works when I make the method (setAttr()) public but doesn't for fri... | There are some mistakes in your code:
First, you are checking for a method with no parms, but you want to check for the void setAttr(int x). If you want to do check for method with int, your test must be something like: decltype(std::declval<T>().setAttr(1) ( See additional int parameter here! )
If you do so, we run in... |
62,910,379 | 62,911,091 | Problem with C++ pipes when doing a read and write on the same pipe in a process | I am learning about pipes and forks. I am trying to get the count of kworker processes by using pipes and forks to represent ps -A | grep kworker | wc -l. My code is working correctly until the point where I am doing the pipes for the grep statement.
I run my code like this: ./a.out kworker
#include <iostream>
#include... | Look:
close(pipefd[1]);
dup2(pipefd[1], STDOUT_FILENO);
You close one of the FDs. Then you use dup2 with it. Because the FD is closed, dup2 returns an error code and doesn't do anything. So grep's stdout is still the normal stdout.
Your code has other problems. This is the one you asked about.
Elaboration about "oth... |
62,910,702 | 62,910,818 | C++ 11: How to write 2 template functions that differ in their return type | What I'm trying to do is have two function templates: one that translates a string to an boost::optional<some integer type> and one that translates a string to a boost::optional<some enum type>. Something like this:
template<typename T> boost::optional<T> func(const std::string &s) { return boost::make_optional(std::st... | You can use the type trait std::is_enum, and apply SFINAE.
template<typename T>
typename std::enable_if<std::is_enum<T>::value, boost::optional<T>>::type
func(const std::string &s) {
return boost::make_optional(EnumMapper<T>::map_string_to_enum<T>(s));
}
Note that you have to constrain on type for the 1st overloa... |
62,910,867 | 62,911,654 | How to run tests and debug Google Test project in VS Code? | I want to run the sample tests and debug the Google Test project. I am using VS Code on Ubuntu 16.04 LTS.
I cloned the project locally at /home/user/Desktop/projects/cpp/googletest,
created a new directory called mybuild at /home/user/Desktop/projects/cpp/mybuild.
According to the README instructions here: https://git... |
Start with a clean directory:
/home/user/Desktop/projects/cpp/ # your project lives here
Add your cmake file(CMakeLists.txt), your source files, and test file. The directory now looks like this:
└─cpp/
├─ CMakeLists.txt
├─ myfunctions.h
└─ mytests.cpp
Clone and add googletest to this directory:
└─cp... |
62,910,966 | 62,922,962 | How to use QStringView (or QStringRef) in Qt widgets? | I'm trying to replace heavy QString class with the lighter alternatives (QStringRef/QStringView). The problem is that Qt widgets don't consume these classes by any mean. For example, the QLabel::setText method requires const QString& as an input parameter, making my improvement useless.
I'm confused with this discrepan... | QString, QStringRef and QStringView have different use cases:
QString: the default class to store a string in Qt. It uses implicit sharing to avoid unneeded (read only) copies. Note that you may construct it efficiently by using f.ex. QStringLiteral for static strings:
[...] For most purposes, QString is the class yo... |
62,911,120 | 62,911,521 | Fenwick tree(BIT). Find the smallest index with given cumulative frequency in O(logN) | let's say I have a BIT(Fenwick Tree) with non-negative values and I want to find the smallest index in it for given cumulative frequency in O(logN).
Now, I can do it O(log^2(N)) like this.
int l = 0, r = n;
while(l < r) {
int midd = l + (r-l)/2;
if (get_sum(BIT, midd+1) < given_sum)
l = midd+1;
else... | Here is my implementation of a lower_bound-like function for a Fenwick tree with 0-based indexing:
std::size_t lower_bound(int value) const
{
std::size_t index = 0;
for (auto mask = msb_size_mask(); mask != 0; mask >>= 1)
{
const auto k = mask + index - 1;
if (k < data.size() && data[k] < va... |
62,911,273 | 62,911,854 | How do I get the correct size of a char*? | New to C++, so apologies if this is an obvious question.
I have a char[], containing an AES key (the key here is for demo only):
char oldkey[] = {0x7c, 0x4f, 0xd7, 0xc2, 0xfb, 0x09, 0x1f, 0xef, 0x6d, 0x34, 0x1a, 0x78, 0x6d, 0xd7, 0xb5, 0x17};
I'm moving from storing the key in this format to storing a base64 encoded s... | DecodeBase64 returns a value.
int DecodeBase64(.... // <------------------------------- this int right here
{
return( outLen ); // <------------------------------- this variable right here
}
That's the length you need. Use it.
int decodedLen = DecodeBase64((const BYTE *) key, key_len, (char *) key_mem, key_len);... |
62,911,380 | 62,916,581 | Automatically registering class members to the containing object in C++ | This is a question about C++ design: how to avoid introducing a bug as a class changes. The question title indicates my point of view of what I want, but might be the wrong strategy.
I have a class called MyCell that I collect in another class called MyRow. Behind all of this is a database, and the row will, prior to... | If you like boiler plate, I got something for you:
#include <tuple>
#include <type_traits>
// This you have to do once:
namespace detail {
template<class... Args>
constexpr void dump(Args...) {}
template<class T, auto en>
struct EnumTypePair {
using type = T;
static constexpr auto value = en;
constexpr... |
62,912,056 | 62,912,189 | Assigning const std::string to std::string in c++ | I am trying to assign a const std::string variable to std::string variable.But getting some memory related error. code is like below:
#include <iostream>
#include <string>
using namespace std;
std::string sender1;
std::string fun()
{
const std::string sender = "hi";
sender1.assign(sender);
}
int ... | You've forgotten a return in fun. If you change that function like this:
std::string fun()
{
const std::string sender = "hi";
sender1.assign(sender);
return sender;
}
then the code will compile and run fine.
|
62,912,057 | 62,912,222 | C++ for loop because i can't figure it out | Hello i want to add for loop that will print my code for 20 times or 50 times .. but i really can't figure it out since i already add for function but it still give only 1 result :D
#include <bits/stdc++.h>
using namespace std;
const int MAX = 36;
// Returns a string of random alphabets of
// length n.
string p... | Just run your function in a loop
int main()
{
srand(time(NULL));
int n = 20;
for (int i = 0; i < 50; ++i)
cout << printRandomString(n);
return 0;
}
Side note: #include <bits/stdc++.h> is bad, using namespace std; is bad and they are especially bad hen combined together.
|
62,912,066 | 62,936,458 | Compile Error(C2440)Using CEFbrowser & VS2015 | there. I'm new to CEFbrowser.
I'm developing the download model of My CefBrowser.
I've written some code but error while compiling.
class CefClient : public virtual CefBase {
public:
///
// Return the handler for download events. If no handler is returned downloads
// will not be allowed.
///
/*--cef()--*/
... | It looks like your CefClient has to inherit from CefDownloadHandler, i.e. class CefClient: public virtual CefBase, public CefDownloadHandler: CEF C++ Implementing download handler
Once you inherit from CefDownloadHandler, returning this from an instance of CefClient will fit correctly as a CefRefPtr<CefDownloadHandler>... |
62,912,546 | 62,913,378 | C++ reliable way to get QDateTime for buildtime | Previously I had a question about __DATE__
I want to use __DATE__ to get the build time.
The product will be compiled on systems with different locale.
Is the format for __DATE__ always the same?
My goal is to get the buildtime from __DATE__ and i want to make sure it works on any system.
Currently I use:
QDateTime(QLo... | From C++ standard (draft):
__DATE__
The date of translation of the source file: a character string literal
of the form "Mmm dd yyyy", where the names of the months are the same
as those generated by the asctime function, and the first character of
dd is a space character if the value is less than 10. If the date of
tr... |
62,913,079 | 62,923,773 | 1d Smart Pointer doesn't work with syntax (*)++ | I am learning about smart-pointer. So, I have arrowed code which I don't understand. code shown below. I tried below code in visual studio 2019.
why can't i use increment operator (*i)++ where as i can use i[0]++.
shared_ptr<int[]> foo(shared_ptr<int[]>i)
{
cout << i << '\n';
(*i)++; // doesn't ... | If a shared_ptr stores an array, then (and only then) shared_ptr::operator[] provides access to individual elements of the stored array.
shared_ptr::operator* provides access to the stored object as a whole. It is defined for all types of stored objects. If that's an array, then that's the whole array.
That's a quite i... |
62,913,685 | 62,913,839 | How to ensure a C++ function is declared before being defined (like the override keyword)? | In my shared library I declared a function in a header file, and defined it in a .cpp source file. When linking an application with the library, the linker complains that the function is undefined and I don't know whether it's because of a missing namespace, different parameters, or something else.
If I could mark the ... | Declare a function in a header file in a namespace, e.g.:
namespace N { void f(); }
Define the function in a .cc file using a qualified function name:
void N::f() { /*...*/ }
This way if no declaration of f in namespace N matches the definition, a compiler error is issued.
|
62,913,809 | 62,914,076 | boost asio doesn't recognize timer object | I'm trying to run boost example from the boost documentation timer2
this is the code:
#include <iostream>
#include <boost/asio.hpp>
void print(const boost::system::error_code& /*e*/)
{
std::cout << "Hello, world!" << std::endl;
}
int main()
{
boost::asio::io_context io;
boost::asio::steady_timer t(io, boost::a... | because you have boost version 1.58 you need to change your code according to the relevant version.
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp> // <- look at this header
void print(const boost::system::error_code& /*e*/)
{
std::cout << "Hello, world!" << std::en... |
62,913,869 | 62,914,479 | Ardunio UNO solve multiple overlapping timer loops | I'm stuck in writing two overlapping loops for switching a pump relay. If the timer "delayPump" ends (LOW) the timer "runnningPump" (HIGH) should start.
i guess some math madness, to be honest this loop is already making me mad, cause it should be easy!!!!
Any clue??
#define pumpSwitch_1 8
int delayPump = 10000; //dela... | I think this is what you need:
You just need a single Timer variable, and each time you toggle the state, set it to current time, i.e. millis().
#define pumpSwitch_1 8
int delayPump = 10000; //delay time
int runnningPump = 5000; // running Timer
bool pumpState = LOW;
unsigned long Timer = 0;
void setup() {
pinMode(... |
62,913,989 | 62,916,995 | Functionpointer based syntax for QMetaObject invokeMethod | I'm working on a simple wrapper for a IPC lib we are using.
I want to convert the events from this lib to calls on Qt slots.
Right now i have something like this:
void Caller::registerCallback(int id, QObject* reciever, const char* member)
{
_callbackMap[id] = std::make_pair(reciever, QString(member));
}
bool Call... | This soulution relies upon std::invoke and lambda.
Variant 1: use std::invoke directly instead of QMetaObject::invoke
Variant 2: use std::invoke inside a lambda, which is passed to QMetaObject::invoke
Variant 3: use MACRO instead of std::invoke in variant 2.
If you use QMetaObject::invoke you've got an option to choose... |
62,914,431 | 62,915,634 | How can I initialize objects from base class array, containing different derived classes, using a for loop? | I'm truly amazed by the idea behind the OOP, since I find it so much easier to think of the classes and the objects, as if they are real ones. I have a base class Tooth and derived classes for the different groups of teeth (they have their specifics). Their constructors are taking as argument the texture, which is draw... | The reason a lot of people are going to tell you to "get a textbook" is because there's a lot of machinery going on in C++. But don't worry, there's plenty of learning you can do without one. Practice is probably the best way to learn.
... There's a few things to consider finding a solution to your problem.
First, ther... |
62,915,579 | 62,915,687 | #define macros for "static" for different contexts | I want to distinguish "static" keyword in the different contexts. What are possible drawbacks of doing
#define common static // class member
#define intern static // linkage
from technical and semantic perspectives.
| If you use this approach, that if somebody, who has no idea what this means, will be really disoriented.
If you really want to use macros (Read this: https://google.github.io/styleguide/cppguide.html#Preprocessor_Macros), I'd advise you to use UPPER_CASE:
#define COMMON static // class member
#define INTERN static // l... |
62,915,720 | 62,915,959 | Change circle colour every 5 seconds | I try to create a green circle which every 5 seconds disappears.
Actually, I have the green circle created with the QPainter method. I tried QTimer and others methods but I can't find the good solution.
I overrided the paintEvent function like this :
void MainWindow::paintEvent(QPaintEvent *)
{
QPainter painter(thi... | Define a flag boolean that changes every 5 seconds and in paint use a brush as global variable
void MainWindow::paintEvent(QPaintEvent *)
{
....
QBrush brush(myBrush, style);
...
}
and in slot (run_led)
void MainWindow::run_led()
{
c != true;
if(c)
{
myBrush=Qt::green;
}
else
... |
62,916,404 | 62,924,396 | How to correctly set _MSVC_LANG value? | As you may know _MSVC_VALUE determines whether _HAS_CXX17 and _HAS_CXX20 macros are set. Today I tried to compile the following code in Visual Studio 2019 (latest 16.6.4 version):
#include <algorithm>
#include <execution>
#include <vector>
int main()
{
std::vector<int> _vector = { 3, 2, 1 };
std::sort(std::exe... | For future readers:
If you have similar issue, double-check that you are changing configuration that you will run then. In my case I was changing all the settings for Release but I tried to run the Debug configuration instead and I somehow didn't notice it.
Steps to change the configuration:
Right click on project
In ... |
62,916,695 | 62,917,783 | Locating a memory leak in the globals with given memory allocation number | I am trying to locate a memory leak in my c++ programm using VS 2019.
The output in the Debug-Output window reads for example:
{3880} normal block at 0x00D66730, 8 bytes long.
Data: < 5 > D8 35 0F 05 00 00 00 00
So the memory allocation number is 3880. In order to locate this leak I implemented
a memory leak on ... | You can add a Watch entry ucrtbased.dll!_crtBreakAlloc. It's initial value is -1. But you can set it to 3880 to request a stop at that allocation.
To get to that point when the allocation happens during startup is a bit difficult, though.
You must set a function breakpoint at ucrtbased.dll!heap_alloc_dbg_internal.
Ru... |
62,916,778 | 62,916,838 | Why can't I include the standard algorithm library after defining 'epsilon' in C++? | When I include the algorithm library before defining epsilon, the following code compiles:
#include <iostream>
#include <algorithm>
#define epsilon 0.00001
int main() {
std::cout << epsilon;
return 0;
}
When I switch them around, it doesn't:
#include <iostream>
#define epsilon 0.00001
#include <algorithm>... | Standard library headers are allowed to include any other standard library header.
It's possible that <algorithm> includes <limits> and there exists std::numeric_limits::epsilon() there. And of course macros ignore namespaces and classes, so it would try to declare a function called 0.00001.
Don't use macros. Use C++ c... |
62,917,251 | 62,917,421 | I want to bind a a non-const lvalue reference to type T to a temporary of type T | Is there a trick/cast letting me do that?
#include <vector>
std::vector<int> getBar(){
std::vector<int> bar (5,200); // five ints with a value of 200
return bar;
}
int main ()
{
std::vector<int> foo (3,100); // three ints with a value of 100
foo.swap(getBar());
return 0;
}
In this specific case
f... | You can define a auxiliary function, the "opposite" of std::move
template<typename T>
constexpr std::remove_reference_t<T> &stay(T &&t) { // perhaps "temporary" is a better name
return t;
}
In your case, the prvalue will materialize into an xvalue that binds to an rvalue reference, which lets us construct an lvalu... |
62,917,451 | 62,917,687 | (C++) Parse tree for evaluating simple arithmetic expressions returning incorrect value | I attempted to write a function that takes a simple arithmetic equation, converts it into a parse tree, and returns the evaluated value. For some reason, the value being returned is not correct at all. (Not that it helps, but the same function coded in Python works correctly). I've rechecked multiple times but I'm not ... | The problem is that you are doing calculations with characters and not with integers. As you might know each character has a Ascii-code, a numerical representation of this character, which is used for calculations. Ascii codes for '5', '2' and '7' are 53, 50 and 55.
Thus '5' + '2' * '7' is indeed 2083, because it's act... |
62,917,653 | 62,917,956 | Const-correctness with proxy object | I am confused with the following code, where the class Baz gives access to its internal data through the proxy class Bar:
struct Foo{};
template<class T>
struct Bar
{
Bar(T &val_): val(val_) {}
T &val;
};
struct Baz
{
Bar<const Foo> get() const {return Bar<const Foo>(foo);}
Bar<Foo> get() ... |
I must do a const_cast to dispatch to the right Baz::get() function.
Yes. Or std::as_const, or make Bar<T> convertible to Bar<const T>.
What I understand about a const function member is that it makes the this pointer-to-const, but in fact it is not totally clear to me what it means... Do all the data member be 'as ... |
62,918,253 | 62,918,375 | Is sizeof(variableName or expression) the same as sizeof(decltype(variableName or expression))? | Given the c++ keyword decltype and illustrating with a code example:
int main(){
int variableName = 0;
sizeof(variableName) == sizeof(decltype(variableName));//Always true for all types? And for all expressions?
//
//
double variableDoubleName = 0;
sizeof(variableName+variableDoubleName) == size... | Yes.
You might be imagining trouble from decltype variously returning a reference type or a value type, depending on whether you give it an identifier or an expression (ref).
But, fortunately for us:
When applied to a reference type, the result [of sizeof] is the size of the referenced type. (ref)
So, it doesn't matt... |
62,918,439 | 62,919,971 | Return Eigen::VectorXd by reference from function | I'd like to return an Eigen::Vector from a function and wondering what's the proper way to do it. Something like
Eigen::VectorXd& getMesh(int N) {
Eigen::VectorXd mesh(N + 1); // nb. of nodes
// Nodes are equally spaced
for (int i = 0; i < N + 1; i++) {
mesh[i] = i * (1.0 / N);
}
return me... | You must not return a reference to a local variable of your function. This is called a dangling reference. Note that your compiler should give you a warning when you do this : e.g Visual Studio.
warning C4172: returning address of local variable or temporary: mesh
The problem with your current getMesh() function is th... |
62,918,855 | 62,919,212 | C++ global operator method | I am not able to understand why I cannot be able to create global operator () method as like:
#include <iostream>
class A
{
public:
bool operator()(const A& a)
{
return true;
}
};
bool operator()(int a, int b)
{
return true;
}
int main ()
{
std::cout << "Hello\n";
}
When I co... | Well your question has two answer.
When you are writing operator()(xxx) you're trying to declare a function call operator. This means that you want to be able to use something as a function. For this to be possible, you have to be able to create an instance of this something, thus it need to be in a class.
As for your ... |
62,919,062 | 62,919,138 | Guaranteed 'if' statement elimination by using templates | I am wondering if it can be guaranteed (by the compiler's implementation) that certain 'if' statements are never going to be implemented in binary code, i.e., no jumps for some given 'if' statements are ever going to be used in the binary code.
This can be motivated with examples, but let me be brief. Assume you have a... | Maybe
if constexpr (condition)
syntax would be an interesting solution, without a template
|
62,919,499 | 62,932,519 | Can usage of C++ references be considered giving a function parameter a new name? | I was taught that giving concrete names to function parameters improves readability however what should I do if the function is an implementation of some mathematical formula where variable names are single letters by convention?
Is what I have done in the example a correct approach?
void EKF::update(const Vector& inno... | I don't think there's anything wrong with the idea, but I don't see why it's preferable to just using the right names and documenting the interface properly. For example, using Doxygen syntax:
/** Update function for Extended Kalman Filter
*
* @param y Innovation or measurement pre-fit residual
* @param S Innovati... |
62,919,576 | 62,920,988 | Schedule event later in C++: how to pass the task to be ran | I'm trying to run the following codes to schedule taskFun in class A to start running after 1000ms. When I run this code, I get this error:
main.cpp:9:70: error: no type named 'type' in 'std::__1::result_of<void (A::*(int))(int)>'
std::function<typename std::result_of < callable(arguments...)>::type() > task(std::b... | You were close.
As a non-static member function, taskFun has a hidden argument which becomes this. You need to bind this to the callback in addition to your argument 99:
later(1000, true, &A::taskFun, this, 99);
Now the argument list matches.
A lambda would probably be nicer though:
later(1000, true, [=]() { taskFun(9... |
62,919,708 | 62,920,305 | Read file and input into vector | Given a text file with the following fixed contents (only two lines, nothing more):
43 65 123 13 41
83 67 22
I need it to turn into a vector array where I can apply the name.size() to find out the length of the array and also to make use of the integers inside for other purposes.
The result should be:
Array 1: 43 65 1... | As already mentioned, std::getline and std::istringstream are good starting points.
Then you can use std::istream_iterator to create the vectors directly using the iterator overload of the std::vector constructor.
Perhaps something like this:
std::vector<std::vector<int>> read_file(std::istream& input)
{
std::vecto... |
62,920,011 | 62,920,479 | Trying to convert postgres time stamp string to c++ time stamp | I have PostgreSQL timestamp string:
2020-07-06 09:30:00.646533
I'm trying to convert it to timeval struct, I tried using this answer, but I'm getting this output:
Thu Jan 1 00:33:40 1970
This is my code:
#include <iostream>
int main()
{
std::string ss("2020-07-06 09:30:00.646533");
auto t = atoll(ss.c_str());... | atoll and atoi simply parse integers of various sizes from a string. They aren't great functions to use in general as they have no way of indicating that they have failed to parse the string. std::stoi and friends are the better functions to use. However in this case we don't have a number we have a date string so std:... |
62,920,269 | 62,923,133 | How to properly delete 1+ object from vector of uniq_ptr's | I have:
std::vector<std::unique_ptr<Zombie>> zombie;
for(unsigned j=0; j < zombie.size(); j++)
{
if(bullet intersects zombie)
{
zombie.erase(zombie.begin()+j)
}
}
I would like to delete specific object/s in vec... | The lecturer is correct.
Your loop unconditionally increments j on every iteration regardless of whether erase() is called. So, whenever you do call erase(), the indexes of the remaining elements decrement, but you increment j anyway, skipping the next element that followed the "erased" element.
One solution is to inc... |
62,921,348 | 62,937,156 | Proper API for access data members of container<T> | I have the following class:
class Document
{
public:
Document():
// default values for members,
// ...
m_dirty{false}{}
// Accessor functions
template<class OutputStream>
Document& save(OutputStream stream)
{
// Write stuff to... | I think the most robust way to solve it is to use a a callback. An issue with the proxy is that it would not handle the case where the the client code throws an exception (assuming strong exception guarantee). Testcase:
try
{
auto property_proxy = obj.getProperty();
// an exception is thrown here...
propert... |
62,921,373 | 62,921,689 | Embedder side pointer compression is DISABLED | I have built v8 8.4 for Windows as a monolithic static lib, and am trying to get this sample project running using Visual Studio 2019.
The error I get when the project runs is this:
# Fatal error in ../../src/api/api.cc, line 5619
# Embedder-vs-V8 build configuration mismatch. On embedder side pointer compression is DI... | To turn on pointer compression, compile your app with the compiler flags V8_COMPRESS_POINTERS and V8_31BIT_SMIS_ON_64BIT_ARCH defined (e.g. set to 1).
(With GCC/Clang, you'd add -DV8_COMPRESS_POINTERS to the command line; I don't know what the Visual Studio equivalent is, probably there's some build settings configurat... |
62,921,397 | 62,922,262 | Is it possible to initialize member variable (or base class) of a non-copyable type? | Consider following code:
struct S
{
S() = default;
S(S const&) = delete;
// S(S&&) = delete; // <--- uncomment for a mind-blowing effect:
// MSVC starts compiling EVERY case O_O
};
S foo() { return {}; }
struct X : S
{
// X() : S(foo()) {} // <----- all compilers fail here
}... | So, I think I found the relevant parts of the standard and I think the compilers are in error regarding to X. (All links are to a standard draft so very maybe it was different in C++17, I will check that later. But gcc10 and clang10 also fail with -std=c++20, so that is not that important).
Regarding the initialization... |
62,921,429 | 62,921,706 | std::map<struct,struct>::find is not finding a match, but if i loop thru begin() to end() i see the match right there | struct chainout {
LONG cl;
std::string cs;
bool operator<(const chainout&o)const {
return cl < o.cl || cs < o.cs;
}
} ;
struct chainin{
std::string tm;
std::string tdi;
short mss;
LONG pinid;
bool operator<(const chainin&o)const {
return mss < o.mss || pinid < o.pini... | As noted in comments, you have a bad comparison operator. If you don't know what order the objects should be sorted in, then neither does std::map or any other sorted container.
When you have multiple things to compare, consider deciding which is most important, and use std::tie to compare them, as demonstrated here:
#... |
62,921,507 | 62,921,877 | CreateFile function executed without errors but doesn't create any files | I have such implementation in my method
std::string name2 = "D:\\Buffer\\Temp\\t_libpng" + std::to_string(i) + ".png";
bool _write_png_file_cv2_(char const *filename,
int width,
int height,
int widthStep,
png_byte color_type,
png_byte bit_depth,
png_bytep *row_pointers)
{
// ...
hFi... | You have an invalid type-cast in your code.
CreateFile() is a preprocessor macro that maps to either CreateFileW() (which takes wchar_t*) or CreateFileA() (which takes char*) depending on whether UNICODE is defined. Clearly UNICODE is defined in your project, which is why CreateFile() expects wchar_t*.
// winbase.h
W... |
62,922,513 | 62,923,253 | Split threads on several pools | I have some code like this:
void doSth () {// code ...}
vector<string> files_1; // filenames .txt to get text from
vector<string> files_2; // filenames .txt to get text from
// sizes of files_1 and files_2 are ==
mutex m;
// lambda for for_each
auto gogogo= [&](const string& fn1) {
// Comupute other element via p... | You have to put for_each() inside a loop, and give it iterators that are 8 elements apart. Here is a possible solution:
#include <iterator>
...
for(auto i = files_1.begin(); i != files_1.end();) {
auto start = i;
auto end = std::advance(i, std::min(8, std::distance(i, files_1.end()));
for_each(execution:... |
62,922,725 | 62,922,784 | std::vector vs dynamic array passing by value | Hello I am comming from c to c++ and I've been wondering why can std::vector be passed by value.
I assume passing dynamicaly allocated array by value is not possible as that would only copy the pointer.
How is it then possible for a vector to be coppied, if inside of a vector class is same pointer. It has to somehow kn... | std::vector knows how many elements are stored in the dynamic memory. It is a simple matter to allocate a new buffer of that size and copy the contents into that new memory. All of this happens in the copy constructor.
|
62,922,783 | 62,923,649 | Is there a way to declare an array of std::vector of a certain size? | I want to declare an array of vectors of a certain length. To declare an array of vectors, I write this, for instance:
std::vector<double> myarray[17][38][42];
This creates a 3-dimensional 17x38x24 array, where each element is of type std::vector<double>.
I also know that to specify the size of a std::vector I may wri... | You can't initialize such a multi-dimensional array the way you want. But you can declare it first and then use a separate initialization loop instead, eg:
std::vector<double> myarray[17][38][42];
for(size_t i = 0; i < 17; ++i) {
for(size_t j = 0; j < 38; ++j) {
for(size_t k = 0; k < 42; ++k) {
... |
62,923,007 | 62,997,554 | intel-oneApi CUDA support was not enabled at compilation time | I am new to intel-oneapi, I followed intel's instructions to install oneApi on Ubuntu 20.04.
I successfully compiled vector-add example. Unfortunately, during runtime I get the following exception:
pi_die: CUDA support was not enabled at compilation time
terminate called without an active exception
Aborted (core dumped... | If you are targetting Nvidia hardware using DPC++ you currently need to re-compile DPC++ with this support.
The instructions for doing this are in the repository here.
Once you have done that you can use the appropriate device selector to choose the Nvidia GPU for executing.
|
62,923,260 | 62,923,889 | Does reinterpret_cast cause a strict aliasing violation? | why does it even exist? In what situations does it not cause a strict aliasing violation, and in which ones does it do cause one?
I mean, if you cast between two incompatible types, and the result of that cast is the only pointer that points to the memory it uses in the whole program, is it safe to use it then under th... |
Does reinterpret_cast cause a strict aliasing violation?
Not by itself, no. But its misuse can lead to such violation.
It is not a good idea to use reinterpret cast unless you know that you need it (rare), know that there is no satisfactory alternative (rarer), and know that it won't lead to undefined behaviour.
why... |
62,923,672 | 62,924,545 | Pybind11: Passing list of tuples from Python to C++ | I'm using pybind11 and I would like to pass a list of tuples (coordinates) from Python to C++. Here is the example C++ code:
parse_coords(py::list coords) {
std::vector<PointI> coordinates(py::len(coords));
for (size_t i = 1; i < py::len(coords); i++) {
coordinates[i].x = coords[i][0];
coor... | You have to use py::cast. If there is no casting function registered for your custom type, or there is a type mismatch, then you are going to get an exception:
Example:
void cast_test(const py::list& l)
{
for(auto it = l.begin(); it != l.end(); ++it)
{
std::cout << it->cast<int>() << std::endl;
}
}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.