FAQ Database Discussion Community


Standard way of shortening C++ function signatures

c++,templates,stl,function-declaration
The templates always get really lengthy when I have certain vector and templated contained objects and the end just looks like a bunch of > > > > > > > that hardly helps discern boundaries sometimes, like this: std::vector< std::pair< std::string, std::set< std::string > > > Is there a...

'operator<' error while creating an std::pair

c++,qt,stl
I already have a workaround for this but would still like to understand the problem. I have a Multimap multimap<QPoint,Figure*> mymap; QPoint is a class from Qt 5.4. Figure* is a pointer to a class I have concocted myself. Now I want to add elements to that map. This sample...

How to remove a customized object using stl remove from container set?

c++,stl,set,remove-if
Following is the class and container class student { std::string name; int id; } set<Student*, compare> s; // sorted by id that i have done correctly class compare { public: bool operator()( Student* s1, Student* s2) { return s1->id < s2->id; } }; How to remove a object from set...

Considering complexity of STL container operations

c++,algorithm,stl
Do we factor-in the time/space complexities of STL container operations when calculating the complexity of an algorithm? For example, given the following code snippet: // str is an std::string, and size = str.size() std::string res; for (int i = 0; i < size; i++) // size is some integer res...

Which STL container(s)/algorithm(s) could I use to solve this?

c++,algorithm,sorting,stl,containers
I have an MFC project which, given an initial root path, iterates through every file, folder and subfolder, and subsequently displays each file to the user in a List Control. Since this can easily become a rather lengthy operation, I occasionally yield control to the operating system (via processing a...

For a data member, is there any difference between dynamically allocating this variable(or not) if the containing object is already in dynamic memory?

c++,design,stl,smart-pointers,c++14
I'm starting with the assumption that, generally, it is a good idea to allocate small objects in the stack, and big objects in dynamic memory. Another assumption is that I'm possibly confused while trying to learn about memory, STL containers and smart pointers. Consider the following example, where I have...

Using vector std::find with a user-created object - third argument

c++,stl,iterator,find
I am trying to make use of std::find to search a vector and return an iterator of the required object is found. The problem I am having is that I am not sure what to put as the third argument. Below is the relevant line of code as well as...

passing std::unique_ptr.get() as a parameter to addWidget()

c++,qt,c++11,stl,smart-pointers
I am trying to pass a QWidget pointer argument (plot2) to Qt's addWidget(QWidget * T,...) function that takes a pointer to a QWidget as its first argument. If I pass the raw pointer plot2, I get the two side-by-side panels as expected. raw pointer version plot1 = new QWidget; plot2...

Problems compiling NDK project with Android Studio 1.3 preview

android,android-studio,gradle,stl,android-ndk
Decided to give the new NDK support in Android studio a shot but seem to be running into an issue: Error: 'std::function' has not been declared Had a few other linking issues with stl libraries before but those were fixed by adding stl "stlport_static" cFlags "-O2 --std=c++11 " to the...

How can I find out if a map contains a given value?

c++,dictionary,stl
I'd like to find out whether a given value is present in a map. Also getting the corresponding key(s) would be nice but is not required. bool map::contains(string value); Is there a simple way to do this other than to iterate over the whole map and comparing each value with...

Cannot assign a vector iterator

c++,vector,stl,iterator
I cannot use =operator in the below code, as I am getting compiller error. I cannot understand what is wrong. int CProcessData::calculateMidPoints(const std::vector<double>& xv, const std::vector<double>& yv) { if((0 == xv.size()) || (0 == yv.size())) return 1; std::vector<double>::iterator it; for (it = xv.begin(); it < xv.end(); it++) { } return...

Does const containers have only const iterator?

c++,stl,iterator,standard-library
Why do const STL containers only return const_iterators? For example both std::vector and std::list have the method begin overloaded as: iterator begin(); const_iterator begin() const; const_iterator cbegin() const; I thought I could still modify values of a const vector but not the vector itself. According to the standard library there...

How to find all elements that correspond to a vector of keys?

c++,algorithm,c++11,dictionary,stl
I have a std::vector<std::string> k; with keys values of witch I seek for. I have a std::map<std::string, void*> table; I search in. I want to get a std::vector<void*> v; of values for all keys that are in k (if such values exist in table, not all keys can be presented...

Passing iterator's element to a function: wrong type of pointer

c++,pointers,stl,iterator
I'm attempting to solve Project Euler's problem #3 using C++ to gain an understanding of how to use C++ iterators. According to the examples I've seen online, I can use the dereferened iterator as a parameter for cout, and it will print the elements successfully. By that same logic, I...

Is there a flat unsorted map/set implementation?

c++,c++11,boost,stl,containers
There is the boost.container flat_map and others, and the Loki AssocVector and many others like these which keep the elements sorted. Is there a modern (c++11 move-enabled, etc.) implementation of an unsorted vector adapted as a map/set? The idea is to use it for very small maps/sets (less than 20...

Including STL in static libraries

c++,c++11,stl,static-libraries
I have created a static library with the files alien.h and alien.cpp below. That library is linked by the file user.cpp. If one removes the line with the comment, then the code compiles, links, and runs as expected. As it is, the library and the program compile, the program however...

Must the C++ standard library support classes that are picky about who their friends are?

c++,stl,language-lawyer,friend,access-modifiers
This question is easiest to illustrate with an example, so here goes: Is code like the following guaranteed to be valid, and compile & run correctly? (Not all implementations actually compile it correctly, but I'm wondering if that's a bug.) #include <algorithm> class Picky { friend Picky *std::copy<Picky const *,...

C++ atomic list container

c++,list,stl,containers,atomic
Probably this is a stupid question and I get downvoted but I'll ask it anyways. I'm playing around with std::atomic but I think I didn't fully understand the concept. I'm wondering why there are no atomic Containers. So I played a Little bit around. First I tried the following: std::atomic<std::list<int>...

C++ Unordered Map

c++,dictionary,stl,unordered-map
I have a program in which I am using an iterator to get access to a value of a map entry . #include <iostream> #include <cstdio> #include <unordered_map> #include <utility> #include <algorithm> using namespace std; int main() { int a[]={1,2,4,7,9,3,3,55,66,88,11}; int k = 58; unordered_map<int,int> c; int i=0; for(auto x:...

Is there a way to prevent insert or erase on STL unordered_map?

c++,dictionary,stl
I frequently use unordered_maps with fixed / constant keys, but mutable values. Example: If you have an enum Dimension{ X, Y }, you might want to store a data point for each but never allow inserts or deletes for the map. Updates are OK. Example initialisation: typedef std::unordered_map<Dimension, std::size_t> Dimension_To_Size_Map;...

Stream of Integers arriving at specified interval need to look sorted

c++,algorithm,stl
Interview question: There is a stream of Integers that arrives at specified intervals (say every 20 sec). Which Container of STL would you use to store them so that the Integers look sorted? My reply was map/set when there is no duplicate or multimap/multiset when there is duplicate. Any better...

Thread-Safe Unordered Map that is being Continuously Iterated Over

c++,multithreading,templates,stl
I have collections of classes that can be accessed using the following template: template <typename T> using RegistryMap = std::unordered_map <std::string, T *>; template <typename T> class Registry { static RegistryMap<T> registry; public: static T* get(const std::string& name) { auto it = registry.find(name); return it == registry.end() ? nullptr :...

Use boost::circular_buffer as STL container

c++,c++11,boost,stl
I've written a lot of code using std::vector<T> and std::vector<T>::iterator. Now I've decided to replace the vector container with a circular buffer from boost, namely boost::circular_buffer<T>. Of course now the compiler will complain for every function that uses std::... where I'm passing the boost::... counterpart. Do I have to rewrite...

How to use const InputIterators to write a function for generic containers?

c++,c++11,stl,iterator,const
I'm trying to understand how to write a (stand-alone)function that takes const InputIterators and does something simple while iterating over every element in the container. For simplicity, I'm considering a simple print function, that would print all elements in the range between [first..last), but the function is not allowed to...

Printing values using Iterator on 2d vector

c++,vector,stl,iterator
Here is my code: std::vector< std::vector<std::shared_ptr<int>> > om(2, std::vector<std::shared_ptr<int>>(2)); om[0][0] = std::shared_ptr<int>(std::make_shared<int>(1)); om[0][1] = std::shared_ptr<int>(std::make_shared<int>(2)); om[1][0] = std::shared_ptr<int>(std::make_shared<int>(3)); //init values om[1][1] = std::shared_ptr<int>(std::make_shared<int>(4)); std::vector<std::shared_ptr<int>>::iterator pd; //inner iterator...

Finding all keys that correspond to same value in std::unordered_map

c++,c++11,stl,c++14
I have an unordered_map looking like this: std::unordered_map<int, std::string> theMap2 = {{1,"a"}, {2,"b"}, {3,"c"}, {4,"a"}}; I want to find all the keys that have same value lets say 1. Any suggestions beside the obvious way: std::vector<int> arrKeys; std::string value = "a"; for (const auto& element : theMap) if (element.secont ==...

How would one replace a vector with a linked list c++

c++,list,vector,stl,linked-list
I have a code with a template class and a few data members, the code for vector looks like this std::vector<Check> ck(100); how would one go about making this into a linked list?...

pre/post increment operator on OutputIterator

c++,stl,stream,iterator
I read in an article on OutputIterator that we only can dereference it as lvalue. My question is about operator++ which increments the iterator by one position. So, *it++ = t would be {*it = t; ++it; } https://www.sgi.com/tech/stl/OutputIterator.html Now, I am assuming that operator++ would be overloaded in such...

Assigning to an element via iterator

c++,stl
I thought we can assign a new value to the elemnt of a container through its non-const iterator. So I tried that: #include<iostream> #include<set> typedef std::set<int>::iterator it; std::set<int> set_int; int main() { set_int.insert(1); it i = set_int.begin(); *i = 11; //error: assignment of read-only location } and failed. Why did...

Seg Error while erasing from multiset C++

c++,stl,segmentation-fault,multiset
I don't know whats making this code give an error. It's a simple multiset. No compilation errors, but segmentation fault on the machine while executing. g++ version : 4.8.2 Machine : Ubuntu 14.04 #include <cstdio> #include <set> using namespace std; struct compare { bool operator() (int lhs, int rhs) {...

Compilation error with adaptable function objects in c++

c++,templates,stl
I am learning how to use standard generic algorithms in c++. In the below code example I am trying to convert strings to double with the help of a custom compose function that combines two operations (string to const char* and const char* to double) into one. I have written...

Compile error on std::list

c++,c++11,stl
Tried to compile the following code snippet on my ubuntu 12.04, using command g++ -std=c++11 te1.cc, (g++ version 4.7.3) typedef unsigned int uint; typedef std::unordered_map< uint, uint > imap; void printTop (imap &m, int n=3) { std::list<uint> l; uint tmp; int size; for (auto kv: m) { size = l.size();...

STL Push_back string in vector

c++,vector,stl
I am trying to push a string in a string vector, like below void Node::set_val(string &val) { this->val.push_back(val); } But when I try to call it as below Obj.set_val("10h;"); I get the below error, error: no matching function for call to 'Node::set_val(const char [5])' I assumed that the string in...

STL pair comparion - first elements

c++,stl
Can someone explain meaning of this paargraph The great advantage of pairs is that they have built-in operations to compare themselves. Pairs are compared first-to-second element. If the first elements are not equal, the result will be based on the comparison of the first elements only; the second elements will...

Creating custom std::streambuf

c++,file-io,stl
I am defining a custom std::streambuf class for use in file I/O. In this class, I am overloading the functions open, close, is_open, xsgetn, xsputn, overflow, underflow, and uflow. I then insert this buffer into an std::ifstream as follows (the same scenario holds for std::ofstream): std::ifstream temp; Filebuffer *buffer =...

How to find all elements in a range in STL map(set)

c++,dictionary,stl
I have a map in stl and a range [lo, hi]. What is the best way to find all elements in map which fit in this range? UDT: The question about upper_bound and low_bound is: For example I have a set or map with {1, 2, 7, 8} and my...

Pass vector of char vectors to char**

c++,vector,stl,char
Is it possible to pass a std::vector<std::vector<char>> to a function void doSomething(char** arr) e.g. to store a bunch of paths similar as with std::vector<char> vec to void func(char *str) vec.assign(64, ' '); Function call: func(vec.data());...

Reordering vector of vectors based on input vector

c++,c++11,vector,stl,idioms
In a small application, I've been using a std::vector of std::vector<std::string> to temporarily store some data (pulled from a non-SQL database) before processing it and uploading it to a SQL database. Unfortunately, the API from which I am extracting the data does not necessarily return fields in the order specified...

why is operator-> implemented by operator* in C++ STL library?

c++,stl
I read std::deque source code, I found the following implementations for _deque_iterator::operator-> and _deque_iterator::operator* reference operator* const() { return *cur; } pointer operator-> const(){ return &(operator*()); } So My question is why not just return cur pointer? Like this: pointer operator-> const(){ return cur; } ...

How to insert data into nested map in c++?

c++,stl
//I am reading data from file and storing data into structure.Here "obj" is a object of structure. Also note that my file have outer map key multiple times means when i am reading from file then some field of structure has common value and i am using that common value...

Can STL be made completely inline?

c++,stl
We are using a third-party library in our Visual Studio 2013 C++ project. This library I guess uses a different STL library than ours. We are getting some link errors. There are no compile-time errors. As I understand, STL is primarily template-based code thus requiring no linking. Looks like there...

Add more features to stack container

c++,visual-c++,stl
I am using default features(push, pop, top, empty, size) of stack container of STL. If I want to add more features like access an element from middle of stack. How could I do this? Thanks...

Template Functions Referring to Globals (Depending on Type)

c++,templates,stl
For many classes in my codebase, I need to maintain a global map allowing me to look up instances of that class. Example: // In ExampleClass.h ExampleClass *getExampleClass(std::string name); std::unordered_map<std::string, ExampleClass *> &getAllExampleClasses(); bool addExampleClass(std::string name, ExampleClass *e); // In ExampleClass.cpp std::unordered_map<std::string, ExampleClass *> exampleClasses; ExampleClass *getExampleClass(std::string name) { return...

STL Algorithm element wise multiplication WITHOUT sum [duplicate]

c++,algorithm,stl
This question already has an answer here: element-wise multiplication of two vectors in c++ 2 answers I would like to multiply two vectors (element-wise), save the result, and then take the sum. I know the function from stl algorithm std::inner_product(x.begin(), x.end(), y.begin(), 0); This doesn't save the result of...

Both set::find and std::find fail to find only some double elements in a set

c++,stl
I am developing a big code base and wanted to use set-s from the STL to store double elements. I just ran some tests and found something very weird. Here's my source code #include <iostream> #include <set> #include <numeric> #include <algorithm> int main() { double iter = 0.001; int count...

Longest substring with only 2 distinct chars in C++

c++,string,stl,set
I am trying to find the longest substring with at most 2 distinct characters. It is a brute force program which just uses all possible substrings and checks if they have 2 or more distinct chars. I use a set to keep track of the distinct chars. #include <iostream> #include...

Template C++: How to access iterator value for both std::map and std::set?

c++,templates,dictionary,stl,set
I have a specific search function. Because it's used on both std::set and std::map, it was duplicated in our code (not using template). I have to maintain those two functions, and I'd like to move them to a single function using a template (and then have only one search preocedure...

How to write a hash function for a std::vector>

c++,hash,struct,stl,unordered-set
I have a struct which has one variable, a std::vector<std::vector<bool>> that represents a grid. One of these structs is equal to another if the grids are equal, or if any rotation of the grids is equal. I'm trying to use an unordered_set to store many of these, however, after some...

Why SGI STL don't use the copy-and-swap idiom?

c++,stl,copy-and-swap
I recently read an answer on StackOverflow about What is the copy-and-swap idiom? and knew that the copy-and-swap idiom can avoiding code duplication, and providing a strong exception guarantee. However, when I looked into SGI STL deque implementation, I found that it doesn't use the idiom. I'm wondering why not,...

How does `std::less` work?

c++,c++11,stl,relational,partial-ordering
Pointer relational operators do not define a total order (§ 5.9 of the C++11 standard): If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only...

C++ Custom std::map<> key class causing memory violation

c++,templates,dictionary,stl,key
For the first time I've written a class that is supposed to be usable as a key type for std::map<>. I've overloaded copy constructor, assignment, and operator < as suggested in other questions on SO. But for some reason it crashes when I'm trying to insert using operator []. This...

Using std::list::remove_if with MyClass' function [duplicate]

c++,list,stl,stdlist
This question already has an answer here: std::remove_if using other class method 2 answers I have std::list<MyClass> *info1 I want to use (*info1).remove_if with a bool function of MyClass. As I see, everyone creating external functions or structs for remove_if. Isn't it possible to use it with bool MyClass::Condition()...

Nested Vector Iterator - Displaying n'th Vector Only

c++,vector,stl,iterator
Please bear with me if the answer to this is blindingly obvious, I'm pretty new to the STL. So what I have is a nested vector. The iterator works as expected, displaying the values stored in each vector in the nested vector sequentially. My question is, would there be any...

STL Map - Displaying what is pointed to by find() function

c++,dictionary,stl,iterator,iostream
For testing purposes, I'm running the following code through a for loop. Only the first three keys actually exist, and "Record found" is displayed as expected, along with the key, retrieved from findVertex->first. My question is, how would I be able to access the second value being pointed to? findVertex->secondseems...

“invalid operands to binary expression” when using custom struct as index of map in C++

c++,sorting,stl
The code: struct Tag { std::string left_tag, right_tag; }; When I try to use this->_tags[__tag] = true;, I got the error: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__functional_base:63:21: error: invalid operands to binary expression ('const Tag' and 'const Tag') {return __x < __y;} ~~~ ^ ~~~ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/map:1207:17: note: in instantiation of member function...

Debug error: Vector iterator not dereferencable and Vector subscript out of range [closed]

c++,vector,stl,iterator
I am trying to implement Rateless codes, but I have some issues in decoding. In the first implementation I used iterator to loop over a vector of vector and do some operation (like erase()) but I was getting this debug error: Vector iterator not dereferencable. After some googling I found...

Why does std::shared_ptr = std::unique_ptr compile, while std::shared_ptr = std::unique_ptr does not?

c++,stl,g++,c++14
I explored this topic in Coliru with the following input command: g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out The test can be found here, but I have posted the code below. I used int in my example, as it's a basic type. #include <iostream> #include <memory> struct Foo{...

For_each and pointer to member function

c++,stl
I came across a problem with the following code: #include <list> #include <algorithm> #include <string> #include <iostream> #include <functional> using namespace std; struct Person { string name; ostream& print(ostream& out) const { return out << name; } }; int main() { Person p = { "Mark" }; list<Person> l; l.push_back(p);...

How to use std::toupper in std::for_each?

c++,c++11,stl
I'm trying to convert the lowercase characters of a string into its uppercase counterpart using the std::toupper function and I'm using the std::for_each algorithm to iterate over the characters in the string. #include <iostream> #include <string> #include <algorithm> #include <locale> std::string convert_toupper(std::string *x) { return std::toupper(*x, std::locale()); } int main()...

Manage sqlite3 db not using the official sqlite3 library

c++,stl,sqlite3
I need to simply manipulate a Sqlite3 database (just read some column) and being this just a small part of my program,I don't feel to add 160k line for just few instruction. There is a way to do this STL or another library that isn't so much memory expensive? I...

Xcode - shallow copy in STL string assignment

c++,xcode,string,c++11,stl
When running the following C++ code in Xcode: std::wstring str1 = L"1111"; std::wstring str2 = str1; void* ptr1 = (void*)str1.c_str(); void* ptr2 = (void*)str2.c_str(); Result is that both pointers are equal. Is this by standard? In Visual Studio it's not the case....

Why the libc++ std::vector internally keeps three pointers instead of one pointer and two sizes?

c++,vector,stl,libc++
I'm looking at the implementation of std::vector in libc++ and I noticed that it internally keeps three pointers (one to the begin, one the end, and one to the end of the allocated memory) instead of what I'd instinctively do, i.e., one pointer to the begin and two size and...

Why do some STL algorithms provide an additional '_if' function instead of overloading? [duplicate]

c++,c++11,stl,stl-algorithm
This question already has an answer here: Why does the standard library have find and find_if? 4 answers Why do some STL algorithms provide an additional '_if' function instead of overloading it? // example: find(beg, end, val); find_if(beg, end, pred); Couldn't they just have overloaded those algorithms instead of...

Is there any way to use istreambuf_iterator to read a specific length?

c++,stl,istream-iterator
I'm writing my files like this: std::ofstream os; // declared somewhere earlier std::vector<char> vec; // declared somewhere earlier std::ostreambuf_iterator<char> oi(os); std::copy(vec.begin(), vec.end(), oi); So naturaly I was wondering if there was a similar way to read let's say 5 bytes using the std::istream_iterator or std::istreambuf_iterator, however since they don't support...

Can std::this_thread::sleep_for() have spurious wakeups?

c++,c++11,stl,sleep,thread-sleep
Note, this is not a question about std::condition_variable::wait_for(). I know that can wake spuriously. My program’s behavior suggests the answer to this question is Yes, but the STL documentation is quite clear for the condition_variable case. At least at cppreference.com, the correct answer for this_thread appears to be No. Compiler...

unary operator in std::transform

c++,algorithm,stl
Can someone help explain how does this line of code work? I don't understand how the operator worked in transform(). Thanks! typedef std::list<int> L; L l(5); typedef L::const_iterator CI; CI cb = l.begin(), ce = l.end(); typedef L::iterator I; I b = l.begin(); std::transform(cb, --ce, ++b, [] (CI::value_type n) {...

Given cbegin(), cend(), why is there no cfront(), cback(), cfind(), …?

c++,stl,c++14
So, in order to allow code such as auto vect = ...; auto it = vect.begin(), end = vect.end(); // want const_iterator, getting iterator to pick the right overload of begin() and end(), even for non-const containers, the more explicit cbegin()/cend() functions were added. Why stop there? Associative containers have...

Passing a C++ Member Function Pointer to an STL Algorithm

c++,stl,member-functions,stl-algorithm
I have a member function as follows: class XYZ{ public: float function(float x); private: float m_DensityMin; float m_DensityMax; }; Now, I'm trying to transform a std::vector<float> foo using the std::transform STL algorithm by passing the member function function, and storing the resulting values in a vector bar. If I use...

Vector Resizing in C++ (Scaling Down )

c++,vector,stl
I read from TopCoder STL Tutorials and some other standard tutorials which says, if i resize() a vector to a lower value than the original value, the last 'difference' number of elements would be deleted. But, #include <iostream> #include<vector> using namespace std; int main() { vector<int> v(20); for(int i =...

How to insert data into map where one parameter is an object?

c++,stl
I have a class Normal defined as: class Normal { bool value; float time; public: Normal(bool val,float time): value(val),time(time) {} } Also, I have declared a map variable as: map<string,Normal> myMap; Now I want to insert an data into this map. Is this way of inserting correct? Normal temp(true,45.04); myMap.insert(pair<string,Normal>("one",temp));...

How to get rid of the “.\r\n” characters appended to the error message from FormatMessageA?

c++,windows,boost,stl
I'm replacing boost::system::error_code with std::errc. The error_code supports displaying the error message in string format through error_code::message(). But I think in STL, we don't have a pre-defined way to do it. Am I right? If I'm wrong, please tell me the default way of doing it without writing my own...

Why do the const accessors of std::string return a reference?

c++,c++11,stl,language-design,stdstring
The std::string accessors (back, front, at, and operator[]) have const and non-const overloads, as below: char& x(); const char& x() const; Why does the second version return a const reference, as opposed to simply returning the char by value (as a copy)? According to the rules of thumb on how...

std::push_heap and std::pop_heap with MoveConstructible objects

c++,c++11,stl,heap,move-semantics
I want to maintain a heap where the payloads are MoveConstructible (because they hold a std::unique_ptr inside.) Although the documentation suggests that the object must be MoveAssignable and MoveConstructible, doing so throws an error both in GCC and Clang. Sample Code I don't use an std::unique_ptr yet, but just disable...

No viable conversion std::weak_ptr to std::shared_ptr for method call

c++,c++11,stl,shared-ptr,weak-ptr
I am able to convert back and forth inline. std::shared_ptr<sfg::Notebook> mNotebook = ...; std::weak_ptr<sfg::Notebook> weakNotebook(mNotebook); std::shared_ptr<sfg::Notebook> strongNotebook(weakNotebook); When I attempt to pass it to a method, I get the error: "No viable conversion between std::weak_ptr<sfg::Notebook> to std::shared_ptr<sfg::Notebook>." I am calling the method normally, and the method looks like: onNotebookLeftClick(weakNotebook); void...

Sorting Of two arrays

c++,sorting,stl
Suppose I have been given two array.For ex- Process With their Arrival Time and Finish Time. I want to sort it on the basis of finish time.On the basis of Finish Time,Arrival Time Should also be sorted. I can use bubble sort or selection sort for this purpose. But Is...

Cast between two slightly different std::map

c++,casting,stl,callback,stdmap
I have a std::map defined as follows: typedef void (SomeClass::*callback_f)(); typedef std::pair<std::string, callback_f> my_pair; typedef std::map<char,my_pair> my_map1; There are multiple of these definitions, so there is my_map1, my_map2, etc. and every one of them differs from the other for the class SomeClass, which is SomeClass, SomeClassTwo, etc. My need...

What is the equivalent of boost::upgrade_to_unique_lock in STL?

c++,multithreading,stl,boost-thread
I'm trying to replace the boost functionalities with STL functinoalities in C++11. There is a write function in my multi-thread application. First, the function verifies the data. Next, writes to it. There are two locks mentioned as mentioned below: class Data { mutable boost::mutex mut; void Data::Write() { boost::upgrade_lock<boost::shared_mutex> ulock(mut);...

What is the difference between std::function and std::mem_fn

c++,c++11,stl,function-pointers
I am having trouble figuring out the difference between the two function wrappers std::function and std::mem_fn. From the description, it seems to me that std::function does everything std::mem_fn does and more. In which instance would one use std::mem_fn over std::function?

std::reverse on MFC CArray

c++,stl,mfc
I have an array of points like this: CArray<CPoint,CPoint> points; And I need to reverse the order of the points. I've tried this method: std::reverse( &points[0], &points[0] + points.GetSize() ); And it works. Then I've tried this other method: std::reverse( &points[0], &points[points.GetUpperBound()] ); But it doesn't work: the last item...

Memory Allocation of STL-Containers as Static Members

c++,templates,stl,static-members
I have the following class used to access global registry variables. template <typename T> using RegistryMap = std::unordered_map <std::string, T *>; template <typename T> class Registry { static RegistryMap<T> registry; public: static T* get(const std::string& name) { auto it = registry.find(name); return it == registry.end() ? nullptr : it->second; }...

Peculiar behaviour while erasing an element from from std::multimap

c++,c++11,stl,multimap
I was trying to remove an element from a std::multimap while I am looping over it in a thread that manipulates it . I used erase function in the following ways When I do this //mItr is base iterator which loops over the multimap std::multimap<std::string, std::string>::iterator tmpItr = ++mItr; healthyQ.erase(mItr);...

unable to find key in unordered_map

c++,stl,tr1
Created an unordered_map with key as a shared_ptr of a class. Defined a hash function that created hash based on a data member of the class. I am not able to lookup the key. I see that hash method is called during the find operation. // key to be stored...

Passing iterator by reference gives an error: cannot convert parameter 1 from 'const data' to 'data &

c++,stl
I have a function int func(data& dt). Its need to use the list of structureslst. Its proposed that map and list has some elements (but in my example it has one element). I have to iterate through list and push each element into the func function by reference. #include <iostream>...

call const overloaded function with std::map of std::shared_ptr

c++,c++11,stl,shared-ptr
I am trying to call a const overload function void process(std::map<std::string,std::shared_ptr<const Data_Struct>>); with data I generate. Because I generate the data, I use a non-const version std::map<std::string,std::shared_ptr<Data_Struct>> my_data; When I try to call my function with process(my_data); I get the error: error C2664: 'void process(std::map<std::string,std::shared_ptr<const Data_Struct>,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>)' : cannot convert...

std::vector references being copied on .insert()

c++,stl
I was trying out this code, but something that keeps happening is that when I insert into the vector the reference isn't changing. For example on the first insert into the vector all 11 elements will be equally changed including temp_word. Is this expected behaviour? std::cout << "Searching for the...

std::enable_if sfine custom type via template parameter?

list,templates,c++11,stl,enable-if
First question, Let say that I have custom struct like this one: struct Var:{}; struct is_var_type:std::integral_constant<bool,std::is_same<Var, typename std::remove_cv<T>::type>::value > {}; After this, I want to have some custom type via template parameter sfine using std::enable_if, however I couldnt figure out. From what I could do was only following ways template<typename...

Passing a vector as argument to function

c++,function,stl
I have a function like this: void Foo(std::vector<bool> Visited, int actual element); I actually use this function for a BFS in a Graph, but it goes in an infinite loop. I suspect it always creates a copy of the Visited vector. How do I make it change the vector, which...

Populating a List Control with the sorted contents of an `std::multimap`?

c++,winapi,stl,mfc,clistctrl
As a follow-up to this question, I need a way to access my data by index. But the data needs to be sorted by timestamp, contain a filepath as a value, and be displayed in real-time as new elements are discovered. Considering that multiple files/folders could potentially contain an identical...

Can't understand linear time method for Stock span using C++ STL

c++,stl
I found out this code on geeksforgeeks and it works. But I have a few doubts.Inthe function calculateSpan(), in the following line, while (!st.empty() && price[st.top()] < price[i]).. we want to compare the value of the ith element in the array with the element on stack top,but st.top() gives the...

set_union issue while using arrays

c++,stl,set-union
I am trying to get union of 4 arrays using set_union. Here is the code I have so far: int setA[5] = {2, 4, 5, 7, 8}; int setB[7] = {1, 2, 3, 4, 5, 6, 7}; int setC[5] = {2, 5, 8, 8, 15}; int setD[6] = {1, 4,...

why sort function of STL is not working?

c++,c++11,stl
A set of numbers will be passed as input. Also the redefined relationship of the digits 0-9 in ascending order will be passed as input. Based on the redefined relationship, the set of numbers must be listed in ascending order. Sample I/O Input: 20 50 11 121 9231476058 Output: 50...

Is there a way to iterate over at most N elements using range-based for loop?

c++,c++11,stl,c++14
I would like to know if there is a nice way to iterate over at most N elements in a container using the range based for loop and/or algorithms from the standard library (that's the whole point, I know I can just use the "old" for loop with a condition)....

Initialize String in C++

c++,string,stl
Hi I have a simple c++ program. #include <iostream> #include <algorithm> using namespace std; int main() { string s = "Rotate this"; rotate(s.begin(),s.begin()+6,s.end()); cout<<s<<endl; string s1; rotate_copy(s.begin(),s.begin()+4,s.end(),s1.begin()); cout<<s1<<endl; } This program fails (Runtime Error) since s1.begin() iterator points to nothing. How can I initialize the s1 string so that it...

parsing fails when using istream iterator

c++,parsing,stl,iterator,boost-spirit
I'm using boost::spirit to parse csv input (please don't suggest an alternative, this is just testing). When I read the contents of stdin to a string and iterate over that, the parsing succeeds; however, when the contents of std::cin are read directly (through a wrapper that I wrote myself because...

Is it legal to store an STL iterator inside a union?

c++,stl,unions
Does any C++ standard guarantee that STL iterators can be stored in a union? If so, which standard? For example: union MyUnion { std::vector<int>::iterator iter; size_t size; }; The reason that I ask is that I'm porting someone else's code that stores std::vector and std::map iterators in unions, and MSVC2013...

How to insert preprocessor value in a vector?

c++,stl,c-preprocessor
#define HEADER = 5 int _tmain(int argc, _TCHAR* argv[]) { vector<int> v; v.push_back(HEADER); return 0; } why this code gives me a syntex error ? as far as i preprocessor get treated like int....

expected type-specifier error, any ideas as to what I am doing wrong?

c++,stl
I am trying to implement a DEQUE using double linked list. DEQUE.h using namespace std; template <typename T> class Node{ Node(const T& data):data(data), next(0), prev(0) {} public: Node* next; Node* prev; T data; }; template <typename T> class DEQUE { //interface }; DEQUE.cpp template <class T> void DEQUE< T >...

Why is erasing via a const_iterator allowed in C++11?

c++,c++11,stl,const,erase
As of GCC 4.9.2, it's now possible to compile C++11 code that inserts or erases container elements via a const_iterator. I can see how it makes sense for insert to accept a const_iterator, but I'm struggling to understand why it makes sense to allow erasure via a const_iterator. This issue...

c++ typedef and subclassing

c++,templates,c++11,stl
I am having a bit of trouble with a c++ class that I am trying to implement. I subclass std::vector<T> but I can't get the iterator. Here's my sample code: This line MyPairList::iterator Item = this->begin(); I can't get the iterator to my template class. How can I fix this...

Trying to improve efficiency of this search in an array

algorithm,sorting,stl
Suppose I have an input array where all objects are non-equivalent - e.g. [13,2,36]. I want the output array to be [1,0,2], since 13 is greater than 2 so "1", 2 is greater than no element so "0", 36 is greater than both 13 and 2 so "2". How do...