question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
65,379,786 | 65,380,142 | What is the significance of having a function reentrant in a single-threaded environment? | What is the significance of having a function reentrant in a single-threaded environment?
I understood that for a function to be reentrant it needs to be able to be interrupted, entered by another thread, and resume without having any undefined or undesired side effects.
I read this question Threadsafe vs re-entrant. B... | Suppose we put multi-threading aside. This function can be said to be non re-entrant:
void bar() {
static bool inside_function;
inside_function = true;
assert (inside_function == true)
inside_function = false;
}
Without recursion and callbacks this isn't an issue. Though once you add recursion th... |
65,379,825 | 65,386,517 | QtCore/QTextCodec not found in Qt 6 | After upgrading to Qt 6.0, the compiler told me
qzxing/src/QZXing.cpp:16: error: 'QtCore/QTextCodec' file not found
qzxing/src/QZXing.cpp:16:10: fatal error: 'QtCore/QTextCodec' file not found
#include <QtCore/QTextCodec>
^~~~~~~~~~~~~~~~~~~
qzxing/src/QZXing.cpp:16:10: note: did not find header 'QTextCodec' i... |
Make sure that you have installed "Qt 5 Compatibility Module".
Add QT += core5compat in .pro file.
Replace #include <QtCore/QTextCodec> to #include <QTextCodec>
|
65,379,850 | 65,380,001 | What does C::* mean in typename argument | I know there is a similar problem here
My question is slightly different from that,
what does it mean When c::* appears in the template parameter,
template <typename C>
static yes& f(typename std::enable_if<
std::is_same<decltype(static_cast<typename C::const_iterator(C::*)() const>(&C::begin)),
typename C::con... | IMHO that's awfully constructed statement over there, it's unreadable. But it can be "disassembled" hierarchically:
template <typename C>
static yes & f (
typename std::enable_if<
std::is_same<
decltype(
static_cast<
typename C::const_iterator(C::*)() const
... |
65,380,026 | 65,380,325 | c++ global config class without passing as reference | I have my Config class, that manages app config, get set etc.
I want other classes to be able to use it, but passing it to each method as a reference is a pain, And I have a feeling there is better way to do it.
so this is my config class header:
class Config
{
public:
Config();
public:
char *port;
templ... | Depends on the actual usage context, but if you are familiar with the singleton pattern, this might be a way to go here in doubt if you are not able to forward the configuration information by design in a quite non-intrusive way (the latter should almost always be the preferred way but I know there are sometimes except... |
65,380,328 | 65,380,800 | Boost multithreading exception | I have a program like main.cpp
#include <stdio.h>
#include <boost/thread/shared_mutex.hpp>
#include <boost/thread.hpp>
class MutexClass
{
private:
/* data */
boost::shared_mutex m_mutex;
bool running; //The flag program should stop
public:
MutexClass(/* args */);
~MutexClass();
void doSomeThi... | It can be done by plenty of ways. The main goal here is not to delete your object until all the routines using it are dead. One of the method is using shared_ptr to pass the object into thread.
Take a look at what I'd done here to make this code work. I've commented the significant changes with !!!
#include <stdio.h>
#... |
65,380,526 | 65,385,707 | How to import windows.h as module correctly | mybar.ixx
export module mybar;
#include "windows.h"
export
double trywinapi() {
MEMORYSTATUSEX memInfo;
memInfo.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&memInfo);
return memInfo.ullTotalPageFile;
}
main.cpp
import mybar;
#include "windows.h"
void main() {
trywinapi();
}
And vis... | The global module fragment goes before the module name:
module;
#include<windows.h>
export module mybar;
export double trywinapi() {…}
|
65,380,717 | 65,380,760 | Double acts weird in C++ | I am trying to make a small graphics demo, and was increasing a variable (let's say it's called B) by 0.05 every iteration.
Problem, the code does not work as expected.
#include <iostream>
int main(void)
{
double b = 0;
for (int i = 0; i < 3001; ++i) {
if (b < 150)
b += 0.05;
std::c... | It is because of double precision. You can solve it by using integers:
int main(void)
{
int b = 0;
for (int i = 0; i < 3001; ++i) {
if (b < 15000)
b += 5;
std::cout << b/100 << std::endl;
}
}
|
65,381,675 | 65,382,040 | How to sum matrix with function? | I want to sum the matrix on the third row by using a function but it didn't output anything.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int m = 5, n = 7;
void sumrow ( int *i , int *j ){
int sum = 0;
int **a = new int *[m];
for(int j = 0 ; j < n ; j ++)
... | I suppose you are trying to sum the matrix created in main. The way to do that is to pass the matrix as a parameter from main to sumrow. Not to create a totally different matrix in sumrow. Something like this
int sumrow(int** a)
{
int sum = 0;
for (int j = 0; j < n; j++)
sum = sum + a[2][j];
return... |
65,381,746 | 65,382,012 | How to output/Input multibyte symbols? | After a lot of searching I start using that weird code:
ofstream myfile;
string chars = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
myfile.open ("alphabet.txt");
for (int i = 0; i < 66; i+=2) {
myfile << chars[i] <<chars[i+1] << "\n";
}
myfile.close();
But is there really no way to get a wide cha... | This worked on my machine. My source code file is in UTF-8. The string is in UTF-16. The output is in UTF-16LE.
C++ has gotten a little better over time handling Unicode strings, but still has a lot of room for improvement.
#include <fstream>
#include <string>
using std::ofstream;
using std::string;
int main() {
... |
65,382,031 | 65,382,221 | Trouble initializing and incrementing a static member variable | I am new to C++ and I'm facing trouble with my code here:
#include <iostream>
using namespace std;
class Student {
public:
string student_name;
double CGPA;
string degree;
static unsigned int count_total_no_of_students_enrolled; //STATIC VARIABLE
const string uni_name = "umt";
void sets... | The two errors in your code are:
Your call to display_total_no_of_student() doesn't provide either a class object or a class name for that function, so the compiler is looking for a 'free' function of that name/signature, which it doesn't find.
Although you have provided a declaration for the static count_total_no_of... |
65,382,197 | 65,382,322 | Understanding a solution for implementing square() without using the multiplication operator | I am currently working through Bjarne Stroustrup's Programming Principles and Practice Using C++. One of the "try this" exercises is to implement a square function without using the multiplication operator. A solution I found is:
int archaic_square(int v) {
int total = 0;
for (int i = 0; i < v; ++i) {
total ... | This is simple you can think of multiplication as:
for example I say 3 * 5 it equivalent to I say 5 + 5 + 5 or 3 + 3 + 3 + 3 +3.
The same way this function is summing N number N times. For example let say I pass v=5.
It will work like this:
total= 5 + 5 + 5 + 5 + 5 = 25.
|
65,382,288 | 65,382,710 | using vkEnumerateInstanceVersion to get exact Vulkan API version | I am using vkEnumerateInstanceVersion to get the vulkan api version and pass it to VkApplicationInfo struct. I can easily differentiate between VK_VERSION_1_0 and VK_VERSION_1_1
//query the api version in order to use the correct vulkan functionality
PFN_vkEnumerateInstanceVersion FN_vkEnumerateInstanceVersion =
PFN_v... |
I am using vkEnumerateInstanceVersion to get the vulkan api version and pass it to VkApplicationInfo struct.
That's not what vkEnumerateInstanceVersion is for.
VkApplicationInfo::apiVersion specifies the version of Vulkan against which your code is written. This version is meant to be a fixed value, because your code... |
65,382,551 | 65,382,809 | arithmetic std::unique_ptr and void* (get position of element by address) | I have a class:
Allocate blockSize*maxSize bytes of memory. Has a method which return ptr to free block of memory.
I fill this block in main() for example (see usage below) and send it back to my class.
PROBLEM: How can I get position of sent me back address of initialized data? Because in main() I have void* ptr, no... | When I compile your code with Visual C++ 2019, I get this error:
error C2440: '-': cannot convert from 'unsigned char *' to 'char *'
If I change your code to cast to unsigned char* as per the error message, then it compiles:
auto pos = ((unsigned char*)data - memoryPool.get()) / blockSize;
Whether that does what you i... |
65,383,252 | 65,383,361 | array from friend class in assignment operation is being manipulated | I have a class called Map with the following declaration:
class Map {
public:
void get_world_size(const double val);
void get_landmarks(const double array[][2], int val);
void print_map();
private:
int num_landmarks;
double world_size;
double landmarks[][2];
friend class Robot;
};
where I... | double landmarks[][2]; is not legal C++. Such declaration allowed only if you initialize it directly and then omitted size would be defined by size of the initializer list.
|
65,384,273 | 65,384,587 | C++ ranges find and return std::optional like Java stream | In Java, Stream.findFirst() returns Optional<T>. I'd like to have the similar behavior for std::ranges::find(). If the value is not found, it returns last iterator. This is inconvenient if T is a struct and I try to get a member out of it. Here is a demonstration code:
struct Person {
int age;
int h... | template <class ...ArgsT>
auto OpRangesFind(auto &&Range, ArgsT &&...Args)
{
auto Iter = std::ranges::find(Range, std::forward<ArgsT>(Args)...);
return Iter != Range.end() ? Iter : std::optional<decltype(Iter)>{std::nullopt};
}
int main()
{
/* ... */
auto OpIter = OpRangesFind(people, 26, &Person::age... |
65,384,277 | 65,390,432 | error: failed to read compiled module: No such file or directory | I've just purchased the book Beginning C++20 (the eBook version) and I'm trying to compile the first example using the new C++20 method.
The content of the source file is
// Ex1_01.cpp
// A Complete C++ program
import <iostream>;
int main()
{
int answer{42}; // Defines answer with 42
std::cout << "The answ... | I guess I'll be answering my own question.
When I follow the instructions on the GCC wiki (https://gcc.gnu.org/wiki/cxx-modules) it's a newer version compared to the one found on svn.
The svn has a version 10 of gcc while github has version 11.
When I compile the version for github (g++ (GCC) 11.0.0 20201217 (experimen... |
65,384,436 | 65,384,474 | Where can I find "Try This" solutions on Stroustrup's book Programming Principles & Practices? | I just need to double check my soulutions, but I can't find any solutions posted in the web.
Would be glad if you help me because I've set myself a goal to learn c++ during holidays.
In particular I need help with a function exercise, this is what I have so far:
//(not using multiplication)
int square(int a)
{
int ... | result is 0, so adding it to itself, no matter how many times, will result in 0. If you're attempting to square a, you should add that to the result. Additionally, the return statement should be outside the loop, not inside it:
int square(int a)
{
int result = 0;
int count = 0;
while (count < a)
{
... |
65,384,492 | 65,385,111 | How to pass a String without quotes to function? | template<typename... Args>
void callJavaScript(const Args&... args) {
// TO-DO
}
callJavaScript({
console.log("Hello World")
})
Is it possible to accomplish something like this with Variadic templates (with/without Macro hack)?
Instead
callJavaScript("{
console.log('Hello World')
}")
I want
callJavaScript... | Answering my own question.
void callJavaScript(std::string script) {
std::cout << script << "\n";
}
#define callJavaScript(...) callJavaScript(#__VA_ARGS__)
Now you can call like this,
callJavaScript({
console.log("Hello World")
})
You can compile this then it will output
{console.log("Hello World")}
If any... |
65,384,778 | 65,384,871 | How to register a dynamic member in C++ | Magic methods in python are really magical. For example:
class DynMember:
def __getattr__(self, name: str):
def fn(self, **kwargs):
print(kwargs)
setattr(self.__class__, name, fn)
return lambda **x: fn(self, **x)
if __name__ == "__main__":
d = DynMember()
d.someFn(tit... | What you want is not supported by C++ yet, there is some third-party libraries like Qt or Boost which provide that. But (is ambiguity about what you exactly want) if you want to implement something like def fn(self, **kwargs) you can do it with Variadic Functions (Example) or Template Parameter Pack (Example) or Design... |
65,384,913 | 65,390,577 | Segmentation fault in vscode c++ | I am writing a simple program of linear search on vscode on macOS.
The code is producing an error called segmentation fault only in vscode.
But the strange thing is that code is working perfectly fine on onlinegdb compiler and Xcode IDE.
I have the default c++ compiler installed on my Mac which came after installing Xc... | Segmentation fault isn't a vscode error, its a program error, it indicates that your program is accessing a memory adress that it hasn't reserved, thus the OS kills your program to save the system from wrong or bad memory accesses.
You first initialize n with 0 and then initialize the array arr with n ints. So it makes... |
65,384,989 | 65,385,033 | What are the pros and cons of having an update source be a reference member instead of passing it to the update functions? | I have a class whose instance relies completely on updates from an instance of a separate class.
Simplified example:
#include "Source.h"
class ObjectThatNeedsUpdates
{
public:
ObjectThatNeedsUpdates();
void update(const Source& source)
{
//Update member data with data from source
}
private:
... | Do whatever you feel best expresses the contract between the caller of update() and the class itself.
If the lifetime of ObjectThatNeedsUpdates is always contained within the lifetime of the Source object, and which Source object to use never changes, then I feel that holding a reference to the Source object is the bes... |
65,384,997 | 65,385,025 | Implicit conversion to array index type | Let's say I have following type:
struct XY
{
short nIndex;
constexpr operator int()
{
return nIndex;
}
};
What can I change to make the following work:
char arr[10][255];
constexpr XY xy{1};
char *x = arr[xy];
I thought that just giving XY a convert-to-int operator would be enough but I'm getting th... | Since the variable is constexpr, you cannot call the conversion operator that is not const-qualified. Solution is simple: Make the conversion operator const qualified:
constexpr operator int() const
|
65,385,103 | 65,385,499 | How to use a parallel std::for_each on systems where <execution> is missing? | This C++17 snippet works fine in newer versions of G++
std::for_each(std::execution::par_unseq, container.begin(), container.end(), [&](const auto& element) {
// do something with element... or don't. whatever.
});
When you try to port that code to the current Debian (Stable) distribution for instance, which has G... | <execution> was added in gcc 9 (9.1 I think) but you could use the underlying library, Intel® oneAPI Threading Building Blocks or tbb for short, directly instead. It's a little cumbersome but something like the below would work in gcc 8.3 if you link with -ltbb (which you need to link with even in the newer gcc version... |
65,385,237 | 65,385,902 | OpenCV 4.0 -- Waiting to capture from VideoCapture | Problem
What I wanted to do is make a live video capture VideoCapture cap that only captures every set amount of time 'X', where X is typically anywhere between 500ms - 1s. If the difference between two captures currentIMG & previousIMG was high enough, it was supposed to do some kind of processing task and set the pre... | you have to start a thread that grabs AND retrieves (or simply reads) the frames, and nothing else is allowed to read from the camera or access the VideoCapture object.
that thread stores the latest frame somewhere, so the rest of your program can get that frame whenever it needs to.
use synchronization primitives such... |
65,385,552 | 65,385,738 | How I can create a texture atlas in OpenGL with other existing textures? | I will like to generate a texture atlas from some textures that are already loaded in memory.
The textures I will like to include in the atlas are generated procedurally on runtime so I can't just create a png tilemap that already contains them.
Is this possible to do with OpenGL?
| Create a texture big enough with glTexImage2D and use glTexSubImage2D to put the 100 tiny square textures into it. glTexSubImage2D allows the specification of the x and y offsets in the target texture and the size (width and height) of a tile.
|
65,385,679 | 65,401,317 | Policy Based Design - Ideomatic way to deal with multitude of types, e.g. storing them in a container, iterating, etc | In the hello world example of policy based design from wikipedia we use a common interface HelloWorld and configure it with different policies through templates - so far so good:
int main() {
// Example 1
typedef HelloWorld<OutputPolicyWriteToCout, LanguagePolicyEnglish>
HelloWorldEnglish;
HelloWorldEnglis... | So here is a solution I found after pondering the comments again - key seems to combine the best of both worlds, polymorphism and policies - who would have thought ....
By introducing a common base class that defines only the public interface of the behavior class and then deriving the behavior class from that and the ... |
65,385,855 | 65,385,878 | Using template programming to change the type of the container | I have been reading through a template metaprogramming tutorial and I am struck at this example from that book.
/* Change the type container */
template<class NewList, class List>
struct rename_container;
template<template<class...> class NewList,
template<class...> class List,
class... ... | Seems there is a typo, it should be
/* Change the type container */
template<template<class...> class NewList, class List>
struct rename_container;
and probably:
rename_container<std::variant, std::tuple<int, float, double>>::new_list v;
// v is std::variant<int, float, double>
|
65,386,509 | 65,390,756 | Checking for the intersection of a 4D line segment and a 4D convex polytope | I have two 4D shapes: a polytope composed of two triangles with each side connected to the corresponding side on the other triangle (think triangular prism, but not necessarily straight) and a line segment.
I don't need to know where they intersect, just whether they intersect or not. How can I check for this?
| Your convex polytope is delimited by a number of hyperplanes, of equation ax+by+cz+dw+e = 0. Considering a point inside the polytope, you can adjust the signs so that all inside points verify ax+by+cz+dw+e ≥ 0 for all hyperplanes.
Now a line segment will have parametric equations like
x = (1-t)x'+tx''
y = (1-t)y'+ty''
... |
65,387,589 | 65,388,600 | short doesn't overflow visual c++ 2017 | Input of 32760 and 9 print out 32769, not -32767.
I don't know what else to do, it's a simple program, but it doesn't work as I want.
#include <iostream>
using namespace std;
int main()
{
short a, b;
cin >> a;
cin >> b;
cout << a+b;
}
| The result of the arithmetic operation a+b is not of type short. Instead the rules of integer promotion have it that the operands are first promoted to a larger integer type before addition.
To make it "work" as you want, then something like this will force integer overflow (that you seem to want to see):
short x = a +... |
65,387,660 | 65,387,872 | Error converting a char[] string to uppercase | This code is giving me an error that sptr was not declared in the while loop.
#include<iostream>
#include<ctype.h>
#include<stdlib.h>
using namespace std;
void convertToUppercase (char *s);
main()
{
{
char s [40]="Welcome to gbk gang";
cout<<"Before converting The string is! "<<s<<endl;
void *convertTo... | The code shown has multiple syntax mistakes.
Starting with a spurious { that causes the code from void convertToUppercase(char *sptr) onward to become part of main() rather than be in a separate function definition. void convertToUppercase(char *sptr) itself should not compile inside of main(), you should have gotten ... |
65,387,853 | 65,387,899 | Optimization: Is it faster to multiply a float by an integer or another float | If I am trying to multiply a float by a whole number is it faster to multiply it by a whole number being represented by an integer
int x;
...
float y = 0.5784f * x; //Where x contains a dynamically chosen whole number
or by another float (provided there is no loss in accuracy)
float x;
...
float y = 0.5784f * x; //Whe... |
Is it faster to multiply a float by an integer or another float
In general, float * float is faster, yet I suspect little or no difference. The speed of a program is a result of the entire code, not just this line. Faster here may cost one more in other places.
Trust your compile or get a better compiler to emit co... |
65,388,432 | 65,388,599 | How close message box after closing parent process opened using CreateProcess() | I want auto check bad or good for run my .exe files. For example for this binaries I have missing dll's, and when I use CreateProcess it's not return error and provide me system MessageBox("Dll is missing"). If I close it by hand, methods return exitCode STATUS_DLL_NOT_FOUND. I want that from some timeout all system m... | Call UINT oldErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS); before CreateProcess, and make sure that CREATE_DEFAULT_ERROR_MODE is not set in the dwCreationFlags parameter, so that the child process inherits the error mode of the parent. Per docs, this "does not display the critical-error-handler message box, instead... |
65,388,883 | 65,388,931 | C++: How to create a multiset of objects of a class? | Here is my class declaration:
class Person
{
private:
string name;
public:
void showData()
{
cout << name << endl;
}
void insertData()
{
cin >> name;
}
bool operator<(Person p)
{
return name < p.name;
}
};
Now I am trying to create a multiset of objects ... | You need to define your operator< in a slightly different way. I would define it as a friend not a class member, but if it is a class member it should be const.
So this is OK
class Person
{
...
bool operator<(Person p) const
{
return name < p.name;
}
};
but I would do it like this
class Person
... |
65,388,969 | 65,389,045 | how to convert 'std::vector<double>' to 'double' in initialization | I'm trying to make quicksort program. I just couldn't understand why and how this error is coming. I've tried every method online but I'm unable to catch the issue. If I'm doing this with array in place of vector, I'm getting correct output but with vector error is coming.
My errors are:
.\quicksort.cpp:7:28: error: ca... | References not pointers
int partition(vector<double>& values, int start, int end) {
void quicksort(vector<double>& values, int start, int end) {
If you used a pointer (but you shouldn't) the correct code would be
double pivot = (*values)[end];
Pointers are not the same as the things they are pointing to, you have to... |
65,389,235 | 65,389,837 | How to find fibonacci sums of huge numbers? | I'm solving a CSES problem in which I've to find the sum of first 'n' Fibonacci numbers. The code:
#pragma GCC optimize("Ofast")
#include <iostream>
using namespace std;
int main()
{
unsigned long long int n;
scanf("%llu", &n);
unsigned long long int seq[n];
seq[0] = 0;
seq[1] = 1;
unsigned ... | In this problem
F[i] -> i th Fibonacci number. MOD = 1e9 + 7. n < 1e18
F[n] % MOD = ?
F[n] = F[n-1] + F[n-2]
if you calculate this with loop you get TL
that`s way you can optimize this solution
now you calculate F[n] with recursion
F[2*n] = - F[n] * F[n] + 2 * F[n] * F[n+1]
F[2*n+1] = F[n] * F[n] + F[n+1] * F[n+1]
here... |
65,389,415 | 65,406,730 | How to generate global scroll events and disable mouse movement in Windows 10 (C++)? | I'm writing a program to implement chiral scrolling on a touchpad. I have the code to read the raw touchpad data, and I have a rough idea of how I want to implement the gesture. My question is how to implement the scrolling behavior. These are my requirements:
My program needs to be able to generate scrolling events, ... | I think hook and SendInput can meet your needs.
Here is a quick gif demo.
Run the code,
Press "L" key => install mouse hook(start)
Press left mouse button => Start scrolling
Press right mouse button => Stop scrolling
Press "P" key => uninstall mouse hook(end)
After the hook is installed, the mouse cannot be moved. Pr... |
65,389,583 | 65,389,633 | compiler error in accessing first and second of pair inside a map in c++ | What is the problem in line of code inside inner for loop if else block??
Accessing first and second of a pair inside a map is creating problems
#include <iostream>
#include <unordered_map>
#include <utility>
using namespace std;
int main() {
int t; cin>>t;
for(int i = 0; i < t; i++){
int n; cin>>n; in... | I think you're mixing up between iterating on a hashtable, and accessing its value with a provided key.
In your first loop, to acess the pair <int, int> value, you just do p[num].first (first int of the pair) or p[num].second.
It's not like your iterator loop, where it->first points to the key, and it->second.first & i... |
65,389,654 | 65,390,634 | how xcodebuild to pass WARNING_CFLAGS to buildsettings | xcodebuild -project MyProj.xcodeproj -scheme MyLib WARNING_CFLAGS='-Wno-shorten-64-to-32
It seems like not workable...
|
Go to Build Phases of your Xcode project.
In compile sources, select all files you want to compress the error for
Add -Wno-shorten-64-to-32 to the "Compiler Flags" column
|
65,390,252 | 65,390,298 | opengl glDepthRange object disappearing on Z depth |
Lines are dissapearing when z depth increases while rotating the object around x axis by 10 degrees. I edited the glDepthRange value to -100,100 or higher but nothing changes. How can i solve this?
void render()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
if( gRenderQuad )
{
glBegin( GL... |
I edited the glDepthRange value to -100, 100
This is not possible. The values for the depth range must be in [0.0, 1.0]. You can just set a sub range of the range [0.0, 1.0]. See glDepthRange.
If you want to increase the viewing volume, you need to use a projection matrix. An Orthographic projection can be set with g... |
65,390,467 | 65,392,249 | Passing lambda as a template parameter? ( c++20, lambdas in unevaluated context) | I know this question has been asked before, but none of them addressed the c++20 lambdas.
I've been looking at the new c++20 features, and one of which caught my eye is the possibility of having lambdas in unevaluated contexts.
I've seen that you could write code like the following on Jason Turner's video:
std::unique_... | As mentioned in the comments, the problem is that your lambda captures u. Therefore, you the lambda cannot be instantiated from just its type in C++20. However, if you pass the lambda directly as a parameter, not its type, and you use an array instead of a vector (vector's constructor and operator[] are not constexpr),... |
65,390,597 | 65,390,665 | LNK2019 From Unresolved External Symbol _main in MSVCRTD.lib For New DLL Project | I've begun a new C++ solution in Visual Studio 2019 which contains two projects (hereafter: project1 and project2).
Project1 is set as a DLL project and has no main() or _main() function. Project2 is set as the startup project and contains the main() function.
Project1 is receiving the following error on build:
CODE: ... | Whoops:
I forgot to remove the x86 platform from the project properties. For anyone experiencing this issue in the future:
If you wish only to build for x64, from the properties dialogue select 'Configuration Manager'. Then expand the 'Active solution platform:' dropdown and select 'edit'. Select the configuration you ... |
65,390,927 | 65,391,251 | define a function to return specified type of std::variant c++ | I am almost new to using c++17 rules. My question is straightforward; how can I access the std::variant types in the same order I defined them? Something like the following code that I know is not working!
#include <variant>
#include <iostream>
using myVariant = std::variant<double, int, std::string>;
template<typena... |
how can I access the std::variant types in the same order I defined them?
No need to write it yourself - std::get already does that. Just:
double c = std::get<0>(b);
|
65,390,935 | 65,391,121 | How do you Qualify a Type Name in a Constructor for an Object which has a Member of the Same Name? | Suppose I have the following 2 structs.
struct ErrorCodes
{
const unsigned long UsbErrorCode
const DWORD DriverErrorCode;
ErrorCodes(const unsigned long usbErrorCode, const DWORD driverErrorCode)
: UsbErrorCode(usbErrorCode),
WinDriverErrorCode(winDriverErrorCode)
{
}
}
struct Resp... | Just add :: to ErrorCodes type if it's in global namespace or ns:: if it's in namespace ns or whatever name you would like. Like ::ErrorCodes. And as mentioned by @goodvibration in comment it's better avoid such name collisions.
const ::ErrorCodes ErrorCodes;
:: is the scope resolution operator.
|
65,390,973 | 65,393,255 | Communication between browser extension and windows service | I have a browser extension(For chrome, Firefox, Edge) and now I want to query some info from the extension to the windows service which is running on the same machine.
I need to pass some strings from the extension and the windows service will process these strings and return the processed strings.
I have tried WebAsse... | You can use native messaging (Chrome docs / MDN)
Create an executable like this:
json_object process_string(std::string_view s) {
// Example code
std::string result(1000);
UINT sz;
HRESULT status = CallWindowsApi(s.data(), s.size(), result.data(), 1000, &sz);
if (FAILED(status)) {
return my_... |
65,392,043 | 71,981,597 | VS code error "Permission Denied" when printing simple output | I am trying to set up my c++ environment in Visual Code Studio but the error here is Permission denied and I tried giving it administrator permission but it didn't work out.
This is the code :
#include<iostream>
using namespace std;
int main()
{
cout<<"Hello World";
return 0;
}
This is the error
PS D:\Work\VS... | I solved it by removing all of "tasks.json" content and going to Terminal->Configure Default Build task then I selected
|
65,392,418 | 65,392,703 | Why is the argument for Wire.write () type-casted? | When I see code written for communication via I2C with external EEPROMs and RTCs and such, I always notice that when sending the register address bytes and data byte using Write.write(), the hexadecimal address is type-casted into a byte or int like below:
static uint8_t read_i2c_register(uint8_t addr, uint8_t reg) {
... | Because the requestFrom method is overloaded. There is a requestFrom(int, int), taking two integers and a requestFrom(uint8_t, uint8_t) taking two bytes.
the above call Wire.requestFrom(addr, 1) does not exactly match any of them as the parameters are a uint8_t and an int. And the compiler is not allowed to favor one o... |
65,392,546 | 65,394,806 | How to destroy wxWidgets Popup ONLY on clicking button inside it? | I have created a popup using "wxPopupTransientWindow" and added some text and a button. Now I want to destroy this popup only on Clicking this particular button. Right now, Popup will get destroyed if click anywhere outside it.
Here is what I have tried so far.
SimpleTransientPopup::SimpleTransientPopup(wxWindow *paren... | By overriding "wxPopupTransientWindow::Dismiss()" I was able to close the popup when button is clicked.
void SimpleTransientPopup::Dismiss()
{
if (m_bGotItClick) {
wxLogMessage("%p SimpleTransientPopup::Dismiss", this);
wxPopupTransientWindow::Dismiss();
m_bGotItClick = false;
}
}
|
65,392,797 | 65,393,624 | How can I overcome the issue of output console disappearing after taking input or compiling in Visual Studio-2013 for C++? | I am new to C++ coding and in Visual studio environment. My simple code to find a sqrt of a number is being compiled and even run but the console disappears after taking number as input and I am left with the debugging messages and final message of Program terminated with exit code 0. Basically no output is shown.
#inc... | You can temporarily add a simple line at the end of code:
system("pause");
Don't forget to include: #include <cstdlib>
|
65,393,089 | 65,393,344 | Overriding << operator for templated struct | numcpp.h file
#include "iostream"
namespace numcpp{
template<typename T>
struct Vector
{
std::vector<T> v;
};
template<typename T>
struct Matrix
{
std::vector<T> m;
//template<typename T>
friend std::ostream& operator << (std::ostream& out,... | What you normally want is to define a template in your header file. The definition needs to be available at the call-site to allow the compiler to make an instatiation of the template.
If possible, the easiest way is to put the definition in the class definition.
template<typename T>
struct Matrix
{
std::vector<T> ... |
65,393,337 | 65,406,863 | Generating the background of imatest color error chart generated by using color checker? | I am having some trouble finding the background of the following plot made using imatest. Basically what I want to know is that how, or from where, can I find the background of this plot. The imatest website mentions that the colors of the chart are generated at a constant Luminance L* = 90 and by varing a* and b* fro... | Just for fun, if anyone wants a Python OpenCV version, I made one like this:
#!/usr/bin/env python3
import cv2
import numpy as np
# Set size of output image
h, w = 500, 500
# Create "L" channel, L=90
L = np.full((h,w), 90.00, np.float32)
# Create "a" channel, -80 to +80
a = np.linspace(-80,80,w,endpoint=True,dtype=... |
65,393,592 | 65,395,865 | How to initialize object of a class if the values are stored in a .txt file in C++ | How to initialize an object of a class if the values are stored in a .txt file in C++
I'm Making A Data Management System Which has 3 Options:-
Add a new student.
View a student's information.
Delete a student.
And the code looks something like this
#include <iostream>
using namespace std;
//Struct Containing The ... |
Explore data structures such as sets and maps in Cpp.
Apart from a thousand possible solutions of this problem, here is one:
class Student{
string name = "no_student";
/* appropriate members */
};
map<string, Student> m; // mapping from string-name to Student-objects
\\ ADDING A STUDENT:
m[name] = Stude... |
65,394,322 | 65,394,453 | Why `std::string str(nullptr)` and `std::string str=nullptr` is wrong? Could someone explain the reasons in details? | Why std::string str(nullptr) and std::string str=nullptr is wrong? Could someone explain the reasons in details?
| Such examples compile because there exist a std::string(const char*) constructor for accepting null-terminated strings, which is the standard version of storing strings in C. Also, arrays eagerly decay into pointers, in order to allow code such as std::string("Ahoj") to compile.
It is wrong, because the constructor exp... |
65,395,109 | 65,423,207 | How to send float value to fragment shader? | I have no idea, how can I pass the float to my fragment shader. I want to change
float ambientStrength;
as a value taken from mainloop. There should be a case ("O" key) which change this ambientStrength to 1.0 for example.
case sf::Event::KeyPressed:
switch (windowEvent.key.code) {
case... | Include "uniform float ambientStrength" in fragment shader and use this in your C++ code keystroke:
GLint loc = glGetUniformLocation(ProgramObject, "ambientStrength");
if (loc != -1)
{
const float value = 0.5;
glUniform1f(loc, value);
}
|
65,395,588 | 65,395,790 | producing "unhandled exception X at memory location Y" when checking every pixel of an grayscale image | I am trying to solve a problem where I have to check every pixel from a 640x480 cv::Mat (Greyscale Video Image -> cv::Mat MainImageSW (global)) and check if the pixel above, below, to the left and to the right is equal or below the Threshholdvalue ( GetTreshholdSW() ).
My target matrix XY_ThreshholdMat is also 640x480 ... | cv::Mat Matrix255(GetPixmapWidth(), GetPixmapHeight(), ...
should be
cv::Mat Matrix255(GetPixmapHeight(), GetPixmapWidth(), ...
Because of this mistake you access the elements out of bounds and your program therefore has undefined behavior.
|
65,395,833 | 65,402,143 | Program window doesn't show up | I'm starting programming in C++ and want to start making applications with graphics and user interface.
I've watched many tutorials on the subject,
and have finished the first part of the tutorial
but the window refused to pop up, and I know that it's working because there are no errors,
and I can see it running in ta... |
window refused to pop up, and I know that it's working because there
are no errors, and I can see it running in task manager.
You don't check the error for RegisterClass and CreateWindowA functions calls.
Check the return value of RegisterClass() you will find that the return value is zero, that indicates failure. To... |
65,396,043 | 65,396,257 | how to write a function that links other functions in C | Lets say I have functions A, B, & C.
I would like to write a function which looks like:
Linker(A,B,C,{{0,1,0},{0,0,1},{0,0,0}});
where the arrays correspond to which element in the first list will be called. In other words, when A finishes, it starts the second element B, when B finishes it calls the third element C, ... | You could do this by setting up some "processing" class that stores pointers to your functions and the links you want to establish between them:
class processor {
private:
std::vector<void (*)()> funcs;
std::vector<std::pair<int, int>> links;
public:
void add_func(void (*func)()) { funcs.push_back(func); }
... |
65,396,085 | 65,396,456 | Different behavior of consteval in GCC and MSVC (not work) | Consider the following code:
#include <cstdint>
#include <vector>
class ClassT
{
public:
consteval static size_t GetSize()
{
return sizeof(int);
}
void Resize()
{
_Data.resize(GetSize(), 0);
}
std::vector<uint8_t> _Data;
};
int main()
{
ClassT Object;
Object.Resiz... | This looks like an MSVC bug. It might even be the same as this existing one- #1224555.
Minimal example:
consteval int test() { return 0; }
int main() {
return test(); // error C7595: 'test': call to immediate function is not a constant expression
}
|
65,396,510 | 65,396,602 | Why does the code promt user for an input but exits without waiting for it? | I am writing a simple piece of code for a bigger project, now this piece of code asks a user to enter two arrays - X and y.
vector<double> X;
double element;
while (cin >> element)
{
X.push_back(element);
}
cout << "Enter array y: " << endl;
vector<double> y;
while (cin >> element)
{
y... | The first loop will go on for as long as extracting a double succeeds. When it eventually fails, the stream (std::cin) is set in a failed state and any further extraction will also fail, so your second loop will fail immediately.
One possible way to fix that is do reset the state and ignore the rest of the line after y... |
65,396,657 | 65,397,492 | How can I multiply two matrices if I only store non-zero elements in a list<list<pair<int,double>>>? | So I got my Data structures and algorithms project. I basically need to develop a class Matrix with following atributes:
list<list<pair<int,double>>>, (In which are only non-zero elements of a Matrix. Value of a certain element is stored as the second argument of a pair, and the first argument of a pair represents an ... | The main idea consists in having convenient primitive to set/get the value at position (i, j) of a matrix, its number of rows and its number of column.
For sake of simplicity, I replaced in the following code your top list by a vector (it's more efficient as you have random access to the i-th value):
#include <cassert>... |
65,396,779 | 65,396,805 | Can someone tell me what is wrong with this statement? | How is this statement
int* p = new int[10];
p[10] = 5;
delete[] p;
different with this statement ?
int* p = new int[10];
*p = 5;
delete[] p;
I wanna what is wrong with the first code. I'm kinda new to C++, so any explanation is appreciated. Thanks.
| The behaviour of p[10] is undefined as the array has only 10 elements and the first element is at position 0. You can access p[0] (which is the same as *p) to p[9] inclusive.
In other words, arrays in C++ are zero-based. Cf. Fortran, for example, where they are one-based.
|
65,396,833 | 65,397,515 | Testing three points for collinearity in a numerically robust way | You can test that three 2D points, a, b, and c, fall on a line by noting the slope of line segment (a,b) will have to be the same as that of (b,c), or by noting that the area of the triangle they define will be zero if and only if the three points are collinear. I chose the former method because the math seemed more co... | For a numerically meaningful test, consider the (double) area over the length of the longest side. This gives you the deviation of the middle point from the line by the two others. It is in units of length.
|
65,398,140 | 65,398,840 | Does NRVO happen in static member variables initialization? | I have got a class with a large static std::array that needs an expensive computation to be initialized, so i defined a static method to perform it. I don't know however if some copy happens or maybe the computation is performed inside the member array.
class A
{
static inline array<double, 100000> a = fill_a();
st... | I don't know what "NRVO" is. From context I guess you are referring to copy elision. Copy elision is allowed in a few cases. In particular, when returning a non-volatile local variable with the same type as the function's return type, copy elision is permitted (see [class.copy.elision] paragraph 1.1.
With C++17 copy-el... |
65,398,402 | 65,398,663 | What is the purpose of taking the largest number as an input when you are computing the largest value in a sequence? | int main ()
{
double largest; cin >> largest;
double input;
while (cin >> input)
{
if (input > largest)
{
largest = input;
}
}
}
Why are we taking largest as a user input when clearly that is what we want out of this code fragment?
| If you don't set largest to something, you're going to have problems; having an unset stack value means largest has a garbage value and you'll get undefined behavior when you test if (input > largest). So that's the worst option; you don't want nasal demons.
You could initialize it -HUGE_VAL, or -DBL_MAX if you must av... |
65,398,876 | 65,399,000 | c++ why the following variable doesn't go through virtual table | Assume we have a code like this:
struct X{
virtual void foo(){}
};
struct Y: X{
void foo() override{}
}
And we do something like this:
void test(Y& ref){
Y local_y;
local_y.foo();
ref.foo();
}
In the first call (in some compiler), the first call won't go through the vptr at all, while the second one w... |
That made sense to me because from what I know only references and pointers are polymorphic in c++, while regular variables aren't, so there is no need to through the table.
does what I thought make sense?
No. Runtime polymorphism isn't somehow "disabled" for "regular variables". A virtual function is a virtual funct... |
65,399,184 | 66,726,399 | Vim's `:compiler gcc` has an issue with `make: ***` | It seems to be that Vim's :compiler gcc has a bug. It treats make: *** as an error and therefor opens an empty buffer named build.make when opening quickfix.
Here is a screenshot:
I don't want to bother Vim people for no reason. It looks like a bug to me, but maybe I a m wrong, so I want a second opinion: who else thi... | I eventually opened an issue at Vim's Github. Here is the link: https://github.com/vim/vim/issues/7536. TL;DR - since I use cmake and not make, :compiler gcc was not working as expected, I should have used :compiler cmake (such a thing does not exists).
|
65,399,888 | 65,402,715 | Error MBS4019 in Visual Studio 2019 when running main.cpp function | I'm trying to run the main function of a c++ library of mine but it doesn't wanna work. Returning as error:
The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\Microsoft.Cpp.Default.props" was not found. Confirm that the expression in the Import declaration "C:\... | You should first check whether you have the file Microsoft.Cpp.Default.props under C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\ on your C disk. That file works for v142 platform toolset.
And from the message, your project uses the file under C:\Program Files (x86)\Microsoft V... |
65,400,089 | 65,400,306 | No instance of everloaded function "Getline" matches the argument list | There are many variations of this question on this site but all of the answers assume the user has a good fundamental knowledge of how C++ works. As a beginner, this is not good for me.
I have a very simple subroutine attempting to print a single item from a csv file.
void parseCSV()
{
int line = 0;
ofstream m... | Problem:
std::getline first argument should be an input stream. std::ofstream is an output stream.
std::getline takes a std::string& as second parameter, not an int.
Solution:
You should probably open your file as an std::ifstream and use either the std::ifstream::operator>> or std::getline to fill a std::string an t... |
65,400,738 | 65,401,996 | Invoke slot of child of child of QQmlPropertyMap? | Before marking this as a duplicate of "Can't call slot or Q_INVOKABLE from QML in subclass of QQmlPropertyMap," please read the final response (https://stackoverflow.com/a/18674363/447438).
I am working on a design where I have a class (call it MyBaseClass) that inherits from QQmlPropertyMap. It implements some additio... | Observe that the 2-argument QQmlPropertyMap constructor is a template constructor that needs the type of the [most] derived class (the documentation could be clearer on that, but that's the only way to make it work with automagic registration). The only type it ever sees is that of MyBaseClass.
You need to pass the typ... |
65,400,866 | 65,401,051 | How I can draw a tile from a texture tilemap in an OpenGL shader? | So I have an AtlasTexture that contains all the tiles I need to draw a tile map.
Right now I pass the AtlasTexture through a uniform, and the idea is to change the texture coordinate to select just the portion I need from the atlas.
The issue is that I can only specify on the fragment shader to cut the texture from the... | Use an Uniform variable for the offset. `vec2(1.0/3.0 + aTextureCoordinate.x / 3.0f, aTextureCoordinate.y); "selects2 the 2nd tile. Use a uniform instead of 1.0/3.0:
#version 330 core
layout(location = 0) in vec2 aPosition;
layout(location = 1) in vec2 aTextureCoordinate;
out vec2 textureCoordinate;
uniform float tex... |
65,401,067 | 65,401,092 | Nullptr - bool assignment | Why we can't directly assign nullptr to a bool object? For example, the flag object's assignment causes an error. Visual Studio compiler gives that: "C++ a value of type cannot be assigned to an entity of type".
int main(){
int x = 10;
int *ptr = &x;
bool flag = ptr;
flag = nullptr;
}
but below... | It's kind of tricky. We have to carefully examine the C++ standard. First, "Standard Conversions" states:
All pointers have implicit conversion to boolean (per [conv.bool])
And this conversion simply just converts null pointers to false. So it seems like we should be able to directly assign a null pointer constant to... |
65,401,101 | 65,401,387 | What is the fastest way to count all set bits? | What is the fastest way to count all set bits?
The number from which I am counting bits is from 1<=n<2^63, only positive values.
For now I use bitset from the library and it is pretty fast, but if there is any faster option I would like to know.
In the worst case scenario I have over 1 billion iterations, so I am look... | Here is a demo of what I mean with a balanced lookup table.
This one is heavy on the size saving.
You can adapt the concept to lookup tables of size e.g. 64 or 256, speeding up considerably.
#include <iostream>
using namespace std;
int main()
{
unsigned long long int input=679043ULL; // just a big number, for demo... |
65,401,336 | 65,401,467 | Avoid tautological-compare warning in template | I have a template class that should return different values if the (unsigned) parameter is even or odd, like in this test case:
template <unsigned X> class t {
public:
static int get(int *n) {
if constexpr (1 == (X & 1))
return n[X] + n[X-1] + t<X-2>::get(n);
else
return n[X]... |
Is there a way to avoid this warning without resorting to writing template specializations depending on another parameter?
In the latest version, gcc does not warn about this so adding an exception seems reasonable:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtautological-compare"
if constexpr (1 ==... |
65,401,573 | 65,401,664 | Why is implicit conversion not applied to templated function parameter? | I'm having an issue with some template stuff that I've narrowed down to the following example (C++17):
template <typename T> struct item {
operator item<const T> () const { return item<const T>(); }
};
void conversionToConstRefWorks (const item<const int> &) { }
template <typename T>
void butNotWhenTemplated (cons... | item<int> i;
template <typename T> void butNotWhenTemplated (const item<const T> &) { }
butNotWhenTemplated(i);
According to template argument substitution rules, no T could be found for item<const T> to match item<int>. This fails with an hard error way before any conversion (builtin or user-defined) could be consid... |
65,401,655 | 65,402,620 | Fast STL way to find input that produces maximum output of function? (contiguous integer inputs) | To improve the readability, I'm trying to get out of the habit of reinventing the wheel.
Problem:
Consider a black-box function, Foo, which has an integer as input and output. We want to find the input that maximises the output. Consider that all the possible inputs belong to a single, contiguous range of integers; and... | C++20 ranges can do this:
template<typename T, typename F>
T argmax_iota(T begin, T end, F &&score) { // can't really think of a good name for this; maybe it doesn't even deserve its own function
return std::ranges::max(std::views::iota(begin, end), std::less{}, std::ref(score));
// over the values in the range... |
65,402,444 | 65,420,795 | GCC and Clang printf format check doesn't work with decltype in a template function | This code compiles even with -Wall -Werror but it should not:
#include <cstdio>
template <typename T>
void f()
{
decltype(printf("%u", 1.0))* p = nullptr; // format does not match args
(void)p;
}
void g()
{
f<int>();
}
If f() is not a template, GCC and Clang refuse to compile it, as I expect and desire. ... | You might try:
template <typename T>
void f()
{
if (false) { printf("%u", 1.0); } // format does not match args
}
You might need some additional pragma to silent warning about condition evaluate to always false and or unreachable code.
|
65,402,557 | 65,402,795 | Passing vector of unique_ptrs by reference | This is more of a best practices type of question. Please assume that there are no issues with correctness.
Is it okay to pass around a vector of unique_ptrs by reference between functions in the same class? I want to do this to apply some changes to all the elements in the vector.
Related reason for confusion: isocpp ... | Whereas from std::unique_ptr<myType>, we can easily use /*const*/ myType* or /*const*/ myType& when no ownership transfer is involved.
There are no trivial/simple types to represent the equivalent for range (std::vector<std::unique_ptr<myType>>):
transforming into std::vector<myType*> need extra vector.
the lazy/range... |
65,402,561 | 65,407,588 | Template overloaded operator in Eigen::Matrix | I got this basic code working:
#include <iostream>
#include <Eigen/Dense>
using T12 = Eigen::Matrix<double, 2, 1>;
using T22 = Eigen::Matrix<double, 2, 2>;
template <typename Der1, typename Der2> T22
operator^ (const Eigen::MatrixBase<Der1>& d1, const Eigen::MatrixBase<Der2>& d2) {
return d1 * d2.transpose();
}
vo... | You can derive the size of the return type from Der1::RowsAtCompileTime:
template <typename Der1, typename Der2>
T2n<Der1::RowsAtCompileTime>
operator& (const Eigen::MatrixBase<Der1>& d1, const Eigen::MatrixBase<Der2>& d2) {
return d1 * d2.transpose();
}
Or fully generic (assuming Der1 and Der2 have the same scalar... |
65,402,973 | 65,403,041 | Calculating the sum of an array of differences | I have a code that calculates the mean of an array of 10 numbers then calculates the difference between the mean and each number. Now I need to add up all the differences but I don't know how. This is what I have so far:
#include <stdio.h>
#include<math.h>
int sum,mean,difference;
int main(void) {
int i,j;
int n... | You need to take a new variable for the sum of differences and do the same like you did for calculating the mean.
#include <stdio.h>
#include<math.h>
int sum,mean,difference,sum_difference;
int main(void) {
int i,j;
int n[10] = {1,7,5,8,3,5,6,8,2,15};
for(j = 0; j < 10; j++ ){
sum = sum + n[j];
}
me... |
65,403,328 | 65,403,881 | How To Fix Unexpected Loop In C++ | I'm making a simple data management system which have 3 services
Add a student.
View a student information.
Delete a student
The code looks like this :
#include <iostream>
using namespace std;
enum Services
{
Add=1,
View,
Del
};
class Student
{
public:
string Name;
int Age;
string Gender;
... | The !cin in your loop condition returns true if the stream is in an error state (eg. reading an int failed). Not to mention the strange != in your conditions that @dxiv mentioned. What you probably meant was the following:
do
{
cout << "\nWhich Service Do You Want To Access: ";
int Input = 0;
cin >> Input;
... |
65,403,999 | 65,404,009 | error:expected intializer before 'void'(How to fix it?) | I got this problem when I tried to code for competitive programming courses, but I got this problem about void:
Code 1:
On the first code, it could be executed properly. the void didn't need to be initialized and everything works really well.
#include <iostream>
#include <cstdio>
#include <bits/stdc++.h>
#define ll ... | You're missing a semi-colon in line int a; int b;int c[10000]
|
65,404,127 | 65,405,463 | Sort class member functions and variables in ascending order in header file | Given a class declaration thus:
class foo_{
public:
int t1();
const std::vector<int> & ureference();
private:
std::vector<std::pair<int, int>> vecofpairs;
string name;
}
I would like to sort the public functions in ascending order of their names. The following command in vim after appropriate visual s... | You can use Vim's built-in :sort command to sort on arbitrary parts of the lines.
The built-in :sort can take a pattern, and then either skip that pattern or match that pattern to decide what to use as a key for sorting.
For example, in your case you can use /.* / as a pattern to skip everything until the last space on... |
65,404,197 | 65,500,147 | Failing to install gtkmm / gtk+ | So i am new on the platform, i use c/c++ and i have interests in graph interfaces so i decided to use gtk+and gtkmm with visual studio.
First, i downloaded gtk for the gnome project. I followed all the steps and i got this after a manual run :
\\\ test23.cpp
#include <gtkmm.h>
int main(int argc, char* argv[])
{
... | Use JHbuild, its your friend when building GNOME applications from source !
Run jhbuild build gtkmm --nodeps, the built files will be installed in $HOME/jhbuild/build. To compile your application with it, you must export the environment variable PKG_CONFIG_PATH as follows:
export PKG_CONFIG_PATH="$HOME/jhbuild/build/li... |
65,404,205 | 65,404,874 | std::cout calls in C++ is giving inconsistent results with linked list on my compiler | I've been trying to create a function that turns an array into a linked list. It creates an array of nodes the same length as the array and stores each value in the array into the data field of each node, and sets up the pointers similarly. I quickly realized it wasn't working since print() is giving undefined results ... | This is a very common problem.
The issue is that your code is using pointers to objects which have been destroyed. Take a look at your toNode function (with comments)
Node toNode(int ar[], int size) {
Node nodes[100];
...
for (int i = 1; i < size; i++) {
nodes[i-1].next = &nodes[i]; // pointers to '... |
65,404,305 | 65,406,135 | Why is the defaulted default constructor deleted for a union or union-like class? | struct A{
A(){}
};
union C{
A a;
int b = 0;
};
int main(){
C c;
}
In the above code, GCC and Clang both complain that the default constructor for union C is defined as deleted.
However, the relevant rule says that:
A defaulted default constructor for class X is defined as deleted if:
X is a union tha... | This was changed between C++14 and C++17, via CWG 2084, which added the language allowing an NSDMI on (any) union member to restore the defaulted default constructor.
The example accompanying CWG 2084 though is subtly different to yours:
struct S {
S();
};
union U {
S s{};
} u;
Here the NSDMI is on the non-trivial... |
65,404,964 | 65,405,572 | why does this routine return an array of length 0? | everyone, here is a function I wrote to read a user input which is a vector of double of unknown size, the input must terminate when 'enter' is pressed:
vector<double> read_array()
{
vector<double> array_in;
double el;
while (!cin.get())
{
cin >> el;
array_in.push_back(el);
}
... | I don't know what you hope std::cin.get() does but based on your comment it seems you hope that it somehow deals with end of lines: it doesn't. It simply reads the next character which is unlikely to do you much good. In particular, if the character is anything but '\0' negating it will result in the boolean value fals... |
65,405,010 | 65,405,101 | what is c++ std::unordered_map default container? | I'm studying about inside logic of unordered_map.
And found that It uses container. And uses key values to find value.
Is the default container of unordered_map std::vector??
And is other containers, for example std::map is able?
| unordered_map is implemented via hash table, so there is no such thing here as "default container".
Signature:
template<
class Key,
class T,
class Hash = std::hash<Key>,
class KeyEqual = std::equal_to<Key>,
class Allocator = std::allocator< std::pair<const Key, T> >
> class unordered_map;
The only ... |
65,405,160 | 65,405,216 | In main(), how to get value from a static variable inside another function? | I want to get a value in main() from the functionTwo().
The functionOne is designed to calculate the sum of the functionTwo().
Why I cannot use this sentence to pass the j value to int b?
int b = functionOne();
//function 0ne
int functionOne(int x) {
static int j = 0;
j = j + x;
return j;
}
//function T... | That int functionOne(int x) wants a parameter. That is why you cannot get it like you tried.
There is not clean way to do this, no intended way to get the value from a static variable inside a function. You do return it, but calling the function obviously has a side effect on the static variable, which is of course the... |
65,405,500 | 65,405,561 | strange overload = operator on some book, c-style? | I find some books which this kind of code:
but if I try to compile somethings similar, it says that miss argument?
struct Test {
double offsetDetected = 0.0;
Test() {}
Test &operator=() // removed here
};
what's wrong, and why books write this way those stuff? c-style?
| It is a binary operator.As the other asnwere mentioned it might have a typing error.
#include <iostream>
struct Test {
double offsetDetected = 0.0;
Test() {}
Test &operator=(const Test &obj); // removed here
};
int main() {
}
|
65,405,691 | 65,406,304 | How do I test if the result from boost::bimap "right.find" was found or not? | I am new to using boost::bimap so forgive me if this sounds like a basic question. I am using boost 1.75.0.
Take this snippet of code:
if (rBiMapStudentItemDescBefore.right.count(aryStrStudentItemDesc[i]) > 0)
{
auto it = rBiMapStudentItemDescBefore.right.find(aryStrStudentItemDesc[i]);
CString strNewStudentIte... | I still can't find actual documentation but I think I have it:
auto it = rBiMapStudentItemDescBefore.right.find(aryStrStudentItemDesc[i]);
if (it != rBiMapStudentItemDescBefore.right.end())
{
CString strNewStudentItemDesc = rBiMapStudentItemDescAfter.left.find(it->second)->second;
pEntry->SetStudentAssignmentTy... |
65,405,749 | 65,406,801 | Qt5 Label Changed Text Shows Corrupted | App works nice in Qt Creator but not in Visual Studio.
I try to learn C++ Qt5 GUI app in Visual Studio. Here is the basic app:
Click to button and change label text.
main.cpp
#include "Deneme.h"
#include "stdafx.h"
#include <QtWidgets/QApplication>
#include <QTextCodec>
int main(int argc, char *argv[])
{
QApplicat... | QTextCodec::setCodecForLocale( QTextCodec::codecForName( "UTF-8" ) );
ui.label->setText(QStringLiteral("Metin Değiştirildi!"));
|
65,405,827 | 65,406,052 | print two diamonds side by side | I wanna print two diamonds side by side, but my code prints 1 diamond.
I spent lots of time on it and really do not know what else to do.
Any help would be appreciated.
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int i,j,n, middle, spaceCount, starCount;
cin >> n;
middle = (n - 1) / 2;
for ... | You forgot to print you second diamond shape. Each iteration, you should print first a few spaces, then the stars, then the double of the spaces (to finish the first diamond and set spaces for the second diamond) and then you should draw you stars for your second diamond.
This is an example of code that prints two diam... |
65,406,022 | 65,406,064 | C++ templates: why is not the specialized function called? | The template function exists as a general and a specialized case:
#include <string>
#include <iostream>
using namespace std;
// General case
template<typename X> void whichOneIsLarger(X a, X b) {
(a > b) ? cout << "x [" << a << "] is larger than y [" << b << "]" : cout << "y [" << b << "] is larger than x [" << a ... | Because "hallo" and "world" are not std::strings, but c-style string literals (with type const char[6] and could decay to const char*).
You can pass std::string explicitly,
whichOneIsLarger(std::string("hallo"), std::string("world"));
Or use std::string literals (since C++14):
using namespace std::string_literals;
whi... |
65,406,066 | 65,407,335 | What is idc short for in H.264? | For exmaple, nal_ref_idc and profile_idc. I knew what they are, but I can not find the idc's full name.
|
profile_idc -> Profile identification for the Encoder
refer https://www.ti.com/litv/pdf/sprufd
I think IDC mean "identification" for the Encoder ,
this question may not programming relevant one
|
65,406,127 | 65,406,941 | How to pass method and call it with variable number of arguments | I have class CallProtector that is supposed to call method with variable number of arguments which suppose to protect call via mutex, but I can't figure out how could I pass object's method with their arguments. Here what I have so far:
class CallProtector
{
public:
template<typename F, typename ...Args>
void ... | Following might work for you:
class CallProtector
{
public:
template<typename F, typename ...Args>
void callProtectedMethod(F&& func, Args&&... args)
{
std::lock_guard<std::mutex> guard(m_guard);
func(std::forward<Args>(args)...);
}
private:
std::mutex m_guard;
};
and then use it ... |
65,406,212 | 65,406,347 | C++ use of explicit suggested by cppcheck | Is using the cast constructor bad?
Otherweise why a code quality checker (cppcheck in my case) would constantly suggest to add explicit before single parameter constructors?
What if I want to do
class MyClass {
A(int) {}
};
A a = 1;
If I follow the "suggestions" and write
class MyClass {
explicit A(int) {}
};
... | Such implicit class type conversion can be used easily without intention. With this converting constructor every function or member function which accepts MyClass as argument will accept also int. Therefore every int passed to such a function will be converted to a temporary MyClass which will be discarded after the fu... |
65,406,478 | 65,406,679 | How does OpenMP use the atomic instruction inside reduction clause? | How does OpenMP uses atomic instructions inside reduction constructor?
Doesn't it rely on atomic instructions at all?
For instance, is the variable sum in the code below accumulated with atomic '+' operator?
#include <omp.h>
#include <vector>
using namespace std;
int main()
{
int m = 1000000;
vector<int> v(m);
... |
How does OpenMP uses atomic instruction inside reduction? Doesn't it
rely on atomic at all?
Since the OpenMP standard does not specify how the reduction clause should (or not) be implemented (e.g., based on atomic operations or not), its implementation may vary depending on each concrete implementation of the OpenMP ... |
65,406,540 | 65,407,511 | CMake variable_watch doesn't show modification of a variable PKG_CONFIG_EXECUTABLE | I have invalid value of PKG_CONFIG_EXECUTABLE variable set by FindPkgConfig.cmake, so I wanted to check the reason. I've added variable_watch(PKG_CONFIG_EXECUTABLE) for this purpose. The output is following:
(...)
CMake Debug Log at /home/my/CMake/share/cmake-3.16/Modules/FindPkgConfig.cmake:27 (if):
Variable "PKG_CO... | According to documentation, variable_watch doesn't track accesses to the CACHE variables. And variable PKG_CONFIG_EXECUTABLE is actually a CACHE one.
However, reading a variable in CMake always uses non-cache version of the variable: the non-cache version is created upon the first variable dereference and is set equal ... |
65,406,795 | 65,406,925 | Unique Pointer Creating copy of the object but i want to avoid the copy | I read somewhere if you want to return a local variable via reference do it via smart pointers and the motivation behind this code is exacttly the same i want to return a Test class variable without it copy being created or in other words Return a local variable with reference . But Everytime return statement executes ... | 1> std::unique_ptr<Test> num() {
2> Test obj;
3> std::unique_ptr<Test> newInt = std::make_unique<Test>(obj);
4> return newInt;
5> };
In line 3 it creates a new Test object and copy-assigns obj to the new object.
The destructor is actually called for the obj variable.
In the example you provided, I don't th... |
65,406,823 | 65,407,161 | Is there a portable literal suffix for int64_t and similar types? | I was trying to understand std::variant:
#include <cstdint>
#include <variant>
std::variant<int64_t, double> v;
I wanted to assign an int64_t variant: v = 5L;
That compiles on x86_64 because int64_t is long. But it does not compile on arm, because int64_t is long long. The type deduction has now two equal choices bet... | No, there are no standard literals for fixed width integer aliases.
One potential workaround would be to use std::variant<long long, double> v;. Although long long theoretically isn't guaranteed to be exactly 64 bits (it may be wider, but not narrower), it is 64 bits on practically every system that supports long long ... |
65,406,916 | 65,407,001 | Cannot Run Because of Uninitialized local variable Error | #include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int calc(int m, int c, int d_T) {
int Q = m * c * d_T;
return Q;
}
int main(){
cout << "Enter mass/c/and delta temperature" << endl;
int val, val1, val2;
cin >> val, val1, val2;
int Q = calc(val, val1, val2);
... | You need:
cin >> val >> val1 >> val2;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.