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
70,037,656
70,037,937
Expecting function body despite it being provided
I have a base class called Node which defines two functions: indent and toString. The former will be used by all derived classes without overriding, however the latter will be overridden in the derived classes. Node.hpp #ifndef NODE_H #define NODE_H #include <string> #include <vector> #include <memory> class Node { ...
To override a function in a child class, you need to write the declaration in the class definition. The override specifier will only appear in the header file. Header File class FunctionNode : public DeclarationNode { FunctionNode(...) { ... } std::string toString(int level) const override; }; Source File #includ...
70,037,732
70,037,887
String is out of range
The task is interchange two parts of a word, which contains the dash (i.e we have 1237-456 but should transform it into 456-1237). Here`s my code, it runs but doesnt shows results as a string is out of range and i dk why. It happens in the 1st for, the second iteration ends in the error+ it happens when strlen is 5 and...
first and second will not have memory allocated to them. They are initialized as strings of size 0. And for this case I would just use iterators instead of indices (though they could work too, but then you need more manual work to allocate enough room for the target strings and all). All in all I think your code is mix...
70,037,992
70,038,169
Friend class in C++ not allowing access to private member attributes
I recently started C++ and to be completely honest my lecturer isn't much help, I am trying to give a linked list friend access to a node class. From what I can see I have declared everything I need, but I still cant access the Node private members , if somebody could see something im missing that would be great! My no...
NodeofBook declaring that ListofBooks is a friend class just means that the implementation of ListofBooks can access NodeofBook's private members, but there still needs to be an instance of NodeofBook to access. Its members are not static; non-static member variables are part of some object. That is, just because the L...
70,038,105
70,038,163
"AddressSanitizer: stack-use-after-scope" when trying to access element of vector of pointers
Why the following code #include <iostream> #include <vector> typedef struct Number { int number = 15; } Number; int main() { std::vector<Number*> nums(5); for (size_t i = 0; i < nums.size(); ++i) { Number num; nums[i] = &num; } std::cout << nums[1]->number << "\n"; return 0; ...
The issue is that you are storing a pointer to a value on the stack that goes out of scope and gets destroyed, leaving a dangling pointer. std::vector<Number*> nums(5); for (size_t i = 0; i < nums.size(); ++i) { Number num; nums[i] = &num; // num goes out of scope here and num[i] has a dangling pointer ...
70,038,139
70,038,468
Append multiple chars to string in C++
Using + is a valid way to append a char to a string in C++ like so: string s = ""; s += 'a'; However, string s = ""; s += 'a' + 'b'; gives a warning: implicit conversion from 'int' to 'char' changes value and does not append a and b characters. Why does the first example append the char and the second does not?
This has to do with operator precedence. Let's take for example the expression: string s = ""; s += '0' + '1';//here + has higher precedence than += Here + has higher precedence than += so the characters '0' and '1' are group together as ('0' + '1'). So the above is equivalent to writing: s+=('0' + '1'); Next, there ...
70,038,541
70,039,208
Customising destruction procedure in std::vector::erase()
When I call the erase function on a vector of type 'T', then the destructor of the elements following the range on which I've called the erase() is called. Is there a way to customise this behaviour? How can I ensure that the destructors of those elements which are being erased are called? Sample Program #include<bits/...
You can't do this with vector. Erase will get rid of the items you want from the vector, but it may not destroy those specific objects. If it is absolutely necessary to call the destructors of the first two elements, consider using a deque if you are going to only insert and erase at the back and the front or a std::fo...
70,038,663
70,041,211
Overloading operator<< twice in same class for different member variables
Sorry if this question has been asked before, but I'm struggling with overloading the << operator to stream different data into multiple files. I have a Player class, which has the following attributes: char* name; char* password; int hScore; int totalGames; int totalScore; int avgScore; I want to overload the << oper...
Rather than defining an operator<< for Player itself, create a couple of utility types that refer to the Player and have their own operator<<s, let them decide which portions of the Player to stream, eg: class Player { private: std::string name; std::string password; int hScore; int totalGames; int ...
70,039,010
70,042,467
Getting a ROS distribution value through c++ code
Is there a way to get the ROS_DISTRO in c++, cz I want to run specific C++ code when ros_distro is melodic, and else if noetic then this code. Ubuntu: 20.04 Thank You.
In C++ you can simply use getenv() to grab environmental variables. import <iostream> int main(){ std::string distro = getenv("ROS_DISTRO"); std::cout << "Got distro: " << distro << std::endl; }
70,039,103
70,039,332
how to check if unique_ptr points to the same object as iterator
Let's consider such method: void World::remove_organism(organism_iterator organism_to_delete) { remove_if(begin(organisms_vector), end(organisms_vector), [](const unique_ptr<Organism>& potential_organism_to_del) { }); } what I'm trying to achieve is to delete organism that iterator points to from ...
You don't have to search through the vector to find an iterator; you just have to erase it: void World::remove_organism(organism_iterator organism_to_delete) { organism_vector.erase(organism_to_delete); } Or if you want to delete only the element that the unique_ptr points to: void World::remove_organism(organism_...
70,039,132
70,160,714
How to set the required version of C++ redistributables
I created a dll based off a sample project that is several years old. I am building the dll and can register this dll successfully on my computer which has both 2010 and 2015-2019 C++ redistributables installed. When I try to install this same dll on a computer with only 2015-2019 c++ redistributables installed, regist...
This ended up being related to the fact that I'm using JNI and was dependent on jvm.dll. I was using the jvm.dll from Java 8u202. This version of the dll is dependent on the 2010 C++ Redistributables. Starting with Java 8u261 jvm.dll is dependent on the 2017 Redistributables (source). Dependency Walker is outdated, ...
70,039,144
70,039,278
Longest common subsequence of more than 1 Letter in a string
I'm trying to find the LCS of more than one letter in two strings using a k value. For example, if k = 3 s1 = "AAABBBCCCDDDEEE" s2 = "AAACCCBBBDDDEEE" then the LCS would be 4: "AAABBBDDDEEE" or "AAACCCDDDEEE", another example is if k = 2 s1 = "EEDDFFAABBCC" s2 = "AACCDDEEBBFF" then the LCS would be 2: "EEBB"...
Use std::is_permutation to find if two strings contain the same characters. To store more than one character in each "cell of the table" use std::string. For any questions on c++, go here. EDIT: Here is a demo of substr's usage: std::string s{"AAABBBCCCDDD"}; std::cout << s.substr(3, 3) << std::endl; // BBB std::vecto...
70,039,351
70,039,712
Is a named rvalue reference "ref" a xvalue?
If an xvalue is a value that is at the end of its lifetime, what is a named rvalue reference if not an lvalue or xvalue (because it is not expiring and is movable)?
Read this part carefully: In C++11, expressions that: have identity and cannot be moved from are called lvalue expressions; have identity and can be moved from are called xvalue expressions; do not have identity and can be moved from are called prvalue ("pure rvalue") expressions; do not have identity and cannot be...
70,039,836
70,040,374
What is the correct way to use fmt::sprintf?
I'm trying to optimize my software and to do that I need to change the way I store and draw things. Many people say that fmt is way faster than iostream at doing those things, yet I'm sitting here and trying to understand what I did wrong. The old code is working: auto type = actor->GetName(); char name[0x64]; if (type...
As @NathanPierson mentioned in comments, fmt::sprintf() return a std::string, which you are ignoring. fmt::sprintf() does not fill a char[] buffer (not that you are passing one in to it anyway, like you were with ::sprintf()). Change this: char name[0x64]; fmt::sprintf("AI [%dm]", dist); To this: std::string name = fm...
70,040,154
70,040,203
C++ vector prints out weird elements
I'm currently in the process of learning C++ and for that I'm reading the book "C++ Primer". The book is pretty good so far and I have learned a lot however I experienced weird behaviour using a vector and I'm unsure if this is right or if it's a problem from my side. The task is: Read a sequence of words from cin and...
You need to realize there's two steps. First step: read all the words and convert each to uppercase Second steps: print all the words Second step needs to be done after first step is done. However, you have a single while loop. Didn't run it, but simplest change that looks likely to work is: string input; vector<strin...
70,040,267
70,048,689
C++ Include Problem in Event Listener Pattern
I am trying to use EventListener Pattern (instead of Observer) in my project. Basically: Entitys can register themselves as listeners for certain types of Events Entitys can report an Event to EventListener. When an Event is being reported, EventListener will notify Entity instances that are registered to receive thi...
The solution is way easier than I thought. You can directly #include the header files with each other. Just remember to add the header guards (#ifndef ENTITY_HPP #define ENTITY_HPP #endif).
70,040,627
70,040,671
syntax variants for function pointer as non type template arg
I want to use a function pointer as non type template parameter. I can do it with a predefined alias to the function pointer type with typedef or using. Is there any syntax for the template definition without a predefined type alias? bool func(int a, int b) { return a==b; } //using FUNC_PTR_T = bool(*)(int,int); // OK...
You are going to declare a non-type template parameter. You can write template < bool( *ptr )( int, int ) > void Check() { ptr( 1, 1 ); }
70,040,667
70,041,507
Having a hard time figuring out logic behind array manipulation
I am given a filled array of size WxH and need to create a new array by scaling both the width and the height by a power of 2. For example, 2x3 becomes 8x12 when scaled by 4, 2^2. My goal is to make sure all the old values in the array are placed in the new array such that 1 value in the old array fills up multiple new...
It's actually very simple. I use a vector of vectors for simplicity noting that 2D matrixes are not efficient. However, any 2D matrix class using [] indexing syntax can, and should be for efficiency, substituted. #include <vector> using std::vector; int main() { vector<vector<int>> vin{ {1,2},{3,4},{5,6} }; si...
70,041,880
70,041,926
faster search protocol with large list (c++)
faster search protocol with large list? hello and thanks for reading my post. I'm making some simple autocomplete software that compares the word being entered to every word that matches that word's sequence of letters in the English dictionary. The dictionary contains 400,000 elements so as you could expect it makes f...
Sort your dictionary. Then you can binary search for the word, since you're matching prefixes only (i.e. you aren't trying to find "hello" by typing "ell"). Also this is very inefficient: input[input.size() - 1] == list[j].substr(0, input[input.size() - 1].length()) That innocent-looking std::string::substr() allocat...
70,042,092
70,069,628
How to convert a gray8_view_t to a rgb8_view_t by using boost::gil and create a rgb8_image_t object from it?
Since boost::gil does not support gray8_view_t writing for the BMP format, I want to convert gray8_view_t to rgb8_view_t. Here is what I've tried so far. auto rgb_view = boost::gil::planar_rgb_view(width, height, pixels, pixels, pixels, width); pixels contains the raw pixels from the gray8_view_t object, so I let r=g=b...
Okay the remaining problem was merely a misspecified template argument, color_converted_view expects a destination pixel type: #include <boost/gil.hpp> #include <boost/gil/extension/io/bmp.hpp> #include <boost/gil/extension/io/jpeg.hpp> #include <boost/gil/extension/io/png.hpp> #include <fstream> namespace gil = boost:...
70,042,094
70,042,169
Nested Structures and using constructor for default value but conversion error
For some reason when I set some default values for the nested structure with a constructor, I get the following error. But it seems the code should work. Can someone tell me where am I going wrong? #include <stdio.h> #include <string.h> #include <iostream> using namespace std; struct smallDude { int int1; int...
smallDude has a user-declared default constructor, so it is not an aggregate type, and thus cannot be initialized from a <brace-init-list> like you are attempting to do. There are two way you can fix that: change the smallDude constructor to accept int inputs, like @rturrado's answer shows: struct smallDude { int...
70,042,157
70,042,264
Creating ArrayBuilders in a Loop
Is there any way to create a dynamic container of arrow::ArrayBuilder objects? Here is an example int main(int argc, char** argv) { std::size_t rowCount = 5; arrow::MemoryPool* pool = arrow::default_memory_pool(); std::vector<arrow::Int64Builder> builders; for (std::size_t i = 0; i < 2; i++) { arrow::Int6...
What do your includes look like? That error message seems to suggest you are not including the right files. The full definition for arrow:Int64Builder is in arrow/array/builder_primitive.h but you can usually just include arrow/api.h to get everything. The following compiles for me: #include <iostream> #include <arr...
70,042,380
70,044,729
Linker error when using cmake and doctest.h (it's working without cmake)
I have 3 files in my directory "project": doctest.h - the testing library, doctest_main.cpp - a file needed for the library, and tests.cpp - the file with tests. project/doctest_main.cpp: #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" project/tests.cpp: #include "doctest.h" TEST_CASE("Some test_case"...
You've created an executable with the target name doctest_main.cpp and only a single source file. The add_executable should be changed to the following to create a target with the name a which by default results in the executable built being named a (or a.exe on windows): # extra whitespaces/newlines not needed below, ...
70,042,457
70,042,569
Should std::async respect thrown errors?
I'm trying to understand how exceptions are handled asynchronously -- I have a webserver that contains a lambda handler for processing requests (uWebsockets) and it keeps crashing. To simulate the scenario I used std::async void call(function<void()> fn) { std::async([&fn]{ fn(); }); } int main() { try { ...
Let's take this step by step. Let's start with the very definition of what std::async does. It: runs the function f asynchronously (potentially in a separate thread The word "potentially" is a distraction here, but the point is that a different execution thread is going to be involved here. For all practical reasons,...
70,042,606
70,042,844
How to access the Optimization Solution formulated using Drake Toolbox
A c++ novice here! The verbose in the terminal output says the problem is solved successfully, but I am not able to access the solution. What is the problem with the last line? drake::solvers::MathematicalProgram prog; auto x = prog.NewContinuousVariables(n_x); // Cost and Constraints drake::solvers::MathematicalProg...
You will need to change the line osqp_solver.Solve(prog, {}, options); to result = osqp_solver.Solve(prog, {}, options); currently result is unset. Another question is that what if I don't wanna choose OSQP and let Drake decide which solver to use for the QP, how can I do this? You can do const drake::solvers::Math...
70,042,711
70,042,765
Is it possible to implement command substitution via pipeline?
For example, we have $(ls): int pfd[2]; pipe(pfd); switch (fork()) { case 0: close(pfd[0]); dup2(pfd[1], 1 /*stdout*/); exec('ls', 'ls'); case -1; // Report the error... break; default; break; } wait(nullptr); // Wait until the process is done (it is better to use the waitpid() versi...
wait(nullptr); This will halt the parent process until the child process terminates. The child process is set up with its standard output hooked up to the write end of a pipe whose read end is opened in the parent process. Pipes' internal buffer size is limited. If the child process generates enough output it will bl...
70,042,745
70,042,857
How to correct this arithmetic operation without the need to use fmod?
In c++ this code below shows an error: expression must have integral or unscoped enum type illegal left operand has type 'double' is it possible to correct it without the need to use fmod? # include <iostream> using namespace std; int main() { int x = 5, y = 6, z = 4; float w = 3.5, c; c = (y + w - 0....
You can use type casting to fix it : c = ((int) (y + w - 0.5)) % x * y; To clarify your response in the comments, changing c to type int still don't work as the part (y + w - 0.5) is not evaluated as int but as double. And modulus operation doesn't take that type as an argument. Full modified code : #include <iostream...
70,042,913
70,042,919
How to print out actual object value instead of memory address in gdb?
(gdb) print inputInfo $8 = (SObjectRecInput *) 0x7fffffffced0 For example, when I want to check the value of inputInfo, it prints out: 0x7fffffffced0 And its type is 'SObjectRecInput'. How to actually print out its value?
inputInfo appears to have a pointer type, so dereference it: (gdb) print *inputInfo
70,043,418
70,043,745
Most frequent Alphabet Substring
My Logic is working for smaller input How can I make it better to accepts for larger inputs. Q) The program must accept a string S containing only lower case alphabets and Q queries as the input. Each query contains two integers representing the starting and the ending indices of a substring in S. For each query, the p...
Following code has a lot of memory waste, but each query is looked up in O(1): int main() { std::string s; int q = 0, start = 0, end = 0; std::cin >> s; std::cin >> q; auto mem = std::make_unique<int[]>(26 * s.length()); for (int i = 0; i < s.length(); i++) { mem[i * 26 + s[i] - 'a']++;...
70,043,553
70,044,582
what is the difference between stl priority_queue and heap-related method?
I used heap-related operations to maintain a heap structure. For example: std::vector<int> a = {1,2,56, 2}; std::make_heap(a.begin(), a.end()); // add a.push_back(3); std::push_heap(a.begin(), a.end()); // erase std::pop_heap(a.begin(), a.end()); int v = a.back(); a.pop_back(); Recently, I find there is a structure na...
See cppreference.com: Working with a priority_queue is similar to managing a heap in some random access container, with the benefit of not being able to accidentally invalidate the heap. And in case it isn't clear: your code manages a heap in a random access container.
70,043,576
70,043,608
Is this a function or variable definition in c++ code?
I am reading a piece of c++ code in which ids, curi and len are integer, content are string. I don't understand what's match_word() part. Is it a function or variable? I can't find its definition in all header files. if(-1!=ids) { len = ids - curi; string match_word(content, curi, l...
From std::string documentation string match_word(content, curi, len); This is/uses a substring constructor which Copies the portion of content that begins at the character position curi and spans len characters (or until the end of content, if either content is too short or if len is string::npos). So for example st...
70,043,855
70,056,475
Are arguments of unary and binary operation arguments guaranteed to be same as original data if passed by reference?
As you know, we can provide UnaryOperation and BinaryOperation for a lot of stl functions. Arguments of these methods can be defined by value, but in a lot of cases, we pass them by reference as follows: Ret fun(const Type &a); // UnaryOperation Ret fun(const Type1 &a, const Type2 &b); // B...
The example as written exhibits undefined behavior. Parallel algorithms are given a dispensation to make arbitrary copies of elements of the sequence, under certain circumstances. [algorithms.parallel.user]/1 Unless otherwise specified, function objects passed into parallel algorithms ... shall not ... rely on the ide...
70,043,928
70,044,174
How to use pointer to string in cpp?
I am studying pointers in C++. I have studied call by value and call by reference concept. I am trying to create a function to reverse a string which accepts a pointer to string and the size of string. The code is as follow void reverse(string* str, int size) { int start = 0; int end = size - 1; while(sta...
Just need a little bit of change in your code Change this *str[start++] to (*str).at(start++) void reverse(string* str, int size) { int start = 0; int end = size - 1; while(start < end) { swap((*str).at(start++),(*str).at(end--)); } } ...
70,043,938
70,044,509
move ctor of std::string does not work properly?
Why the msg is not being modified after the call to std::move(msg)? int main() { std::string msg( "Error!" ); std::cout << "before try-catch: " << msg << '\n'; try { throw std::invalid_argument( std::move( msg ) ); } catch ( const std::invalid_argument& ia ) { std::cerr << ...
Here, the only relevant constructor of std::invalid_argument is: invalid_argument(const std::string& what_arg); Const-ref parameter can bind to anything, including an xvalue, which std::move(msg) is. std::move() itself is just a cast, the real work of moving data out of a string could have been made inside a construct...
70,044,161
70,044,193
C++ declaring a const function in header and implementing it in .cpp
I have the following header: #include <string> using namespace std; enum COLOR {Green, Blue, White, Black, Brown}; class Animal{ private: string _name; COLOR _color; public: Animal(); ~Animal(); void speak() const; void move() const; } ; And the following .cpp implementation: #incl...
You forget to put const in the implementation. Change your code to: void Animal::speak() const { cout << "Animal speaks" << endl; } void Animal::move() const {};
70,044,479
70,078,050
How to configure pcapplusplus so it doesn't ignore packets which are greater than MTU size on PcapLiveDevice?
I am using pcapplusplus library for tcp packet processing in c++. When i am receiving packets greater than MTU size, which is 1500 bytes, my program stops further processing as TcpReassembly is not processing that packet. Due to this onMessageReadyCallback is not calling for that packet. And more serious, as that packe...
Basically the problem was with tcpreplay and not the pcpp::TcpReassembly. Tcpreplay can’t send packets which are larger than the MTU of the interface [https://tcpreplay.appneta.com/wiki/faq.html]. So Now lemme state where the problem was occuring. I had a pcap file and I was using tcpreplay to replay those packets on a...
70,044,902
70,045,194
C++ Sort rows of a 2D array, based on the first column using bubblesort
Disclaimer: These are all fake addresses it is just for learning purposes. I want my list to be sorted based of the first columns which are the [i][0] and with that make the rest of the row ([i][j]) follow with the new sorted position column. Right now my code seems to be ONLY sorting the first columns but not making t...
Arrays are not a good datatype to do what you are trying to do. It is good to take "words" from real life and use them in your code. What you are doing is sorting contacts, so make something that represents a contact first, e.g. a struct. From there build your code, (one function at a time, functions are great for nami...
70,045,775
70,046,486
Alignment attribute to force aligned load/store in auto-vectorization of GCC/CLang
It is known that GCC/CLang auto-vectorize loops well using SIMD instructions. Also it is known that there exist alignas() standard C++ attribute, which among other uses also allows to align stack variable, for example following code: Try it online! #include <cstdint> #include <iostream> int main() { alignas(1024) ...
Though not entirely portable for all compilers, __builtin_assume_aligned will tell GCC to assume the pointer are aligned. I often use a different strategy that is more portable using a helper struct: template<size_t Bits> struct alignas(Bits/8) uint64_block_t { static const size_t bits = Bits; static const size...
70,045,994
70,046,031
Why, when I use a pointer to pass an array to a function, the array's length appears to be 1?
I'm trying to pass an array as a pointer to a function, but when I do that the function only sees the pointer as an array with 1 variable. Here is my code: void make3(int* a) { int n = sizeof(a) / sizeof(a[0]); for (int i = 0; i < n; i++) {a[i] = 3;} } int main() { int a[3] = { 0, 1, 2 }; make3(a); ...
When you pass an array to a function, it decays to a pointer. int n = sizeof(a) / sizeof(a[0]); Gets evaluated to int n = sizeof(int*) / sizeof(int); Which is 1 (when sizeof(int*) is 4 - depends on inplementation). You should pass the array size as an argument instead: void make3(int* a, int n) { for (int i = 0; i ...
70,046,617
70,046,766
Nested designated initializers
Does C++ 20 allows nested designated initializers? E.g: struct Outer { int32_t counter; struct { std::string name; } inner; struct { std::optional<int32_t> value; } inner_optional; }; Outer outer = { .counter = 100, .inner = { .name = "test" // nested } }; If this is allowed, c...
Yes, this is supported, cppreference - aggregate initialization states: If the initializer clause is a nested braced-init-list (which is not an expression), the corresponding array element/class member/public base (since C++17) is list-initialized from that clause: aggregate initialization is recursive. List initiali...
70,046,738
70,050,602
C++ Exception "Access violation reading location"
#include <iostream> #include <fstream> using namespace std; struct review { string text; string date; }; void getRegistry(int i) { review* reg = new review; ifstream file; file.open("test.txt", ios::binary); if (file) { file.seekg(i * sizeof(review), ios::beg); file.re...
The problem is that you can't read/write std::string objects they way you are. std::string holds a pointer to variable-length character data that is stored elsewhere in memory. Your code is not accounting for that fact. To be able to seek to a specific object in a file of objects the way you are attempting, you have to...
70,046,749
70,047,438
Why do i get QJsonValue(undefined)?
When I make request to API to get bid price, I'm getting QJsonValue undefined, and cannot display it later, what am i doing wrong? { QApplication a(argc, argv); MainWindow w; w.show(); QNetworkAccessManager m_manager; // make request QNetworkRequest request = QNetworkRequest(QUrl("https://api.30....
If you're confident that the JSON structure will always be the same, then you can find your value like the following. (I broke it down into multiple objects and named them the same way they are named in your JSON file.) QJsonDocument doc = QJsonDocument::fromJson(textData.toUtf8()); auto rootObj = doc.object();...
70,046,896
70,046,938
Use Functor / Predicate to find the first element smaller than its predecessor in vector
currently I am trying to use function objects to find the first element that is smaller than the previous element in a vector. For example I have vector v and its contents are { 25, 30, 10, 40}; I tried toying with functors and with the algorithm library, but I can't get a correct result. My attempt was: auto target = ...
You can use std::adjacent_find() for that. auto iter = std::adjacent_find(begin(v), end(v), [](const auto& a, const auto& b) { return a < b; });
70,047,118
70,047,167
no matching function call to error in vector.push_back
I am getting the following error while compiling my C++ program: error: no matching function for call to 'std::vector<ChainingTable<int>::Record, std::allocator<ChainingTable<int>::Record> >::push_back(ChainingTable<int>::Record*)' 324 | vector_.push_back(new Record(key, value)); The error is coming from the...
Your vector is declared to store objects of type Record, not pointers to them (Record *) but you are trying to push result of operator new which returns Record *, just use std::vector::emplace_back instead: vector_.emplace_back(key, value); Note: in this line std::vector<Record> vector_ = records_[idx]; you create a ...
70,047,234
70,047,454
C++ breaks out of the loop when filling the array
So basically I am trying to create a loop that fills a matrix with random numbers. I need to make it so every column has a different range, unique to it. //Variables int lsx = 3; int lsy = 10; int lust[lsy][lsx]; int i = 0; int l = 0; int shpp = 7; //List setup for (i = 0; i < lsy; i...
for (l = 0; l < lsx; l++) { Column 1 if (i == 0) } lust[i][l] = rand() % flx; cout << lust[i][l] << '\n'; } Column 2 if (i == 1) } lust[i][l] = rand() % fly; cout << lust[i][l] << '\n'; } Column 3 if (i == 2) { lust[i][l] = rand() % shpp; cout << l...
70,047,306
70,047,507
Clear vertex of all neighbors of v
I'm implementing an algorithm in C++ with Boost Graph. I want to find all the vertex in the neighborhood of v (so, all its neighbors), then change a property of their and finally clear all of their edges. I found in Boost the function adjacent_vertices(v,g) (where v is the vertex and g is the graph) to find all the nei...
It depends on the edge container selectors. The easiest way is when the containers are node-based, i.e. only the iterators/descriptors to any removed edges are invalidated. Another way is when you split the "query" and "modification" aspects, e.g. Compiler Explorer #include <boost/graph/adjacency_list.hpp> #include <bo...
70,047,349
70,047,406
How to locate and remove these symbols from my reversed string
This is an oddly specific problem but I need help because I am very confused. I am trying to use pointers to ask a user to input a string and the output will print the reverse. So far I have used a reverse function and applied the pointers. Here's what the code looks like right now: #include <iostream> using namespace ...
That garbarge happens because you don't have null terminating character at the beginning of the string, thus you don't terminate when going backwards. I modified your code to keep sentinel zero character at 0-th position, and now your code works without bugs. Also condition while (*p >= 0) should be replaced with while...
70,047,533
70,047,726
Why does my nested loop not check the second element of vector (empty string)?
I'm a bit stuck on this one.. my code should stop capitalising the characters when it hits the first empty string ( text[1] ).. but when I put a breakpoint in and step forward; the third string is considered straight after the first. The second element is ignored. The exercise is to print all strings but only capitalis...
If I understood right, you want to stop capitalizing after the first empty string, and not after the first empty character, something like: ONE, TWO, THREE-FOUR-FIVE. ONCE I CAUGHT A FISH ALIVE. Six, seven, eight-nine-ten. Then I let it go again. Why did I let it go? Because he bit my finger so. Which finger did he bi...
70,048,200
70,048,488
Difference between Generic Lambdas
I'm currently learning about generic lambda functions, and I am quite curious about the differences between: [](auto x){}; and []<typename T>(T x){}; They both do the same thing but is one faster than the other? What's the point of having these 2 syntaxes.
Although the two are functionally equivalent, they are the features of C++14 and C++20, namely generic lambda and template syntax for generic lambdas, which means that the latter is only well-formed in C++20. Compared to the auto which can accept any type, the latter can make lambda accept a specific type, for example:...
70,048,276
70,048,356
C++14 Static class map initialization
right now I'm creating a static class (yes, c++ does not have static classes, but to my knowledge creating a class with a private constructor gives the same result) like the following returning to me a map: class Foo() { public: static std::map<MyEnum, SomeInfo> getMap() { static const std::map<MyEnum, ...
You need to "define" your map after you "declared" it: See: https://en.cppreference.com/w/cpp/language/static #include <map> #include <string> struct SomeInfo { std::string id; std::string name; }; enum MyEnum { Enum1, Enum2 }; class Foo { private: static const std::map<MyEnum, SomeInfo> fooMap; pub...
70,048,901
70,049,325
Arrays of Objects without standard constructor using Parameter Packs
I want to fill an std::array of size N with objects without a standard constructor. std::array<non_std_con,N> myArray; (It's std::array<kissfft<float>, 64> in my case, to be specific) This results in the error error: use of deleted function ... standard constructor Setup You can fill the array using an intializer li...
You could write: #include <array> #include <utility> #include <iostream> namespace detail { template < typename T, std::size_t ... Is > constexpr std::array<T, sizeof...(Is)> create_array(T value, std::index_sequence<Is...>) { // cast Is to void to remove the warning: unused val...
70,048,927
70,049,012
Why I am getting error while concatenating variables in output in C++?
I am trying to concatenate output variables in C++ In my code there are some calculations and when I am printing the output of the variables I am getting error. My code: #include<iostream> #include<string> #include<math.h> using namespace std; int main() { string name; cout<<"Enter the name of the b...
You can use the insertion operator (<<) to display values to standard output instead of trying to concatenate a float with an array of characters. cout << mortage_blanace << " " << mortage_blanace << endl;
70,049,327
70,049,507
How to read command line arguments from a text file?
I have a program that takes in one integer and two strings from a text file "./myprog < text.txt" but I want it to be able to do this using command line arguments without the "<", like "./myprog text.txt" where the text file has 3 input values. 3 <- integer AAAAAA <- string1 AAAAAA <- string2
If the reading of the parameters must be done solely from the file having it's name, the idiomatic way is, I would say, to use getline(). std::ifstream ifs("text.txt"); if (!ifs) std::cerr << "couldn't open text.txt for reading\n"; std::string line; std::getline(ifs, line); int integer = std::stoi(line); std::getli...
70,049,647
70,050,377
Why is it not recommended to use a heap to sort a LinkedList?
I know how to sort a linked list using merge sort. The question is, why don't we just use a heap to create a sorted LinkedList? Traverse the linked list and keep adding items to a min-heap. Keep taking the items out of the heap and heapify the heap and add to a new result LinkedList. step one will have O(n) for trave...
I know how to sort a linked list using merge sort. The question is, why don't we just use a heap to create a sorted LinkedList? Traverse the linked list and keep adding items to a min-heap. Keep taking the items out of the heap and heapify the heap and add to a new result LinkedList. Several reasons, among them: A...
70,049,958
70,489,827
Exception thrown at ispunct() when reading words from a text file - C++
Trying to create a program that reads words from a text file and outputs 20 password combinations with 4 words in each and with certain conditions such as no punctuation in word, no digits, and no characters other than the first may be uppercase. However, I am getting an exception thrown at ispunct(b[i]) and I think it...
There are a number of fundamental errors in your code (and your reasoning) that make it seem like your textbook isn't working out so well for you. For example, your diagnosis is only half correct: I think it has to do with the changing sizes of the words but I am not sure That's just a guess. In fact, if we stop bein...
70,050,126
70,067,970
Is there any possible way to resize an PNG image in SDL2?
I am using SDL2 and SDL_image.h. My current attempt was trying to fit the .PNG image in a SDL_Rect which only hid my image in the rectangle's area and thus did not work. I was following this tutorial to load the .PNG image. I'm looking to make the image stretch to the same size of the screen which is 640x480. This was ...
Looking at documentation maybe you should try using SDL_BlitScaled instead of SDL_BlitSurface
70,050,160
70,050,217
Calling delete on std::stack of pointers
I have a std::stack which has some pointers inside: std::stack<State*> m_states; When I initialize my program, I call new to push an item onto the stack (it must be a pointer because I will use polymorphic types). Is this the correct way of deleting with all the stuff? Here is where I call new (GameState and MenuState...
Should I only call (*) or do I need to pop as well? Well, if you don't call pop() in the while loop, then how will that loop ever end? In other words, how will the condition, !m_states.empty() ever become false? There are other container types (like std::vector) where you could just run through each member, deleting ...
70,050,271
70,050,303
Access violation reading location 0xFDFDFE01
This is the entire code, i use no header files this code must input a tree and then write out its high, the problem is in the function High() in the line if (tree[headIndex][1] == -1 && tree[headIndex][2] == -1) {, it says : Access violation reading location 0xFDFDFE01. #include<iostream> using namespace std; int** In...
A recursive call to High can be called with headIndex equal to -1. Your recursion only stops when both child nodes are -1, but if one of them is -1 and the other points to another node, you'll make a recursive call and dereference an out-of-bounds index. One way to fix this is to check each node before making the recur...
70,050,535
70,050,695
Passing array into constructor parameter and creating an array of structs using the value of the array
I am currently writing a class for a polygon that will be drawn onto the screen. My problem however, is that I am unable to figure out how to create an array of structs from an array of arrays (which hold integers, for x and y of each vertex). I am passing this array through the constructor. I assume my error is to do ...
How about this? struct Point { int x , y; }; class Polygon { private: Point m_centre; std::vector <Point> m_vec_vertices; public: Polygon(const Point& centre, const std::vector<Point> &vertices) :m_centre(centre), m_vec_vertices(vertices) { } //etc.... }; int main(){ Polygon polygon({0, ...
70,050,778
70,051,978
Accessing dimension of boost multi-arrays in C++
When I run the following with warning flags I get a type conversion warning. #include <boost/multi_array.hpp> void function (boost::multi_array<unsigned char, 2> matrix) { int nrows = matrix.shape()[0]; int ncols = matrix.shape()[1]; } See warning message below. Does this mean I am implicitly converting a 'long u...
Does this mean I am implicitly converting a 'long unsigned int' into a regular 'int'? Yes, that is what it means. If you don't want the warning then don't make nrows and ncols be of type int. The easiest thing to do is to just let the compiler deduce the type i.e. auto nrows = matrix.shape()[0]; auto ncols = matrix.sha...
70,050,806
70,050,818
Why does std::begin behave differently when called in a nested function
I have some simple code #include<iterator> int main() { int y[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; auto a = std::begin(y); std::cout << *a << std::endl; return 0; } Which prints out 1 as expected. However if I do this : void checkNested(int val [10]) { auto a = std::begin(val); std::cout << *...
An array can't be passed by value, so your array decays into a pointer when passed to checkNested(), and std::begin() is not defined for a pointer, hence the error. void checkNested(int val [10]) is just syntax sugar for void checkNested(int *val). If you pass the array by reference instead, then the code will work: vo...
70,050,839
70,051,065
Can't insert non-const value in unordered_map of references
I'm trying to create 2 std::unordered_map, one holds <A, int> and the second one holds <int&, A&>. I'll explain at the end why I want to do this if you're curious. My problem is that k_i has value of type std::reference_wrapper, k_i.insert doesn't work. But if I make k_i to have value std::reference_wrapper<const A>, t...
From UnorderedAssociativeContainer requirements: For std::unordered_map and std::unordered_multimap the value type is std::pair<const Key, T>. In your code k_s is unordered_map<A, int>, so the value type is pair<const A, int>. In here: auto it = k_s.find(a); you get a "pointer" to such pair, and type of (*it).first ...
70,051,136
70,051,386
Translating text to Morse , not sure how to achieve required output
Need to translate text to Morse for an assignment. The outputted format of the Morse needs to be like this ".../---/... "space" .../---/..." With a space in between words , and a / in between characters. However the / cannot be at the beginning or end of word. Mine outputs like this " .../---/.../ "space" /.../---/.../...
The key here is to understand when exactly you would need to add a / after the character. Currently, inside the for loop of word2Morse, you are adding / after translating every character. However, you actually don't want / before or after an word. However, you can't tell the program to not put a slash before or after a...
70,051,204
70,051,584
Visual Studio Debugger: Register a display format for a specific C++ struct/class
How to let the Visual Studio Debugger know that a specific C++/C struct should be displayed in a specific Format? I've for example a C-struct containing 2 pointers that represent the start and end of an array like the following: typedef struct { VEC_VALUE_T* __restrict DataBegin_; VEC_VALUE_T* __restrict DataEn...
As mentioned by @retired-ninja in comment, the natvis framework can be used: https://learn.microsoft.com/en-us/visualstudio/debugger/create-custom-views-of-native-objects?view=vs-2022 Add natvis file in VS right click on project tab -> Add new item -> Utility -> .natvis Add a type element for that specific struct/class...
70,051,330
70,051,471
if deleting top pointer deletes all pointers
I have a doubt. Let’s say that I have implemented a stack in a way similar to a linked list, like this (there are just a push and a print function) #include <iostream> template <class T> struct node{ T data; node<T> *down; }; template <class T> class mystack{ public: node<T> *top = new node<T>; mystac...
Your single delete is insufficient. You need something like: ~mystack() { while(top != nullptr) { node<T> *curr = top; top = top->down; delete curr; } std::cout << "DESTRUCTION!" << std::endl; } That way, you delete every element in your container.
70,051,521
70,051,555
How to pass a 2D arrays of pointers to 3D arrays of pointers (function and class) and return 3d arrays of values in C++?
I am currently working on C++, creating a program of the analysis of matrices. As far as i saw those can be created using an arrays of arrays like this array2D[3][3]={{1,2,3},{4,5,6},{7,8,9}}. Therefore, what i did was to generate a function in a class, such a function must return a 2D array. Then i created another cla...
The problem is that the function matrixOfIndexes returns a 3-dimensional pointer (int***) but the array you're assigning that return value to is a two-dimensional one (int**). The types have to match. To fix it just add an extra * to the declaration of indexes: int*** indexes = {};
70,051,666
70,052,326
C++ how to handle file with multiple data types?
I have an input txt file which contains information like this: 4 Eric Nandos 3 15.00 45.00 36.81 64.55 50.50 51.52 36.40 25.15 35.45 24.55 41.55 44.55 36.35 55.50 40.55 Steven Abraham 2 40.45 20.35 40.46 30.35 55.50 18.25 18.00 20.00 30.00 60.65 Richard Mccullen 2 40....
The first line specifies the number of records in the file, where each individual record then consists of: 1 line for a person's name 1 line specifying the number of following lines N number of lines of floating-point numbers You can read such data like this: #include <fstream> #include <sstream> #include <string>...
70,052,134
70,052,178
Elegant solution to implementing c++ templates
Inspired by this 2009 question Background: I'm currently working on a small c++ project and decided to try my hand at creating my own templated classes. I immediately ran into a dozen linker errors. As it stands, my understanding is that template specializations aren't generated until they absolutely need to be, and th...
Why is it so? As templates compiles through two phases in first phase compiler checks mostly for syntactical errors. If there is no error found in your template is legal to be used, but at this stage compiler do not generate any code for it. And in the second phase compiler will generate the code for all the class mem...
70,052,228
70,052,281
Why is the move constructor called 2 times?
main.cpp #include <iostream> #include <vector> #include "Person.h" using namespace std; int main() { vector<Person> test{}; test.push_back (Person{ "Chinese", 16 }); test.push_back(Person{}); return 0; } Person.h #pragma once #include <iostream> class Person { public: std::string* ethnicity; ...
But why are there 3? When std::vector needs more space, it allocates a new array and copies/moves all the existing elements from the old array to the new array. Solution 1 To minimize this, use the std::vector::reserve() member function before pushing elements onto the vector. This pre-allocates the needed space. vec...
70,052,270
70,052,398
Why isn't std::hash<const std::string> specialized in std?
Why isn't std::hash<const std::string> specialized in std? It causes compile error like std::unordered_map<const std::string, int> m; m.insert(std::make_pair("Foo", 1)); //error m["Bar"] = 2; // also error Is there any reason for this ?
Why isn't std::hash<const std::string> specialized in std? In fact, std didn't specialize any std::hash<const T>. The reason is probably it's not needed. For any std::hash<T>, the only function it has is an operator(), which takes in const T& as it's argument. So even if std::hash<const Foo> was specialized, it would...
70,052,298
70,054,262
Speed-up eigen c++ transpose?
I know that this 'eigen speed-up' questions arise regularly but after reading many of them and trying several flags I cannot get a better time with c++ eigen comparing with the traditional way of performing a transpose. Actually using blocking is much more efficient. The following is the code #include <cstdio> #include...
As suggested by INS in the comment is the actual copying of the matrix causing the performance drop, I slightly modify your example to use some numbers instead of all zeros (to avoid any type of optimisation): for(i=0; i<n; ++i) { for (j=0; j<n; ++j) { a[i][j] = i+j; M1(i,j) = i+j; } } for(i=0...
70,052,348
70,052,414
Program stuck in Infinite loop
My program is going in infinite loop and does not print required output please help anyone
On the 2nd and subsequent iterations of the outer while loop, space will be initialized with a non-zero value, and then the while(space) loop will keep incrementing space for a long time until it overflows to a negative value, and then keep looping for a long time further until space eventually increments to 0, finally...
70,052,690
70,053,145
C++ How to handle user input given in contests/problems format
Recently I have been starting to participate in c++ contests but I cannot find the best way to handle user input when given in this format. E.g. 4 and 3 are the dimensions of the next block of input 4 3 1 2 4 5 1 6 7 4 1 5 0 0 The problem I've been having is that sometimes the automatic testing machine successfully ...
First of all, I am sorry for you that you made the decision to participate in such contests. It will help you to learn on how to solve algorithms, but they usually use an extremely bad programming style. Anyway. Back to your question. As always. It depends. If you have data that are just separated by white space, you c...
70,053,247
70,053,357
How do I setup the width?
We are given an assignment wherein we are supposed to output a given txt file and solve for the BMI. However, I am having problems with how to output the data as it is not following my desired alignment. Any help would be appreciated! I apologize if my question is very simple as I am not that good at programming. Here ...
One possible way would be : #include <iostream> #include <iomanip> #include <fstream> #include <stdio.h> #include <string> using namespace std; int main() { string no, firstin, lastin, weight, height; ifstream inFile; inFile.open("homework.txt"); std::cout << std::setw(13) << std::setfi...
70,053,253
70,054,954
How to change type of elements in C++ boost multi array?
I receive a matrix with elements of type unsigned char from another function and I am trying to find its max value. boost::multi_array<unsigned char, 2> matrix; All elements are integers and so I was hoping to recast matrix as type <int, 2> then perform std::max_element() operation, but unsure how to recast type of a ...
You don't need that to use max_element. char is an integral type just like int: Live On Compiler Explorer #include <boost/multi_array.hpp> #include <fmt/ranges.h> #include <algorithm> int main() { using boost::extents; boost::multi_array<unsigned char, 2> matrix(extents[10][5]); std::iota( // ...
70,053,390
70,056,867
How to send .mp4 file over TCP in C/C++?
I am trying to send files over TCP client/server in C++ app. The scenario is pretty simple; Client side send files and server side receive files. I can send text based(such as .cpp or .txt) files successfully, but when I try to send files such as .mp4 or .zip, the files received on the server are corrupted. client.cpp ...
I found the solution by going the way G.M. mentioned in the comment. Adding a null character to the end of a file opened in binary mode causes problems for non-text-based files. Another issue is with the use of the << operator. Instead ofstream's write member function needs to be used. As a result; server.cpp //... //....
70,053,971
70,054,410
Cost of copy vs move std::shared_ptr
Why would I std::move an std::shared_ptr? Answers to this question point out that moving a std::shared_ptr is all about speed, but nobody explains why it is faster in detail. How expensive is it really in comparison? Is it worth optimzing when one uses it a lot?
I wrote a benchmark. On my Macbook Air it is three times faster (g++ as well as clang++ -std=c++17 -O3 -DNDEBUG). Let me know if you see problems with the benchmark. #include <chrono> #include <iostream> #include <vector> #include <memory> using namespace std; using namespace std::chrono; int COUNT = 50'000'000; str...
70,054,164
70,054,336
ARM GCC removing required code during optimization
I have the following code that does a really basic conversion from 16bpp image to a 1bpp image, the code functions as expected until I enable compiler optimizations, at which point I just get a black image. #define RSCALE 5014709 #define GSCALE 9848225 #define BSCALE 1912602 uint16_t _convertBufferTo1bit(uint8_t* buff...
In this code: lum = ((RSCALE * r) + (GSCALE * g) + (BSCALE * b)); if(lum > 0x7FFFFFFF) RSCALE, GSCALE, and BSCALE are 5014709, 9848225, and 1912602, respectively. Assuming int is 32 bits in the C implementation being used, these are all int constants. r, g, and b are all of type uint8_t, so they are promoted to int in...
70,054,197
70,054,357
How to iterate map<int, vector <int>>?
I have map<int, vector > like this: #include <iostream> #include <map> #include <vector> using namespace std; int main() { map<int, vector <int>> someMap; someMap[5] = {5, 2, 3, 7}; someMap[151] = {5, 9, 20}; return 0; } I need to find the last vector element in each map value. Output must be l...
You can use the std::vector::back member function as shown below: #include <iostream> #include <map> #include <vector> #include <cassert> using namespace std; int main() { map<int, vector <int>> someMap; someMap[5] = {5, 2, 3, 7}; someMap[151] = {5, 9, 20}; //iterate through each element of the ma...
70,054,580
70,063,693
stringstream does not allocate integers to integer vector
I have a string of different integers separated by a comma. For example "45,67,2,3,8,9,123,5,6,3,9,4,7,2,4,4,5,69,9,99". I want to read this line as a stringstream and put integers to the vector of integers. On the console, it displays "no response on stdout". The code looks as follows: #include <sstream> #include <vec...
The working code: #include <sstream> #include <vector> #include <iostream> using namespace std; vector<int> parseInts(string str) { stringstream myString(str); int size = str.size(); vector<int> of_integers; char ch = ','; int a=0; while(myString.eof()!=1) { myString >> a >> ch; ...
70,054,587
70,054,986
Why C++ static data members are needed to define but non-static data members do not?
I am trying to understand the difference between the declaration & definition of static and non-static data members. Apology, if I am fundamentally miss understood concepts. Your explanations are highly appreciated. Code Trying to understand class A { public: int ns; // declare non-static data member. static in...
When you declare something, you're telling the compiler that the name being declared exists and what kind of name it is (type, variable, function, etc.) The definition could be with the declaration (as with your class A) or be elsewhere—the compiler and linker will have to connect the two later. The key point of a vari...
70,054,624
70,065,643
Unknown protocol: protocolId = 92, protocolName = CbdProto, servicePrimitive = REQUEST
I try to implement a Network Layer Protocol, using the INET SensorNode module. I properly extend the NED simple module as follow : simple CbdProto extends NetworkProtocolBase like INetworkProtocol { @class(inet::CbdProto); } This protocol is added to the list of the INET Procotol class (Protocol.cc) by extending t...
You don't have to create a new class. You just have to add your new protocol to the Protocol.cc and .h file, to the existing Protocol. (Don't forget to create an instance in the .cc file. Your new protocol provides a service to the upper layer so you have to use registerService() in your protocol's code.
70,054,650
70,054,694
How const char* strings are compared?
Firstly, consider this example: #include <iostream> using namespace std; int main() { cout << ("123" == "123"); } What do I expect: since "123" is a const char*, I expect ADDRESSES (like one of these answers said) of these strings to be compared. ... because != and == will only compare the base addresses of thos...
Yes, the linked answer is correct. operator== for pointers just compares the addresses, never their content. Furthermore, the compiler is free, but not required, to de-duplicate string literals, so all occurrences of a string literal are the same object, with the same address. That is what you observe and re-assignment...
70,054,880
70,055,025
What is the casting order of operations in arithmetics in c++?
Why does result = static_cast<double>(1 / (i+1)) return int in C++ and why does result = 1 / (i+static_cast<double>(1)) return double? Specifically why is casting after the +-operation sufficient to produce a double. Why is it not required before the + or in the numerator as well? Is static_cast the preferred way o...
There's no such thing as "casting order" because the type of an expression depends on its operands. Put it simply, if a binary arithmetic operator accepts two operands of different types then the smaller type will be implicitly converted to the wider type In result = static_cast<double>(1 / (i+1)) it's parsed like this...
70,055,219
70,056,483
Why does passing a parameter pack to a function with one template parameter call it multiple times?
Take this code: template<typename T> int foo() { std::cout << "foo called" << std::endl; return 10; }; template<typename... Ts> std::vector<int> bar(Ts... ts) { std::vector<int> vec{foo<Ts>()...}; return vec; }; int main() { std::vector<int> vec = bar(1,2,3,4); } The code above outputs: foo calle...
foo<T>()... is expanded to foo<T1>(), foo<T2>(), foo<T2>(), .... In your case, since your vector has four components, your function will be called four times with the expansions.
70,055,308
70,055,455
"Pointer to incomplete class type is not allowed"
For some reason I cannot use the "getNotify()" function attached to the "Broker" object. I added a comment to the line that is not working(in "Publisher" class). As an error I get "Error; pointer to incomplete class type is not allowed" Please help the "Broker" class is implemented with Singleton-Pattern Broker.h class...
Normally you would need to include broker.h in classes.h, however, this would create a circular dependency. Therefore, implement the functions of Publisher in a .cpp file and include broker.h in that file. The forward declaration in classes.h (class broker;) needs to remain.
70,055,336
70,055,388
Is there a way to call the destructor of a replaced element when using std::replace?
I have a vector of objects where I want to replace one element by another. Using std::replace seemed appropriate, so I gave it a try. I was concerned about the whereabouts of the replaced element though, so I did some tests : #include <iostream> #include <vector> #include <algorithm> class A { public: A(const ...
From cppreference on std::replace: Because the algorithm takes old_value and new_value by reference, it can have unexpected behavior if either is a reference to an element of the range [first, last). Therefore, this is wrong: std::replace(v.begin(), v.end(), v[2], A(25)); Indeed, we can't choose old_value to be a re...
70,055,550
70,055,765
Resolution of class template with different default template argument and partial specialization argument
I have two class (struct) templates A and B, which are identical except that the second parameter's default argument (in their primary templates) and the template-specializing second argument (in their partial specializations) are the same in A (both void), while different in B (void and int respectively). #include <bi...
If I understand the confusion, when you see /* primary class template B */ template <int N, class = void> struct B : std::false_type {}; /* partial specialization of B */ template <int N> struct B<N, std::enable_if_t<(N != 0), int>> : std::true_type {}; You think that when the compiler sees B<1> in main, it sees tha...
70,055,737
72,158,332
Is constrained auto cast valid?
Since C++20, the constrained auto is introduced by: Concept auto identifier = init Which means, for instance: std::integral auto x = 10; is valid. Also, for new-expressions, concept is allowed to be paired with auto: new Concept auto { expr }; // or: new Concept auto ( expr ); auto{expr} or auto(expr) was introduced...
[dcl.spec.auto.general]/5 allows only auto to be the simple-type-specifier of a functional type conversion, even though a constrained placeholder-type-specifier can be a simple-type-specifier grammatically.
70,055,751
70,055,946
Given n positive integer numbers.Print how many numbers occurs at least 2 times in this array on C++
Input: 4 1 2 2 3 Output: 1 Hello guys! There is one problem...I planned to make this through a map, but... `#include <iostream> #include <map> using namespace std; int main(){ int n; cin >> n; int arr[n]; map<int,int> m; map<int,int> :: iterator it = m.begin(); for(int i = 0;i < n;i++){ ...
I am assuming that in if statement you want to check if find algorithm returned end of map. Better way to do it is to try to insert value into map and check operation return value. You should change it to: if (!m.insert({arr[i], 1}).second) { counter++; }
70,055,752
70,056,866
insert method for doubly linked list C++
I am implementing doubly linked list in C++, and I have been trying to make my insert method work without success. The class should contain two node pointers: one to the head of the list, and one to the tail of the list. If the list is empty, they should both point to nullptr. The insert method should take a value at g...
I tried to fix all of your methods, probably succeded, at least current test example is printing correct answer: Try it online! #include <iostream> #include <vector> using namespace std; struct Node { int value; Node *next; Node *prev; //previous node pointer Node(int v) : value(v), next(nullptr), prev...
70,055,969
70,055,986
erase() in list does not work in c++ on MacOS. What is bash: line 1: 88225 Segmentation fault: 11?
#include <iostream> #include <list> using namespace std; int main () { list<int> mylist; list<int>::iterator it; for(int i=1;i<6;i++){ mylist.push_back(i); } for (it=mylist.begin(); it!=mylist.end(); ++it) cout << ' ' << *it; cout<<endl; for(it=mylist.begin(); it!=mylist.end(...
You need to write if((*it)==2){ it = mylist.erase(it); mylist.insert(it,9); break; } To output the list it is better to use the range-based for loop. Also to find an element in the list with the given value it is better to use the standard algorithm std::find instead of using a for loop....
70,056,043
70,056,136
How to kill a process with QProcess::execute()?
I've some problems with killing a process using taskkill. My code: QStringList args; args << "/F"; args << "/IM testApp.exe"; QProcess::execute("taskkill", args); //Should be 'taskkill /IM testApp.exe /F' Output (translated from german): ERROR: Invalid argument - "/IM testApp.exe". Type "TASKKILL /?" to show the synta...
"/IM testApp.exe" makes a single arg, but should be two args. You get the command taskkill /F "/IM testApp.exe". The proper invocation is QStringList args; args << "/F"; args << "/IM"; args << "testApp.exe"; QProcess::execute("taskkill", args);
70,056,246
70,056,420
VS2019 explicit specialization requires template<> error with 'using' keyword
I have this piece of c++ code, and VS2019 to compile it: #include <iostream> template<typename t> class c { }; int main(){ using o = class c<int>; } does anybody know why it does not compile, complaining about: Error C2906 'c<int>': explicit specialization requires 'template <>' With mingw-gcc it compiles a...
class is unnecessary in the using statement, I think visual studio thinks you are trying to declare a specialisation of c: template <> class c<int>; hence the error message. All you need is: using o = c<int>;
70,056,539
70,056,716
Disable class template member for void types?
Considering the following basic class template: #include <type_traits> template < typename T > class A { public: A() = default; T obj; template < typename U = T, typename = typename std::enable_if< !std::is_void< U >::value >::type > T& get(); }; I'm using <type_traits> to get a simple SFINAE imple...
The first problem is that you are trying to define a variable using T obj; where T is void. But according to documentation Any of the following contexts requires type T to be complete: definition of an object of type T; But since void is incomplete type, you get the error: error: 'A::obj' has incomplete type Sec...
70,056,563
70,057,084
Wy can't I cast a statically cast Lambda as a TIMEPROC Function pointer in a settimer?
I coded this multiple times. But it doesn't even seem to work in a simple console hello word application. Is hWND the one to blame, lambda, or the casting of the lambda? void sleeper() { Sleep(10000); } int main() { SetTimer (GetConsoleWindow(), 1, 1000, [](HWND, UINT, UINT_PTR, DWORD) { pri...
You cannot cast a lamba to a TIMEPROC* or any other type of function pointers that use a different calling convention than the default (one can not specify the calling convention of a lambda). Lambdas are callable objects. This type is similar to a class, with a member function. Aside from that, you MUST use the corr...
70,056,750
70,056,817
Why don't const l-value references to r-values result in dangling references?
Why is the following not an error? const auto& foo = std::string("foo"); In my mental model of C++ I think of references as glorified non-null pointers that the language wraps in syntactic sugar for me. However the code below would be an error but the above is not. const auto* foo = &(std::string("foo")); In the refe...
Because this is the language rule Lifetime of a temporary Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifetime of the reference. There is no such rule for const pointers.
70,056,960
70,057,189
SSH to port exposed by container - permission denied
I have a docker container running and it's exposing port 22 to local host port 1312. I am using the following command to run the container: docker run -it -d -p 127.0.0.1:1312:22 -v /workspace/project:/root --name cpp_dep cpp_dep Now to build the project in CLion, it need to be able to ssh into the container. I enter...
You may enter the container in interactive mode, use whoami to find the current user while use passwd to change the password of current user, then ssh into it using the updated passwd. More details if you are interested: User running the container is decided by USER config in your Dockerfile: https://docs.docker.com/e...
70,056,975
70,057,004
Array index loop to begin instead of mem access error
I'm currently developping a vision system which is controlled/moonitored via a computer application that I'm writting in C/C++. If you are wondering why I,m writting in C/C++ its basically that my vision sensor (LMI Gocator 2490) has functions developped in C and that I'm using opencv (C++) to analyse its data. Long st...
use modulus to wrap when reaching the upper bound long a[4]; size_t sz = sizeof(a) / sizeof(long); for (size_t i = 0; i < sz; i++) { if (a[i] && a[(i + 1) % sz]) //Define some conditions regarding a[i] and a[i+1] { //Process code } } maybe not super-optimal performance wise, though (well, with a v...
70,057,205
70,237,776
Is it possible to get something similar to std::next_permutation, but doesn't always use all the letters in the string?
I currently have this code void get_permutations(std::string s, std::vector<std::string>& vec) { std::sort(s.begin(), s.end()); do { vec.push_back(s); } while (std::next_permutation(s.begin(), s.end())); } and it works as intended, but next_permutation uses every character in s, and I would like to...
Yes, there is more or less a standard approach. Counting and bit masking will be used. If you have some permutation of 3 letters, like "abc", then we will create bit masks like the following: 1. 001 --> "--c" 2. 010 --> "-b-" 3. 011 --> "-bc" 4. 100 --> "a--" 5. 101 --> "a-c" 6. 110 --> "ab-" 7....
70,057,408
70,057,527
Recursive Function to Iterative Function
//Binary Search Tree #include <iostream> #include "BinaryNode.h" using namespace std; template <class V> class BinaryTree { BinaryNode<V> *root; int nodeCount; public: BinaryTree(); //BinaryTree(const V& newValue); bool isEmpty() const; int getHeight() const; int _getHeight(BinaryNode<V>*)...
You can start with a while loop and 2 pointers like this: BinaryNode<V> *curr = root; BinaryNode<V> *prev; if (!isEmpty()) { while(curr) //while current is not null { prev=curr; if(newValue>curr->getValue()) { curr=curr->right; } ...