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 |
|---|---|---|---|---|
71,400,185 | 71,424,134 | How do I use blitz++ | I am a beginner in c++. My focus of learning c++ is to do scientific computation. I want to use blitz++ library. I am trying to solve rk4 method but I am not getting the inner workings of the code(I know rk4 algorithm)
#include <blitz/array.h>
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace b... | #include <blitz/array.h>
#include <iostream>
#include <cstdlib>
using namespace blitz;
using namespace std;
/* This will evaluate the slopes. say if dy/dx = y, rhs_eval will return y. */
const double sig = 10; const double rho = 28; const double bet = 8.0 / 3;
void lorenz(double x, Array<double, 1> y, Array<double,... |
71,400,724 | 71,586,963 | Copying a Public key Mod from an Intel SGX Enclave to Untrusted area | I am developing a C pseudo-API in which Java code calls C code through the JNI, in which it connects to an Intel SGX Enclave. I have a function in which I create an RSA-Key pair to be used further on.
Create RSA Pair:
sgx_status_t create_rsa_pair(){
unsigned char p_n[RSA_MOD_SIZE];
unsigned char p_d[RSA_MOD_SIZE];
unsi... | Using ocalls to return information is not the way to go for this.
While I had failed previously with this Idea, the way to go is by adding a pointer and its size to a functions arguments in order to copy the results.
so
Enclave EDL
public sgx_status_t whatever([out,size=output_size]uint8_t* output,size_t output_size)
... |
71,400,850 | 71,400,889 | Polymorphic Vectors Without Object Slicing [C++] | I am trying to store a number of objects which are derived from a base class in a std::array(or any other container) without object slicing.
The desired output from the code snippet below is:
Hi from child1!
Hi from child2!
And the code:
#include <iostream>
#include <array>
#include <memory>
class Base {
public:
... |
Obviously the derived objects have been sliced.
Actually, no. They are not being sliced. You are doing the correct thing in storing base-class pointers to derived-class objects in your array.
No, the code doesn't work the way you want, not because of object slicing, but because you simply did not mark hello() as vi... |
71,401,084 | 71,404,002 | Extract an autonomous chunk of the dependency graph of a huge CPP project? | Consider Chromium codebase. It's huge, around 4gb of pure code, if I'm not mistaken. But however humongous it may be, it's still modular in its nature. And it implements a lot of interesting features in its internals.
What I mean is for example I'd like to extract websocket implementation out of the sources, but it's n... | Your compiler is almost surely capable of extracting this dependency information so that it can be used to help the build system figure out incremental builds. In gcc, for instance, we have the -MMD flag.
Suppose we have four compilation units, ball.cpp, football.cpp, basketball.cpp, and hockey.cpp. Each source file ... |
71,401,614 | 72,354,866 | How to Precompile <bits/stdc++.h> header file in ubuntu 20.04 / 22.04? | Is there any way to precompile the <bits/stdc++.h> header file in ubuntu 20.04 like we can do in Windows OS so that I can execute programs faster in my Sublime text editor?
I use the FastOlympicCoding extension for fast execution, but I miss the old way of using an input-output file. I searched everywhere but didn't fi... | So, After having help from @TedLyngmo's answer and doing a little bit more research, I decided to answer the question myself with more clear steps.
PS: This answer will be more relatable to those who are using sublime with their custom build file and are on Linux OS (Ubuntu).
You need to find where stdc++.h header fi... |
71,402,386 | 71,402,444 | Cannot convert from const_Ty2* to ValueType* | template <typename ValueType> ValueType* RadixTree<ValueType>::search(std::string key) const {
typename std::map<std::string, ValueType>::const_iterator it = radixTree.find(key);
if (it == radixTree.end())
return nullptr;
return &(it->second);
}
Hello! above is my code which is a placeholder for my... | Your function is const and you're correctly using a const_iterator. This means that it->second is also const. When you do &it->second that becomes a const pointer which cannot be implicitly converted to a non-const pointer (such a conversion discards the const qualifier).
It's unclear why you want a non-const pointer... |
71,402,605 | 71,402,636 | Copy Constructor Error With a Template Linked List Class : no matching function for call to 'Node<int>::Node()' | I'm trying to make a copy constructor for a linked list but I'm not sure how to fix this error and I've been looking for hours. The error is:
no matching function for call to 'Node::Node()'
Here is the code:
template <class T>
class Node //node is the name of class, not specific
{
public:
T data; //t dat... | The class Node does not have the default constructor. It has only the following constructor
Node(T Data) //assign data value
{
data = Data; //makes data = NV parameter
next = nullptr; //makes next = to nullptr
}
And in this statement
Node<T>* newCpy = new Node<T>;
there is used the default constructor t... |
71,402,872 | 71,403,055 | Question about operator new overload and exception | Why this code snippet ouputs a lot of "here"?
I think the program should terminate when after throw std::invalid_argument( "fool" ); has been called.
#include <memory>
#include <iostream>
void* operator new(std::size_t size)
{
std::cout << "here" << std::endl;
throw std::invalid_argument( "fool" ); //commit... | The documentation for std::invalid_argument holds the clue:
Because copying std::invalid_argument is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking std::string&&: it would have to copy th... |
71,404,743 | 71,405,801 | C++ getline function missing the first line of txt file | I have written a function to read from .txt file and build a linked list, but the function missed the first line of the file. Anyone have any idea why that happens?
output:
//empty line
gmail
San Francisco
123456
.txt file
person1
gmail
San Francisco
123456
readFile function
void list::readFile(std::string file... | You create a single node so every iteration through the loop you overwrite the previously read values.
In the second iteration of the while loop your first call to getline presumably fails and sets the value of name to an empty string. As the stream is now in a failed state the rest of your reads are ignored and finall... |
71,404,856 | 71,404,857 | How to make proxying const/ref/volatile qualification without duplication in C++? | Say I want to write some "proxy" object for a callable, e.g. to add some feature that happens before the wrapped callable is invoked. Further, say I want to be const-correct, so that the proxy has an accessible non-const operator() only if the wrapped callable does. Then I need to do something like this, defining two v... | The proposed feature I was thinking of was P0847R7 ("Deducing this"), which was accepted for C++23. There are some useful slides here. I don't have a compiler to check this with, but I believe my four operators could be written as one with something like the following:
template <typename F>
struct Proxy {
F wrapped;
... |
71,404,906 | 71,412,204 | In C++ is there a proposed type traits helper for "copying" reference category and cv-qualification? | For the SFINAE in the hypothetical call operator in this answer I need a type trait that "copies" reference category and const/volatile qualifications from one type to another:
template <typename T, typename U>
using copy_category_and_qualifications_t = [...];
copy_category_and_qualifications_t<int, char> ... | P1450 called this copy_cvref and clone_cvref (the former just applies the qualifiers to the 2nd parameter, the latter first removes the qualifiers from the 2nd parameter). The former is useful, I don't think I've ever personally had a need for the latter.
P0847 uses like_t and forward_like in a few contexts, like_t the... |
71,405,497 | 71,405,948 | C++ Vector Operations | Is there any alternative for this? Performing a vector operation in multiples on certain condition?
i want to perform erase vector operation (n-1) times, just deleting only first element in a particular vector on a given if condition.
is it possible to do like this
if ( ret.size() == n ){
(n-1)*order.erase(orde... | order.erase( order.begin(), order.begin() + ( ret.size() - 1 ) );
Needs prior checking of ret.size() vs. order.size() of course, but it seems your code can assert that from context.
That being said, when you are repeatedly erasing from the beginning of your vectors, perhaps your vectors are sorted the wrong way, or yo... |
71,405,806 | 71,453,562 | CMake one build directory for multiple projects with seperate context | I'm trying to build multiple projects within one build directory with the following structure:
|------ CMakeLists.txt (The main Cmake)
|
|------ ProjectAPP
| |----- .c/h files
| |----- sdh_config.h
| |----- CMakeList.txt
|
|------ ProjectDFU
| |----- .c/h files
| ... | Answering my own question, I'm not sure if it'ss the best way to handle this but cmake ExternalProject solved my problem.
|
71,406,224 | 71,412,198 | Running pgc++ programs on Cluster | I tried to run the below OPenACC program on cluster:
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
#pragma acc parallel loop
for (int i=0; i<1000; i++)
{
//cout << i << endl;
printf("%d ", i);
}
return 0;
}
T... |
What could be the reason?
In order to be interoperable with g++, pgc++ (aka nvc++) uses the g++ STL and system header files. Since the location of these headers can vary, on installation a configuration file, "localrc", is created to store these locations.
What could be happening here is that on install, a single sy... |
71,406,688 | 71,406,799 | Can a reference prolong the lifetime of any member data of a class which is returned by a mamber function | class sample
{
std::string mString;
public:
void Set(const std::string &s)
{
mString = s;
}
//std::string Get() const
const std::string& Get() const
{
return mString;
}
};
Let's say I have such a class as above and now I use this class like this:
sample *p = new sample;
p->Set("abcdefg");
con... | No, lifetime extension by reference binding applies only to temporary objects materialized from prvalues.
Objects created with new never have their lifetime extended past delete.
What you are seeing here is just a manifestation of undefined behavior. ref is dangling after delete p; and therefore reading from it in the ... |
71,406,787 | 71,407,138 | Is providing a deleter explicitly required when storing array types inside smart pointers? | According to this paper, one of the common mistakes developers make ( #3 ) is using a smart pointer with array types; Mainly because the operator delete will be called instead of delete[], leaving the program with a memory leak.
Depite that; looking up default deleter in the C++ reference, the following code is there:
... | If I understand correctly, you seem to think that the example 4 contradicts the paper, and the paper recommends using example 2. This is not what the paper is saying.
Example 1 is undefined behavior, as described in the paper: "Using smart pointers, such as auto_ptr, unique_ptr, shared_ptr, with arrays is also incorrec... |
71,406,883 | 71,407,443 | c++: undefined reference to `Json::Value::Value(Json::ValueType)' | I installed jsoncpp on ubuntu with 'sudo apt-get install libjsoncpp-dev' and tried to run a minimalistic test program:
#include <iostream>
#include <fstream>
#include <jsoncpp/json/json.h>
int main()
{
ifstream file("example.json");
Json::Value value;
Json::Reader reader;
reader.parse(file,value);
... | The comment by user17732522 has solved my issue!
The flags are placed incorrectly:
"-ljsoncpp must be placed after the names of the .cpp files or .o files on the compiler invocation" -user17732522
|
71,406,952 | 71,407,500 | Cmake project set LANGUAGES from variable | currently I've got the following project definition :
set(supported_languages "CXX OBJC OBJCXX")
project(
myProj
VERSION ${ver}
LANGUAGES ${supported_languages})
where supported_languages is defined as string of parameters delimited by space
(i.e. CXX OBJC OBJCXX)
However, it fails since cmake expect to get a l... | that error is because (") characterer
lets try this
set(supported_languages CXX OBJC OBJCXX)
project(
myProj
VERSION ${ver}
LANGUAGES ${supported_languages})
|
71,407,174 | 71,408,392 | Testing templated classes with functions defined in CPP file | For a project that I am working on, I need to mock certain classes for testing to test different behaviours of functions. For testing I use gtest. Because I am working on a game, the speed and efficiency of the code is of the essence. Because of this requirement I do not want to mock my classes by using virtual functio... | A variation of solution #1 by renaming the files:
Foo.h
#pragma once // or/and header guards
<template class Bar>
class Foo
{
public:
Bar bar;
bool ExampleFunction();
};
Foo.inl (or other extension .inc, .ixx, ...)
#pragma once // or/and header guards
#include "Foo.h"
template <class Bar>
bool Foo<Bar>::Exam... |
71,407,289 | 71,408,772 | Saxon .NET with C++ CLI | I had an idea to use C++ CLI to interact with the Saxon .NET interface . The problem is that every single example on Saxonica is with C# , and not C++ . can you give me an example that caches an XML file , and using Xslt filepaths to transform it using C++ CLI to use the .NET interface ???
Also pls dont give me workar... | A minimal sample using Saxon .NET HE 10 (tested with 10.6 initially, now updated to 10.7) run on Windows against .NET framework 4.8 is e.g.
#include "pch.h"
using namespace System;
using namespace Saxon::Api;
int main(array<System::String ^> ^args)
{
Processor^ processor = gcnew Processor();
Console::WriteLi... |
71,407,360 | 71,407,536 | how to define functor as third template class of map? | I am trying to define a map::key_comparator type, but I have no idea how to write the class type of functor std::less and std::greater.
// not compilable
using MapTree = std::map<int, string, std::map::key_compare >;
void funct(MapTree& a) {
a.push_back({1, "a"});
a.push_back({3, "d"});
a.push_back({10, "b"});
};
// u... | You need to make it a template; different std::map instantiations are distinct types.
If you want specific key and value types, use a partial specialization.
template<typename Order>
using MapTree = std::map<int, string, Order>;
template<typename Order>
void funct(MapTree<Order>& a) {
// ...
|
71,408,568 | 71,409,362 | ELF symbol name occurs twice (.data.rel.ro and .bss) | in my library (ELF arm64, Android) I see the same mangled symbol name twice (names changed):
>> nm --format sysv libAPP.so.dbg | grep _ZL15s_symbolNameXYs
_ZL15s_symbolNameXYs|0000000003a9c758| d | OBJECT|0000000000000578| |.data.rel.ro
_ZL15s_symbolNameXYs|0000000016604940| b | OBJECT|00000000000005c0| |.bss
I though... | Lower case letters in the symbol type (in your example, d, b, and r) indicate local symbols. These are not subject to linkage and may hence appear multiple times in the same binary. There is nothing wrong with that.
The main source of such symbols are local symbols in object files. The linker just transfers the loca... |
71,408,644 | 71,428,556 | Extend an interface whilst not having to reimplement its functions | I'm struggling with interface inheritance a little. What I'm trying to achieve is that I would like to extend an interface, whilst not having to reimplement all of its functions by reusing the function implementations from an implementation of the parent interface. Is this even possible?
So suppose I have two interface... | Use virtual inheritance to take advantage of function dominance rules.
I'm rusty on how exactly dominance works, but it happens to do the right thing in this case.
#include <iostream>
class IA
{
public:
virtual void funcA() const = 0;
};
class IB : public virtual IA
{
public:
virtual void funcB() const = ... |
71,408,718 | 71,453,554 | Is use in an unused default member initializer still an odr-use? | Is use in a default member initializer still an odr-use, even if the default member initializer is not used by any constructor?
For example, is this program ill-formed because g<A> is odr-used and therefore its definition implicitly instantiated?
template<typename T>
void g() { sizeof(T); }
struct A;
struct B {
B... | As stated in the comments, g<A> is odr-used. However, there is a definition for it available, so there is no non-diagnosable violation here; MSVC is wrong to accept it. (This is true even without the constructor declaration; the implicitly declared B::B() is never defined, but the default member initializer is still ... |
71,408,938 | 71,409,105 | Conditionally defined variable (static if) | In multiple cases I would want to use something like
template<bool condition>
struct S
{
int value;
if constexpr(condition) /*#if condition*/
double my_extra_member_variable;
/*#endif*/
}
or
if constexpr(sizeof...(Ts) != 0)
// define something extra ( a tuple or so )
This is possible with preprocessor fla... | In C++20, the "good enough" solution is with the [[no_unique_address]] attribute
struct empty_t {};
template<bool condition>
struct S {
[[no_unique_address]]] std::conditional_t<condition, double, empty_t> var;
};
It's not perfect because var is always defined, but it will not take any space. Note that if there a... |
71,409,168 | 71,410,855 | How to pass 2d numpy array to C++ pybind11? | In C++ pybind11 wrapper:
.def("calcSomething",
[](py::array_t<double> const & arr1,
py::array_t<double> const & arr2)
{
// do calculation
}
)
In python:
example.calcSomething(
arr1=np.full((10, 2), 20, dtype='float64'),
arr2=np.full((10, 2), 100, dtype='float64')
)
And I got this error message:
ValueError... | In pybind11 array_t is an n-dimensional array, just like a numpy array.
So there are no restrictions on dimensionality.
The error message is probably coming from somewhere else. Not from pybind11.
At least the code you show should not cause this behavior.
|
71,409,301 | 71,409,737 | error: invalid use of member <...> in static member function | I'm encountering this error when I'm trying to use the content of my map 'freq' declared as a class variable, inside my comparator function for sorting the vector(using map to sort the vector elements by frequency). Can anyone highlight where am i going wrong and what should I do?
Here's the code:
class Solution {
... | static functions cannot access member objects. But if you make comp a non-static member function, you can no longer pass it to sort.
A solution is to make comp non-static and wrap it in a lambda in the call to sort, something like:
class Solution {
map<int, int> freq;
public:
bool comp(int a, int b){
if... |
71,409,432 | 71,409,562 | Standard hash with variadic template | I have the following code:
namespace foo {
template<typename ...Types>
class Pi {
};
}
namespace std {
template<> //line offending gcc 8.3.1
template<typename ...Types>
struct hash<foo::Pi<Types...>> {
std::size_t operator()( const foo::Pi<Types...>& s ) const noexcept {
... | The newer GCC version is correct.
template<> is not valid syntax here. It is only used for explicit specialization of a template.
What you are doing here is partial specialization of std::hash, since you are not specializing for just one specific type, but all types that could be instantiated from foo::Pi. Without temp... |
71,409,758 | 71,411,209 | using libfmt to format to a string | using libfmt to print to a file is very convenient:
auto file = fmt::output_file(filename);
file.print(...);
But how can I format to a memory buffer, ultimatiley converting to a string? I would imagine something like
auto buf = some_buffer_object{};
buf.print(...);
std::string s = buf.get_string();
But I can find no ... |
how can I format to a memory buffer, ultimatiley converting to a string?
Use format_to and print to an iterator the appends to a string.
|
71,409,810 | 71,417,692 | Meaning of std::forward<std::decay_t<F>>(f) | I have a question about the code written in https://koturn.hatenablog.com/entry/2018/06/10/060000
When I pass a left value reference, if I do not remove the reference with std::decay_t, I get an error.
Here is the error message
'error: 'operator()' is not a member of 'main()::<lambda(auto:11, int)>&
I don't understand ... | ,The code you have shared is toxic.
template <typename F>
class FixPoint : private F
{
public:
explicit constexpr FixPoint(F&& f)
what this means is that we expect F to be a value type (because inheriting from a reference isn't possible). In addition, we will only accept rvalues -- we will only move from another F.... |
71,410,231 | 71,413,981 | Windows 10 custom credential provider | recently I'm trying to make a custom credential provider for windows 10 and I ended up with a sample code provided by Microsoft for Windows 8.1 (https://learn.microsoft.com/en-us/samples/microsoft/windows-classic-samples/credential-provider/). I've tried to make it work on my computer but I can't! It just compiles and ... | Most likely windows can't find your dll or your credential provider has not been properly registered.
There are two things to understand to know how a credential provider is created.
First, all registered credential providers on a computer can be found in this registry location :
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\W... |
71,410,293 | 71,410,448 | C++ BOOST Unit Tests: Invert BOOST_CHECK_EQUAL for not equal | Is there a way to check for inequality when writing Unit Tests with BOOST?
There is a macro BOOST_CHECK_EQUAL, however there does not appear to be a BOOST_CHECK_NOT_EQUAL macro.
I assume it must be possible to check for inequality in a BOOST Unit Test? I could not find anything from a duckduckgo search however.
| The macro you're looking for is BOOST_CHECK_NE:
BOOST_CHECK_NE(a,b);
BOOST_CHECK_EQUAL(a,b);
|
71,410,527 | 71,410,830 | How to avoid text in C++ to be outputted vertically? | I need this to read a file and copy it into another file while modifying numbers, everything works except it copies and displays everything in vertical line. Is there a way how to avoid this? For loop seems to be a problem, but what should be added/changed without changing everything else?
Output should be:
9as 3
12as3... | Learn to split code to smaller pieces.
Take a look on that:
#include <cctype>
#include <fstream>
#include <iostream>
char increaseDigit(char ch) {
if (std::isdigit(ch)) {
ch = ch == '9' ? '0' : ch + 1;
}
return ch;
}
void increaseDigitsIn(std::string& s)
{
for (auto& ch : s) {
ch = inc... |
71,410,580 | 71,414,140 | ran2() numerical recipe implementation. Passing void pointer as function parameter | I'm trying to implement the ran2() method from Numerical Recipes. I found an implementation [here] 1 that I'm trying to get working.
I'm first trying to use the ran2_get_double(void* vstate) function working but I've never used void pointers as a parameter before and I don't know how it works even if I have experience... | The ran2_get_double() function takes a ran2_state_t in form of a void * as argument but you are passing a pointer to a double. This then causes a buffer overflow that corrupts your memory.
You need to create a ran2_state_t object and initialize it using ran2_set.
The functions should really just take a ran2_state_t * a... |
71,410,801 | 71,410,942 | How can I declare multiple function pointer types in one typedef declaration? | I can do
typedef int a, b;
but I can't do something like
typedef void(*the_name_1, *the_name_2)(...);
Is there a way do to typedef 2 function pointer types at the same time ?
| Multiple declaration in C/C++ is misleading as * is linked to variable and not to the type:
typedef int a, *b, (*c)();
static_assert(std::is_same_v<int, a>);
static_assert(std::is_same_v<int*, b>);
static_assert(std::is_same_v<int (*)(), c>);
So your one-liner would be
typedef void(*the_name_1)(...), (*the_name_2)(..... |
71,410,939 | 71,411,576 | C++ initialize array class with default value | I want to create an open hash table.
And i want to use an array of lists, where the size of the array is a template parameter, but the problem is i don't know how to pass an allocator to all of the list instances, and i cannot use vector, because i will need another allocator for list allocation (alloception), is there... | This uses C++14 for std::make_index_sequence and the std::index_sequence it produces but you can make your own implementation as shown here. Using a delegating constructor you can add another constructor that takes an index_sequence so you can then expand the sequence and get a variadic list of values like
template<ty... |
71,411,741 | 71,412,559 | Reading numbers from a text file with letters and whitespace | I am having trouble with the formatting of my C++ assignment. I am working on a File I/O assignment and I have a text file with letters, numbers and whitespace. I want my program to read the numbers from the text file and display in the same format as the text file. Right now, my code is outputting the numbers but as a... | Assuming that your goal is not to retain the accuracy of the double values in the file, one way to do this is to read the line in as a string, and remove any characters that are not digits, except whitespace and the ..
Once you do that, then it's very simple using std::istringstream to output the values:
#include <iost... |
71,411,946 | 71,412,035 | Would an unordered_set in c++ find the values in this data in constant time? | Suppose I have a list of vertices in a graph. This list corresponds to a path in the graph and before adding another vertex I need to check if it is already present in the path or not.
I was thinking of adding all the vertices in an unordered set and then using the find function. The documentation states that it runs i... | The std::unordered_set type has expected O(1) lookups regardless of what data you store in it, so yes, in this case you should expect to see lookups taking time O(1).
One possible caveat: the O(1) here refers to the number of equality comparisons and hashes computed. If comparing two nodes for equality takes a variable... |
71,412,512 | 71,412,580 | Add element from map to pair only if the value doesn't already exist (C++) | I am trying to add the elements from a map to a pair vector, and then sort the vector according to the value, but i dont want to add elements that have the same value, and i can't figure out how to make such an if statement.
The map contains the amount of times a word was repeated in the input in main() and the word it... | Since you are searching through a vector of pairs, you need to use std::find_if() instead of std::find() to find a vector element that matches a particular field of the pair, eg:
for (auto& it : M) {
if (find_if(A.begin(), A.end(), [&](pair<string, unsigned int>& p){ return p.second == it.second; }) == A.end())
... |
71,412,812 | 71,413,704 | Can we create std::istringstream object from a reversed std::string | I am learning C++ using recommended C++ books. In particular, i read about std::istringstream and saw the following example:
std::string s("some string");
std::istringstream ss(s);
std::string word;
while(ss >> word)
{
std::cout<<word <<" ";
}
Actual Output
some string
Desired Output
string some
My question is t... | You can pass iterators to the istringstream constructor indirectly if you use a temporary string:
#include <sstream>
#include <iostream>
int main()
{
std::string s{"Hello World\n"};
std::istringstream ss({s.rbegin(),s.rend()});
std::string word;
while(ss >> word)
{
std::cout<<word <<" ";
... |
71,413,350 | 71,414,670 | C++ set limit on maximum memory allocation? | I am writing a program in x86 architecture (for technical reasons I cannot use x64). I have designed my program such that it uses under 4GB of RAM memory. However, when I allocate memory for large std::vectors I notice that the constructors allocate more memory than necessary and later trim the memory down to the prope... | Turns out, the standard vector constructor is briefly allocating additional memory to perform a copy operation, as mentioned by Peter Cordes in a comment. That's why doing:
vector<vector<struct>> myVector(M, vector<struct>(N))
may lead to memory allocation problems.
The workarounds that worked for me are:
If required ... |
71,413,742 | 71,413,992 | Getting Releasing unheld lock CriticalSection in Windows C++ code | I'm getting a warning "Releasing unheld lock 'csCriticalSection'" at the 2nd try below.
Here is my code, but without all the ADO code. I don't know why I'm getting this warning, because if the Execute() function fails, the catch will run a LeaveCriticalSection function. If the Execute() function succeeds, I call LeaveC... | You are not initializing csCriticalSection before using it, eg:
...
CRITICAL_SECTION csCriticalSection;
...
int main()
{
InitializeCriticalSection(&csCriticalSection); // <-- ADD THIS
...
DeleteCriticalSection(&csCriticalSection); // <-- ADD THIS
}
But also, you really shouldn't be using bRanLeaveCritical... |
71,414,121 | 71,419,820 | How to write a multi-dimensional array of structs to disk using MPI I/O? | I am trying to write an array of complex numbers to disk using MPI I/O. In particular, I am trying to achieve this using the function MPI_File_set_view so that I can generalise my code for higher dimensions. Please see my attempt below.
struct complex
{
float real=0;
float imag=0;
};
int main(int argc, char* a... | The default behavior is not to abort when a MPI-IO subroutine fails.
So unless you change this default behavior, you should always test the error code returned by MPI-IO subroutines.
In your case, MPI_File_set_view() fails because external is not a valid data representation.
I guess this is a typo and you meant externa... |
71,414,888 | 71,415,981 | C++: How to pass data from parent to child in a lambda inside a recursive function | I want to iterate over a data structure and collect the paths of the elements. I'd like to do it in a way where the iteration over the structure is as generic as possible (see void WithAllMembersRecursively(..)) and the operation on the structure is inserted as an parameter.
The code below will return:
C
C::B
C::B::A
... | You need some way of popping an item from the path when the recursive traversal finishes with an item completely.
The current call to f is essentially a "pre-visit" call, then the visit happens which is the main recursive function iterating over all children and recursively visiting. If you also add a post-visit call y... |
71,415,131 | 71,415,952 | Method already defined when using new version of Visual Studio | The following files are part of my C++ project.
// DpValue.h
class DpValue {
public:
class RElement {
public:
virtual bool operator==(RElement const &Other) const = 0;
};
};
template<class T>
class DpElement : public DpValue::RElement {
public:
virtual bool operator==(DpValue::RElement const &Other)... | I think the only thing you are missing is a declaration of the explicit specialization in the header file. It must appear before any point that would implicitly instantiate the class specialization (since the function is virtual). In the presence of the explicit specialization declaration the implicit instantiation sho... |
71,415,873 | 71,417,374 | How to start Qt Designer "detached" in Visual Studio? | In previous version of Qt Tools for Visual Studio, when opening an .ui file, Visual Designer started normally, in it's own main window. Now it starts as a docked window inside the Visual Studio IDE, and I have to press the "Detach" link every time. Is there any setting to start Qt Designer "detached" by default?
| Just set Run in detached window to True in extension options:
|
71,416,027 | 71,417,042 | Avoiding wasted CPU cycles while waiting for input | My program is waiting for the F4 hotkey to be pressed in order to exit.
I am calling Sleep(1) because without this, I am using 18% of my CPU. Is this the correct way to do this? My gut is telling me there is a better way.
I know that keyboard inputs are interrupt-based, but is there any way to make a thread sleep until... | Look into RegisterHotKey, UnRegisterHotkey, GetMessage, TranslateMessage and DispatchMessage like
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
RegisterHotKey(0, 1, MOD_NOREPEAT, VK_F4);
MSG msg;
while (Get... |
71,416,623 | 71,416,964 | Variadic construction with per-argument type deduction | I have a class Processor that I'd like to be able to, using C++14 or below (C++17, 20, etc ideas very welcome too for information and posterity, but the problem is specifically C++14):
Take a variadic list for construction, each element of which can be:
"values" of basically any type, or
Handlers: some kind of polymo... | In C++11 and C++14 you can use brace-enclosed initializers to expand and handle variadic arguments. So in your case you could do
Processor(Types&&... args) {
int dummy[] = { (m_handlers.push_back(make_handler(args)), 0)... };
}
Since C++17 you can also use a fold expression with the comma operator to ... |
71,416,824 | 71,423,733 | Use the value of strongly typed enum as index in boost::mpl::map | I am using a C++ map structure defined similar to std::map<Foo, std::any> for storing attributes of a compiler symbol table. The Foo is a strongly typed enum, such as enum class Foo {ENUM}. After casting some other types to std::any, I need std::any_cast to cast it back if I access the entry by the Foo::ENUM key. The t... | You need to include #include <boost/mpl/at.hpp>. Also, I wouldn't recommend using boost::mpl - it's really slow to compile. Your "cumbersome" solution is fastest IMHO, and if you don't like it you might like to look towards boost::mp11 or any other "more modern" metaprogramming library.
|
71,417,003 | 71,418,013 | Best way to define number is unsigned char in c++ | I had some code that when simplified is essentially this
unsigned char a=255;
unsigned char b=0;
while (a+1==b) {//do something}
Now since 255+1=0 with unsigned chars I was expecting it to do something but it didn't because it promoted everything to int. I can make it work by replacing a+1 with either (unsigned char)... | According to This cppreference.com page, "arithmetic operators don't accept types smaller than int as arguments." That said, your proposed solution of (unsigned char)(a + 1) is enough to keep this promotion from happening and a will roll over to 0. Using the modulo operator is more explicit but it introduces an additi... |
71,417,403 | 71,417,431 | Why does declaring an instance pointer with new keyword inside a function causes problems and undefined behaviour? | I am learning C++ and came across something interesting while solving challenges on the platform HackerRank. The code is from the Linked List problem. The goal is to display the linked list with the display method in the Solution class. I noticed that I have to use the new keyword while initializing a class instance fo... | While it's true that using new requires explicit deallocation, this also means that if you are not using new, then somehow the lifetime of the object is already managed implicitly.
This is what happens in your second scenario:
Node new_node(data);
head = &new_node;
Here you are actually taking the address of a local v... |
71,417,771 | 71,417,875 | Overwrite read-only contents of uint16_t array with ntohs() | I have a data array which is populated from the network device in big endian format. The processor on the host is an intel processor, therefore by default little endian.
I am trying to overwrite the contents of the data array received from the network device (little endian) to that of the host (big endian), however rec... | DataBE2LE() is marked as const on the end of its declaration, so its this pointer is a pointer to a const FFT_Data object, and thus its data members are implicitly const and can't be modified.
Since DataBE2LE() wants to modify the content of data, simply remove the const qualifier from the end of DataBE2LE().
Also, the... |
71,417,921 | 71,417,961 | would shared_ptr be aware of intermittence reference? | by intermittence reference I mean the following
shared_ptr<int> a = new int(100);
int* i = a;
shared_ptr<int> b = i;
would the reference count of b be two?
also if it is aware, would still be valid in the following code?
//
shared_ptr<int> a = new int(100);
{// workspace
int* i = a;
shared_ptr<int> b = i;
}// end... | The version you wrote in your example will not compile. But to answer the spirit of what I think your question is here is an example
#include <memory>
int main() {
std::shared_ptr<int> a = std::make_shared<int>(100);
int* i = a.get();
std::shared_ptr<int> b(i);
}
This does not have a and b related as far ... |
71,418,053 | 71,418,160 | Using arrays instead of vectors in C | Program should find smallest enclosing circle of two points.
EXAMPLE:
(1,1) (2,2)
The smallest circle for these two points would be the circle with center(1.5, 1,5) and radius 0.71. This is just a representation of that on a graph:
Two points inside a circle
Here's the problem solution:
#include <iostream>
#include <ma... | normal array in c don't have some method like size() , in your code you need to pass size parameter with pointer instead of vector::size() and -> it can work well
int is_valid_circle(const Circle c, const Point* P, size_t size)
{
for(int i = 0; i < size ; i++)
{
if (!is_inside(c, P[i])) return 0;
}... |
71,418,154 | 71,427,303 | CLion can find the MinGW64, but it takes no effect. I still can't run C/C++ programs | After I download the CLion, I configure MinGW-64 also.
I've tried almost everything online, and they're surprisingly consistent, but they still don't solve my problem.
I know it's just a simple configuration issue, but I spent the whole day and still couldn't solve it.
Can someone help me? I'd appreciate it.
| In order to compile the c/c++ file, none of Cygwin and MinGW can be ignore!
Thanks for the brother's (@long.kl) suggest!
just do as follows pictures, your c/c++ compile can work too.
Note that the order
|
71,419,083 | 71,422,041 | Generate random 128 bit in c++ without boost | I have a datatype of size 128 bit, and I like to generate a random value without using boost or any third party headers/libraries.
I wrote the below code snippet and it's working fine, but I want to know if there are any issues/pitfalls with the approach.
#include <stdlib.h>
#include <time.h>
#include <array>
#include ... | One issue with the posted approach is that it will never generate a 0 octet.
std::uniform_int_distribution<std::uint8_t> dis_{1};
// ^ the range will be [1, 255]
You could also use a distribution of uint64_t and spread the bits in the array
std::uniform_int_distribution... |
71,419,220 | 71,419,584 | Question about returning an unique_ptr from a function | As per the document, which says that
We already have implicit moves for local values and function
parameters in a return statement. The following code compiles just
fine:
std::unique_ptr<T> f(std::unique_ptr<T> ptr) {
return ptr;
}
However, the following code does not compile
std::unique_ptr<T> f(std::unique_ptr... |
1.There is no copy ctor for std::unique_ptr<T> indeed, there should not a function could accept a parameter declared as
std::unique_ptr<T>.
In fact, this is ok as long as you move the original std::unique_ptr to this local parameter
FoolFunc(std::move(uniq_ptr)); // ok
FoolFunc(std::unique_ptr<FooImage>{new FooImage}... |
71,419,276 | 71,432,895 | What is a good pattern for array template compatibility? | I would like to create objects having a variable-length array of elements, and have them be compatible in a base/derived-class sense. In C, one could put an indeterminate array at the end of a struct and then just malloc the object to contain the full array:
struct foo {
int n;
double x[];
} ;
struct foo *foo... | As a low-level C++ developer, I understand exactly what you need, and sadly, there is no replacement for flexible array members in standard C++, with or without templates. You have to keep using flexible array members via compiler extensions.
They are not included in the language since in their current form, they are e... |
71,419,557 | 71,419,647 | Control rate of function calls per second | An operation takes 65ms to complete. It needs to be triggered 'numOpr' times at a specific target operations per second.
How do we control the operation to be trigged at a specific rate?
Below is a sample that I tried but it doesn't seem to care about target operations per second. It is always at ~15ops at all valid ta... | Problem #1 is that you didn't initialize timeBetweenOperation, so it will be set to 0 ticks at your 1/N rate. Thus, you are always adding 0. You can fix that by initializing it:
std::chrono::duration<double, std::ratio<1, targetOPS>> timeBetweenOperation(1);
Problem #2 is the way you are doing the sleep_until. ... |
71,420,262 | 71,420,350 | C++ Template specialization with variable template parameter count | I have the problem, that i have a template<typename R, typename... ArgTs> class that should have a function R call(ArgTs... args). The Problem is, that i need a special case, where R is void. I already tried std::is_same<...> with constexpr but this is not possible as i use c++11.
Here i have broken down the problem to... | Function templates can't be partial specified, you can overload them.
template <typename R, typename... ArgTs>
typename std::enable_if<!std::is_same<R, void>::value, R>::type
call(Callable<R, ArgTs...> *_callback, SemaphoreHandle_t _mutex, ArgTs... args) {
...
}
template <typename... ArgTs>
void
call(Callable<voi... |
71,420,403 | 71,420,777 | Why my answer is getting accepted with set but not with vector? | Question is We have to find if there is any sub array whose sum is zero.Return true if possible and false if not.
Time contraint:3 seconds
This is the code using unordered set getting accepted .
bool subArrayExists(int arr[], int n)
{
//Your code here
int sum=0;
unordered_set<int>s;
... | This line
if(sum==0||s.find(sum)!=s.end()){
is very different from this line
if(sum==0||find(v.begin(),v.end(),sum)!=v.end()){
First, a unordered_set does not store the same element twice. In general this would make a difference, though as you stop when you encounter the first duplicate, the number of elements in the... |
71,420,687 | 71,422,030 | How to return class by value with prohibited copying? | I have the following class and I just want to add a few simple function wrappers to return an instance of this class with some arguments/common initialization, just not to do it for each instantiation:
struct myClass
{
myClass(arg1, arg2, arg3, arg4 );
myClass( myClassconst& ) = delete;
myClass& operator=(... | Simply add a move constructor:
myClass( myClass &&) = default;
You probably also want move assignment operator, but adding that one line will make your question code to work.
Depending on what your real class is, you may of course actually have to write some code, instead of just defaulting these. Look up rule of 0/3... |
71,420,900 | 71,440,391 | LNK1104: cannot open file 'libboost_python27-vc142-mt-x64-1_71.lib' while boost_python version is 1.72 | I'm using cmake and Visual Studio 2019 to build my project. My boost version is 1.72 and I generated file libboost_python27-vc142-mt-x64-1_72.lib in directory boost_1_72_0\stage\lib with b2.exe.
I generated .sln file with cmake. Then I build the project in Visual Studio 2019. However,
it ended up with an error LNK1104:... | I know the reason now. There is another boost directory with some header files in my project folder. I wrongly included the boost directory and made a dependency on boost 1.71....
|
71,421,528 | 71,434,960 | How to convert std::vector<std::pair<double, double>> dataVector to Eigen::MatrixXd rtData(dataVector.size(), 2) | Is there a fast way to make conversion below?
use "std::vector<std::pair<double, double>> dataVector" to initialize "Eigen::MatrixXd rtData(dataVector.size(), 2)"
| Assuming sizeof(std::pair<int,int>) == 2*sizeof(int) (i.e., std::pair is not adding any padding) you can use an Eigen::Map of a row-major integer matrix, then cast it to double. Something like this:
typedef Eigen::Matrix<int, Eigen::Dynamic, 2, Eigen::RowMajor> MatrixX2i_r;
Eigen::MatrixXd rtData
= Eigen::Map<Matri... |
71,422,055 | 71,455,461 | Using glslang to extract all uniform delcarations in a glsl file? | I want to do some glsl parsing, in particular I want to find all uniform declarations, that includes SSBOS, samplers and images.
To my understanding glslang provides access to the AST, meaning it can be a a robust time saver to avoid writing a brittle parser yourself.
However I don't see a lot of documentation for the ... | TIntermTraverser is the way to go.
In practice, you will define your custom traverser class by inheriting TIntermTraverser.
For more details, read the doc comments on the top of the definition of TIntermTraverser.
TIntermTraverser is used globally in the glslang project, so examining how it is used in the project will ... |
71,422,259 | 71,422,281 | Creating an array of string_view elements throws error: unable to find string literal operator ‘operator""sv’ with | I have the following (modified) code where I want to create an array of string_view type objects.
I see this error when compiling corresponding to each line
unable to find string literal operator ‘operator""sv’ with ‘const char [8]’, ‘long unsigned int’ arguments
"Sensor2"sv,
The code:
#include <iostream>
#includ... | You need using namespace std::literals;.
See also this question.
|
71,422,608 | 71,423,440 | Transparent passing C++ variadic call parameters to ostream output operator | I have written myself the following function:
template <class Stream>
inline Stream& Print(Stream& in) { return in;}
template <class Stream, class Arg1, class... Args>
inline Stream& Print(Stream& sout, Arg1&& arg1, Args&&... args)
{
sout << arg1;
return Print(sout, args...);
}
It should make it useful to re... | std::endl is a function template.
So it cannot be deduced as for overloaded functions.
static_cast<std::ostream& (*)(std::ostream&)>(&std::endl)
would select correct overload.
using Manipulator = std::ostream& (*)(std::ostream&);
Print(std::cout, "This took ", ns, " seconds with ", np, " packets.", Manipulator(std::e... |
71,422,977 | 71,517,899 | Why tesseract::ResultIterator breaks Chinese word into separate words? | I have such picture:
Chinese characters
I want to find location of "简体中文", but for some reason with ResultIteratorLevel::RIL_WORD the ResultIterator breaks it like this:
word: "简体"
word: "中"
word: "文"
I don't understand why this happens. I've tried a lot of options, different page segmentation modes, but no luck. Howe... | Actually this is a correct behavior, because in Chinese some specific symbols may be as separate words. If you want to recognize such symbols together without spaces then just use the tesseract::RIL_SYMBOL instead of tesseract::RIL_WORD. Thus, you can iterate through each symbol one by one.
|
71,423,128 | 71,423,352 | How can I static assert to disallow "mixed endianness" in a non-templated member function | I am using 2 x std::uint64_t and 1 x std::uint32_t in a high performance implementation of of operator<=> in a struct conataining a std::array<std::byte, 20>.
I am trying to make it cross compiler and architecture compatible.
As part of that I am trying to outright reject any architecture with std::endian::native which... | I suggest asserting that it's either big or little endian:
#include <bit>
#include <compare>
struct pawned_pw {
std::strong_ordering operator<=>(const pawned_pw& rhs) const {
static_assert(std::endian::native == std::endian::big ||
std::endian::native == std::endian::little,
... |
71,423,188 | 71,441,767 | Codeql c c++ ql queries | I want to statically check the vulnerabilities of c c++ code with codeql, such as: double free, array out of bounds, resource Allocates,releases unpaired etc., where can I get a ql scripts to use.
This SDK:https://github.com/github/codeql is too chaos,too many,can I got a comprehensive ql scripts?
if I write the ql que... | It highly depends on the context in which you want to use CodeQL. The license only permits you to use it on open source projects and for academic research (read the complete license for more information). If you want to add CodeQL code scanning to your GitHub repository, you can take a look at About code scanning with ... |
71,423,398 | 71,565,667 | C++ 20 coroutines with PyBind11 | I'm trying to get a simple C++ 20 based generator pattern work with PyBind11. This is the code:
#include <pybind11/pybind11.h>
#include <coroutine>
#include <iostream>
struct Generator2 {
Generator2(){}
struct Promise;
using promise_type=Promise;
std::coroutine_handle<Promise> coro;
Generator2(std:... | Even though PyBind11 does not support coroutines directly, your problem does not mix coroutine and pybind code since you are hiding the coroutine behind Gen anyway.
The problem is that your Generator2 type uses the compiler provided copy and move constructors.
This line:
myCoroutineResult = myCoroutineFunction();
Crea... |
71,423,435 | 71,424,793 | Undefined behaviour accessing const ptr sometimes | I have a header file defined as
#pragma once
#include <iostream>
template<int size>
struct B
{
double arr[size * size];
constexpr B() : arr()
{
arr[0] = 1.;
}
};
template<int size>
struct A
{
const double* arr = B<size>().arr;
void print()
{
// including this statement al... | It seems that it was completely coincidental that smaller allocations were always addressed in a spot that would not get erased by the rep stosd instruction present in printf. Not caused by strange compiler optimisations as I first thought it was.
What does the "rep stos" x86 assembly instruction sequence do?
I also ha... |
71,423,523 | 71,424,292 | variadic template: SFINAE on last argument | I have an array (of any rank), and I would like to have an index operator that:
Allows for missing indices, such that the following is equivalent
a(1, 0, 0, 0);
a(1, my::missing);
This in itself if straightforward (see example implementation below): one just recursively adds arg * strides[dim] until my::missing it hi... | In earlier version of this answer I didn't provided full implementation since something was not adding up for me.
If this index should calculate index for flattened multidimensional array then your example implementation is invalid. Problem is hidden since you are comparing two results for index with all indexes provi... |
71,423,561 | 71,519,289 | Application of Boost Automatic Differentiation fails | I want to use the boost autodiff functionality to calculate the 2nd derivative of a complicated function.
At the boost help I can take a look on the following example:
#include <boost/math/differentiation/autodiff.hpp>
#include <iostream>
template <typename T>
T fourth_power(T const& x) {
T x4 = x * x; // retval ... | Functions of interest are to be converted into templates that may accept either double or boost fvar arguments. Note that boost provides custom implementations of trigonometric functions from standard library (such as sin, cos) suitable for fvar:
#include <boost/math/differentiation/autodiff.hpp>
#include <iostream>
#i... |
71,423,700 | 71,424,305 | C++: Possibility to assign multiple Interfaces | I ran into a strange situation, and I wonder if there is a better way to implement this. I would be very thankful for suggestions.
It comes down to this simple core problem:
//Interface I1 and I2 shall not be combined, since that makes logically no sense
class I1 {
public:
virtual void foo() = 0;
};
class I2 {
pub... | To improve
items.push_back({ a, a });
items.push_back({ b, b });
into
items.push_back({ a });
items.push_back({ b });
You might add constructors to your pair_t
struct pair_t {
pair_t(I1& accessViaI1, I2& accessViaI2) :
accessViaI1(accessViaI1),
accessViaI2(accessViaI2)
{}
template <typename T,
... |
71,423,721 | 71,423,794 | Vector of objects without a default constructor and iterator | I am learning to use C++ vectors, and I can't quite understand the output of the following program:
#include <iostream>
#include <vector>
using namespace std;
class Custom {
public:
int v;
Custom() = delete;
explicit Custom(int v) : v{v} {};
Custom(const Custom &) : v{4} {
}
friend ostrea... | This range based loop is making copies:
for (auto i: c) {
cout << i << endl;
}
And the copy constructor initializes v to 4 (and does not make a copy):
Custom(const Custom &) : v{4} {
}
You can either implement a proper copy constructor or use references in the loop to get the desired output:
for (const auto& i: ... |
71,423,771 | 71,424,311 | How to return the values of the char linked lists and store it as a string? | I created this program that should check the string entered by user in form of characters using doubly linked lists in C++, however I got stuck at the last point in which I should compare the original word with the reversed one to see if the two words are palindrome or not, how to store the content of function display(... | You have some bugs in your code. First of all my tip is that you need to make a class/struct which will hold the head and tail of your list. For example:
class DLList{
public:
NODE *head;
NODE *tail;
};
Also, as you can see you should have a class for your list nodes, and every node should have a pointer to the next... |
71,423,851 | 71,436,494 | How to initialize WinRT AudioGraphSettings using WRL ComPtr? | With C++/WinRT the AudioGraphSettings can be easily initialized with its constructor:
AudioGraphSettings settings(AudioRenderCategory::Media);
I'm having trouble to use it inside my WRL project. Below is my implementation
ComPtr<IAudioGraphSettings> settings;
Windows::Foundation::GetActivationFactory(
HStringRefer... | Type activation at the ABI level is more involved than, for example, instantiating types in C++. The admittedly terse documentation outlines the different mechanisms:
WinRT defines three activation mechanisms: direct activation (with no constructor parameters), factory activation (with one or more constructor paramete... |
71,424,114 | 71,424,454 | Suppress compiler error for a single line MSVC19 C++20 | I want to check if a shared_ptr is uninitialized, i.e. if it is a nullptr or if it has a default value (as would be the case if created by using std::make_shared). For this purpose I wrote a code to check if the shared pointer is having a default constructed value of a class/struct. To achieve this, I also need to know... | Thanks to @molbdnilo for providing the solution. The working function is:
template <typename T>
bool isSharedPtrUninitialized(const std::shared_ptr<T>& shared)
{
if(shared) {
if constexpr (has_equate<T>) {
T tmp;
if(*shared == tmp)
return true;
}
retur... |
71,424,230 | 71,424,521 | The exe package CLion created cannot be ran | When I try to run the exe package that CLion created, I got an error: libgcc_s_dw2-1.dll not found.
Does anyone know how to fix this?
| If you are using MingW to compile C++ code on Windows, you may like to add the option -static-libstdc++ to link the C++ standard libraries statically. What exactly I mean is following:
For instance adding set(CMAKE_EXE_LINKER_FLAGS "-static") to your cmake file may fix it.
Additionally please also make sure you have ... |
71,424,471 | 71,428,075 | How can the symbols be bigger than each other? Or do I not understand something? Could you explain what this code does? | Is it ok to compare symbols with each other?
#include <iostream>
using namespace std;// For Example, Why if "k = 4" it outputs "r o" ? //
int main() {
char word[] = "programming";
int k;
cin >> k;
for (int i = 0; i < k; i++)
if (word[i] > word[i + 1]) {
cout << word[i] << endl;
... | The char data type is an integral type, meaning the underlying value is stored as an integer. Moreover, the integer stored by a char variable is intepreted as an ASCII character.
ASCII specifies a way to map english characters(and some other few symbols) to numbers between 0 and 127. That is, each english character(and... |
71,424,837 | 71,425,104 | Can the names of parameters in function definition be same as the name of arguments passed to it in the function call in C++? | Suppose we have a function as given below:
int add(int num1, int num2) {
num1 += num2;
return num1;
}
Now, I call the above function by passing the arguments having the same name as the parameters in the add function.
int num1 = 10;
int num2 = 10;
int result = add(num1, num2)
Is it correct to do so? The co... | Yes, the names of the variables you pass in a function call can be the same as the names of the parameters in the function definition. The scope of the function parameters begins and ends in the function block, so the compiler can keep the two (or more) variables defined at different scopes separate, even when they hav... |
71,424,982 | 71,764,145 | Landscape Creation C++ UE4.27 | I would like to create a landscape from scratch in unreal engine 4.27 using C++ only. I have only a simple notion of the process, which revolves around GetWorld()->SpawnActor<ALandscape>, ALandscapeProxy::Import(...) and importing a height/weight map.
I used the LandscapeEditorDetailCustomization_NewLandscape::OnCreat... | This is the solution I came up with, with many thanks to ChenHP (or chpsemail) who gave me a solution to this. Firstly, declare the following variables. A better understanding can be found here.
FQuat InRotation
FVector InTranslation
FVector InScale
FTransform LandscapeTransform{InRotation, InTranslation, InScale}
int3... |
71,425,715 | 71,428,216 | Iterating QList<double> changes list values | I'm trying to convert a double with 4 decimals in a quint32, but when I iterate the list, the values are different.
I added a breakpoint at the first cycle and these are the variables, how can I make "i" to be 112778?
EDIT:
This is the code:
QList<double> list;
list << 11.2778;
list << 11.3467;
list << 11.3926... | This is just a question of floating point precision in C++, and there are a lot of existing SO questions on the topic. The problem I think arises from the fact that: 11.2778 * 10000 might not get calculated to be exactly 112778. It might think it is 112777.999999999, or whatever. Converting to an int doesn't round to t... |
71,426,048 | 71,426,263 | C++ Linked List Reverse Function Triggers Infinite Loop | I've created a linked list from an array. It works fine. But when I try to reverse the list using the reverseList() function, it starts an infinite loop. When I try to display the list, it displays the last two members repeatedly.
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct nod... | Within the function reverseList
node *reverseList(node *h)
{
node *p, *q, *r;
p = h->next;
q = h;
r = NULL;
while (p)
{
r = q;
q = p;
p = p->next;
q->next = r;
}
h = q;
return h;
}
initially q->next for the first node pointed to by the pointer h is no... |
71,426,427 | 71,426,987 | How to set build type to 32 bit in Github actions for CMake C++ project | I need to have automated testing on github for a CMake C++ project. For this I want to use a 32 bit Windows machine (some of our packages are only in 32 bit), but I couldn't find an easy method to do this. I have tried to set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER in the environment to the x86 compiler, but that did n... | As stated in the comments from vre the cmake -A Win32 tag works on github! If you also want the host to be x86 run the following command: cmake -S SOURCEFOLDER -B BUILDFOLDER -T host=x86 -A Win32
|
71,427,285 | 71,462,327 | How to extend dims of blob in openvino | Hello from a beginner of OpenVINO. In the official tutorial, the optimal way of taking input for a cascade of networks is
auto output = infer_request1.GetBlob(output_name);
infer_request2.SetBlob(input_name, output);
However, in my case, the output's layout is CHW but the next network's input has an NCHW layout. So ho... | Use InferenceEngine::CNNNetwork::reshape to set new input shapes for your first model that does not have batch dimension.
|
71,427,427 | 71,431,896 | Is there a way to get a "total sum" which in my program would be the total amount of calories | This is my code and I am wondering how I can get the sum of the calories of the meals the user inputted and output it to the user at the end.
Below you can see that where I commented in all caps for calCount. That doesn't work for my program and I believe I am wrong and that won't output the sum.
Should I do the sum of... | First, you're asking us to read your code and figure out what you're doing wrong. It would really be nice if you took at least half as much time making your question readable. Please take the time to ensure your code is formatted properly so it is easier for us to read.
Next, your main() is crazy.
int main() {
strin... |
71,427,622 | 71,428,254 | Binding a non-const lvalue reference to a deduced non-type template parameter | Consider a function template f that binds a non-const lvalue reference to a deduced non-type template parameter
template <auto N>
void f()
{
auto & n = N;
}
This works when f is instantiated over class types
struct S {};
f<S{}>(); // ok
But doesn't work when instantiated over non class types (as I expected)
f... | The reason for the distinction is because class non-type template parameters weren't always there. Originally, value template parameters could only be pointers, integers, or a few other things. Such parameters were simple and the value was just a single number known at compile-time. As such, making them rvalues (rememb... |
71,428,013 | 71,429,200 | C++ Iterator ( Next ) | I have this code that i am using to get an idea of how C++ Next iterator work on key value map that has a struct. I can not think of how:
iter->val happens to be 1 when struct value is 0 for key "test"
next->val happens to be 0
Can someone help me understand this please.
#include <iostream>
#include <vector>
#... | You first create a struct test with val=0 and st={"test"}. That gets inserted into the list tst, so that has one entry now. The return value is an iterator pointing at the new element and is put into m["test"]. So your unordered map has one entry "test" that is an iterator of tst. And now the fun begins...
auto iter... |
71,428,645 | 71,428,819 | Spaceship (<=>) operator with iterator implementation results in error: '+' cannot add two pointers | This is all I have, and of course, the rest of the typical class with constructor, destructor, etc. However, the C++ compiler in Visual Studio 2022 gives me this error:
CS2110 '+' cannot add two pointers.
This makes sense, given my private declaration within this class. However, I am not sure, how this can be resolve... |
CS2110 '+' cannot add two pointers.
T* m_ptr;
size_t* m_counter;
iterator end() noexcept { return (m_ptr + m_counter); }
// ^
const_iterator end() const noexcept { return const_iterator(m_ptr + m_counter); }
// ^
... |
71,428,682 | 71,428,856 | Cuda float precision | Will the float loses its precision when a number is small enough (GPU Kernel, RTX 2060)?
Say,
#include <stdio.h>
__global__ void calc()
{
float m1 = 0.1490116119;
float m2 = -0.000000007450580;
float res = m1 + m2;
printf("M1: %.15f M2: %.15f Res: %.15f\n", m1, m2, res);
}
int main()
{
calc<<<1... | Your observations are correct and they don't have anything to do with CUDA:
$ cat t1981.cu
#include <stdio.h>
#ifndef DONT_USE_CUDA
__global__ void calc()
#else
int main()
#endif
{
float m1 = 0.1490116119;
float m2 = -0.000000007450580;
float res = m1 + m2;
printf("M1: %.15f M2: %.15f Res: %.15f\n", m... |
71,429,411 | 71,430,261 | Check if matrix is Lower or Upper Triangular Matrix | Is there an API in Eigen library to check if a matrix is a lower or upper triangular matrix?. Obviously, we can write a function to check this. But I would like to know if Eigen has a way of checking this. When I looked in the documentation, I read about triangular views, but no calls to check if it is lower or upper.
| According to documentation: https://eigen.tuxfamily.org/dox/classEigen_1_1MatrixBase.html#title51
matrix.isUpperTriangular();
matrix.isLowerTriangular();
|
71,429,502 | 71,429,648 | Parallel OpenMP loop with continue as a break alternative | I'm referring to this question: Parallel OpenMP loop with break statement
The code suggested here:
volatile bool flag=false;
#pragma omp parallel for shared(flag)
for(int i=0; i<=100000; ++i)
{
if(flag) continue;
if(element[i] ...)
{
...
flag=true;
}
}
What are the advantages o... | After compilation, they are identical at least for the trivial case.
Without continue
With Continue
If you compare the resulting assembly there is no difference between the two. I have taken the liberty of adding a junk condition of halting before 2000.
|
71,429,627 | 71,430,285 | Trying to change a value in a vector bool | I'm reading Stroustrup PPP and while doing an exercise, I found this error.
Why I can't change the value of a vector bool?
#include "std_lib_facilities.h"
int main()
{
vector<bool> vecc(2, true);
vecc[1] = true; // I can't do this, returns error.
return 0;
}
The error:
error: cannot bind non-const lvalue refe... | std_lib_facilities.h defines the following helper template to add a bit of error checking helpful to folks beginning their programming careers:
// trivially range-checked vector (no iterator checking):
template< class T> struct Vector : public std::vector<T> {
using size_type = typename std::vector<T>::size_type;
... |
71,429,692 | 71,430,060 | Reading values of static const data members without definitions: what governs these rules? | Consider the following program:
struct Empty { };
struct NonEmpty { int x{}; };
struct S {
static const Empty e; // declaration
static const NonEmpty n; // declaration
static const int a; // declaration
static const int b{}; // declaration and initializer
};
Empty ... | [basic.def.odr]/4 governs when a variable is odr-used (requiring a definition).
S::e and S::n are not eligible for exception (4.1) because they have non-reference type. They are not eligible for exception (4.2) because they are not usable in constant expressions because they fail to be potentially-constant, and they do... |
71,430,480 | 71,430,925 | How does std::map know when two keys are equal when using a custom comparator? | struct StrCmp {
bool operator()(char const *a, char const *b) const
{
return std::strcmp(a, b) < 0;
}
};
// StrCmp specified in map declaration
map<const char *, int, StrCmp> strMap;
char p[] = "Test";
strMap[p] = 5;
cout << strMap["Test"];
In the code above the output is 5... How does the map know... | Per the std::map documentation on cppreference.com:
std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees... |
71,430,924 | 71,431,048 | Is it well defined to access a variable from an outer scope before it is redefined? | This code compiles with no warnings in gcc-11:
int i{ 2 };
{
std::cout << i; //prints 2
int i{ 3 };
std::cout << i; //prints 3
}
Is this well defined or it just happened to work?
|
Is this well defined or it just happened to work?
It is well-defined. The scope of a variable declared inside a {...} block starts at the point of declaration and ends at the closing brace. From this C++17 Draft Standard:
6.3.3 Block scope [basic.scope.block]
1 A name declared in a block (9.3) is local to t... |
71,432,070 | 71,432,091 | In c++ can you separate the function called based on the template? | I have a function in C++ that works, in theory. What I mean by this, is if the function was converted to a language like Python, it would work just fine because it is not pre-compiled. However, in a language like C++, it throws errors.
This is the function:
template <typename T>
T JSONValue::get(){
if(detect_numbe... | In C++17 and later, you can use if constexpr, eg:
if constexpr (detect_number::detect<T>){
// T is a numeric type, do numerical things here...
}
else if constexpr (detect_string::detect<T>){
// T is a string type, do stringy things here...
}
...
if statements are evaluated at runtime, so the entire function ha... |
71,432,188 | 71,432,463 | How to incrementially concatenate ranges? | Background
What I am trying to do is to implement some classes that represents geometry. Any instance of a geometry class has a method called vertices() that returns a non-owning view of vertices. A geometry class can be expressed in terms of multiple other geometry classes, so the geometry class' vertices()-method wou... | You can do this using Eric Niebler's Range-v3 library.
Just concat the different range views with ranges::views::concat. E.g., for GeometryC:
return ranges::views::concat(a.vertices(), b.vertices(), v);
[Demo]
Much of the Range-v3's stuff is being gradually adopted by the standard Ranges library, although it seems thi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.