What is the difference between (*it).first and it->first?
Can they be used interchangeably, for example in the below code?
Also, would really help if someone has a good resource where I can learn about iterators. Specifically about this line vector<pair<int, int>>:: iterator it; Can someone explain it?
vector<pair<int, int>> adj[10005]; //For storing vertices, weights of a directed graph as an adjacency list
for(int i = 1; i <= V; i++)//GOING THROUGH EACH VERTEX
{
vector<pair<int, int>>:: iterator it;
for(it = adj[i].begin(); it != adj[i].end(); it++)
{
cout<<it->first<<" ";
cout<<it->second<<"\n";
}
}
Iterators are designed so that they are used like pointers would. For pointers, p->expr is a "shorthand" for (*p).expr, so iterators are designed so that it->expr does the same thing as (*it).expr. If all you want is to know how to use them, then know that it->expr and (*it).expr are equivalent.
If you want to know a little more of what's under the hood then read on.
The standard just defines some restrictions and requirements for how iterators are implemented, but doesn't define the actual type. So for random access iterators (e.g. std::vector<int>::iterator) the iterator can be an alias for a pointer. Some implementations, especially in debug mode define an actual class for the iterator for extra safety checks. And for non-random access iterators the only option is to define an iterator class.
If it's a class then:
(*it) will call Iterator::operator*() which should return a reference to the pointed object. And then .expr is just a member access operator for that pointed type.
it->expr will call Iterator::operator->() which should return a pointer to the pointed object and then access the expr member.
Operators in C and C++
operator overloading
Related
ALL,
I have a function with the following signature:
void foo(const std::vector<Bar *> &myvec);
Inside this function I need to loop thru the members of the vector and perform some operations.
So, I tried this:
for( std::vector<Bar *>::const_iterator it = myvec.begin(); it < myvec.end(); ++it )
{
// modify properties of Bar * pointer
(*it)->SetSomeValue( baz );
}
however this code asserts since the iterator is constant.
Now obviously the vector is constant, which means that the function shouldn't be modifying myvec.
What's the best solution here?
Can I use const_cast here to remove constness? It would be kind of hack-ish, but if it works.
But I feel there must be a better solution.
TIA!!
You should use the myvec.cbegin() method instead of myvec.begin(), to ensure that you are not modifying the object the iterator points to.
Of course, for myvec.end(), use myvec.cend() accordingly.
The iterator itself doesn't need to be a const_iterator, in the contrary, you want to modify the objects it gives you - set_...() sounds like a non-const activity.
As I know, we can use ostream_iterator in c++11 to print a container.
For example,
std::vector<int> myvector;
for (int i=1; i<10; ++i) myvector.push_back(i*10);
std::copy ( myvector.begin(), myvector.end(), std::ostream_iterator<int>{std::cout, " "} );
I don't know when and why we use the code above, instead of traditional way, such as:
for(const auto & i : myvector) std::cout<<i<<" ";
In my opinion, the traditional way is faster because there is no copy, am I right?
std::ostream_iterator is a single-pass OutputIterator, so it can be used in any algorithms which accept such iterator. The use of it for outputing vector of int-s is just for presenting its capabilities.
In my opinion, the traditional way is faster because there is no copy, am I right?
You may find here: http://en.cppreference.com/w/cpp/algorithm/copy that copy is implemented quite similarly to your for-auto loop. It is also specialized for various types to work as efficient as possible. On the other hand writing to std::ostream_iterator is done by assignment to it, and you can read here : http://en.cppreference.com/w/cpp/iterator/ostream_iterator/operator%3D that it resolves to *out_stream << value; operation (if delimiter is ignored).
You may also find that this iterator suffers from the problem of extra trailing delimiter which is inserted at the end. To fix this there will be (possibly in C++17) a new is a single-pass OutputIterator std::experimental::ostream_joiner
A short (and maybe silly) example where using iterator is usefull. The point is that you can direct your data to any sink - a file, console output, memory buffer. Whatever output you choose, MyData::serialize does not needs changes, you only need to provide OutputIterator.
struct MyData {
std::vector<int> data = {1,2,3,4};
template<typename T>
void serialize(T iterator) {
std::copy(data.begin(), data.end(), iterator);
}
};
int main()
{
MyData data;
// Output to stream
data.serialize(std::ostream_iterator<int>(std::cout, ","));
// Output to memory
std::vector<int> copy;
data.serialize(std::back_inserter(copy));
// Other uses with different iterator adaptors:
// std::front_insert_iterator
// other, maybe custom ones
}
The difference is polymorphism vs. hardcoded stream.
std::ostream_iterator builds itself from any class which inherits from std::ostream, so in runtime, you can change or wire the iterator to write to difference output stream type based on the context on which the functions runs.
the second snippet uses a hardcoded std::cout which cannot change in runtime.
In C#, you can define a custom enumeration very trivially, eg:
public IEnumerable<Foo> GetNestedFoos()
{
foreach (var child in _SomeCollection)
{
foreach (var foo in child.FooCollection)
{
yield return foo;
}
foreach (var bar in child.BarCollection)
{
foreach (var foo in bar.MoreFoos)
{
yield return foo;
}
}
}
foreach (var baz in _SomeOtherCollection)
{
foreach (var foo in baz.GetNestedFoos())
{
yield return foo;
}
}
}
(This can be simplified using LINQ and better encapsulation but that's not the point of the question.)
In C++11, you can do similar enumerations but AFAIK it requires a visitor pattern instead:
template<typename Action>
void VisitAllFoos(const Action& action)
{
for (auto& child : m_SomeCollection)
{
for (auto& foo : child.FooCollection)
{
action(foo);
}
for (auto& bar : child.BarCollection)
{
for (auto& foo : bar.MoreFoos)
{
action(foo);
}
}
}
for (auto& baz : m_SomeOtherCollection)
{
baz.VisitAllFoos(action);
}
}
Is there a way to do something more like the first, where the function returns a range that can be iterated externally rather than calling a visitor internally?
(And I don't mean by constructing a std::vector<Foo> and returning it -- it should be an in-place enumeration.)
I am aware of the Boost.Range library, which I suspect would be involved in the solution, but I'm not particularly familiar with it.
I'm also aware that it's possible to define custom iterators to do this sort of thing (which I also suspect might be involved in the answer) but I'm looking for something that's easy to write, ideally no more complicated than the examples shown here, and composable (like with _SomeOtherCollection).
I would prefer something that does not require the caller to use lambdas or other functors (since that just makes it a visitor again), although I don't mind using lambdas internally if needed (but would still prefer to avoid them there too).
If I'm understanding your question correctly, you want to perform some action over all elements of a collection.
C++ has an extensive set of iterator operations, defined in the iterator header. Most collection structures, including the std::vector that you reference, have .begin and .end methods which take no arguments and return iterators to the beginning and the end of the structure. These iterators have some operations that can be performed on them manually, but their primary use comes in the form of the algorithm header, which defines several very useful iteration functions.
In your specific case, I believe you want the for_each function, which takes a range (as a beginning to end iterator) and a function to apply. So if you had a function (or function object) called action and you wanted to apply it to a vector called data, the following code would be correct (assuming all necessary headers are included appropriately):
std::for_each(data.begin(), data.end(), action);
Note that for_each is just one of many functions provided by the algorithm header. It also provides functions to search a collection, copy a set of data, sort a list, find a minimum/maximum, and much more, all generalized to work over any structure that has an iterator. And if even these aren't enough, you can write your own by reading up on the operations supported on iterators. Simply define a template function that takes iterators of varying types and document what kind of iterator you want.
template <typename BidirectionalIterator>
void function(BidirectionalIterator begin, BidirectionalIterator end) {
// Do something
}
One final note is that all of the operations mentioned so far also operate correctly on arrays, provided you know the size. Instead of writing .begin and .end, you write + 0 and + n, where n is the size of the array. The trivial zero addition is often necessary in order to decay the type of the array into a pointer to make it a valid iterator, but array pointers are indeed random access iterators just like any other container iterator.
What you can do is writing your own adapter function and call it with different ranges of elements of the same type.
This is a non tested solution, that will probably needs some tweaking to make it compile,but it will give you an idea. It uses variadic templates to move from a collection to the next one.
template<typename Iterator, Args...>
visitAllFoos(std::pair<Iterator, Iterator> collection, Args&&... args)
{
std::for_each(collection.first, collection.second, {}(){ // apply action });
return visitAllFoos(std::forward<Args>(args)...);
}
//you can call it with a sequence of begin/end iterators
visitAllFoos(std::make_pair(c1.begin(), c1,end()), std::make_pair(c2.begin(), c2,end()))
I believe, what you're trying to do can be done with Boost.Range, in particular with join and any_range (the latter would be needed if you want to hide the types of the containers and remove joined_range from the interface).
However, the resulting solution would not be very practical both in complexity and performance - mostly because of the nested joined_ranges and type erasure overhead incurred by any_range. Personally, I would just construct std::vector<Foo*> or use visitation.
You can do this with the help of boost::asio::coroutine; see examples at https://pubby8.wordpress.com/2014/03/16/multi-step-iterators-using-coroutines/ and http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/overview/core/coroutine.html.
Consider a class D derived from a class B, and a sb instance of std::shared_ptr<B>. Once I have verified that dynamic_cast<D*>(sb.get()) is possible, I want to create a proper std::shared_ptr<D> from sb. In other words, I'd like to implement a kind of dynami_cast<> between shared_ptr's. How can I do this in a clean way? A possible solution would be to make B derive from std::enable_shared_from_this and to use shared_from_this() from the (casted) pointer to D. But this would require a change in the definition of type B. Are there better ideas? Is there anything in boost?
Are you aware of std::dynamic_pointer_cast?
http://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast
As other answers pointed out, the standard library already provides what you want, but for completeness, implementing it is easy:
template<typename To, typename From>
std::shared_ptr<To>
dynamic_pointer_cast(const std::shared_ptr<From>& from)
{
return std::shared_ptr<To>(from, dynamic_cast<To*>(from.get()));
}
This uses the aliasing constructor to create a new shared_ptr of a different type that shares ownership with from, so they share the same reference count even though they own different pointers (in this case the pointers they own are different types but point to the same object, but that doesn't have to be true.)
This isn't quite right, because if the cast fails (returning a null pointer) you get a shared_ptr that stores a null pointer, but shares ownership with a non-null pointer. To handle that we need a small tweak:
template<typename To, typename From>
std::shared_ptr<To>
dynamic_pointer_cast(const std::shared_ptr<From>& from)
{
if (auto p = dynamic_cast<To*>(from.get()))
return std::shared_ptr<To>(from, p);
return {};
}
Now we return an empty shared_ptr<To> if the cast fails, which is a better match to the behaviour of dynamic_cast<To*>.
Look here: dynamic_pointer_cast
We have people who run code for simulations, testing etc. on some supercomputers that we have. What would be nice is, if as part of a build process we can check that not only that the code compiles but that the ouput matches some pattern which will indicate we are getting meaningful results.
i.e. the researcher may know that the value of x must be within some bounds. If not, then a logical error has been made in the code (assuming it compiles and their is no compile time error).
Are there any pre-written packages for this kind of thing. The code is written in FORTRAN, C, C++ etc.
Any specific or general advice would be appreciated.
I expect most unit testing frameworks could do this; supply a toy test data set and see that the answer is sane in various different ways.
A good way to ensure that the resulting value of any computation (whether final or intermediate) meets certain constraints, is to use an object oriented programming language like C++, and define data-types that internally enforce the conditions that you are checking for. You can then use those data-types as the return value of any computation to ensure that said conditions are met for the value returned.
Let's look at a simple example. Assume that you have a member function inside of an Airplane class as a part of a flight control system that estimates the mass of the airplane instance as a function of the number passengers and the amount of fuel that plane has at that moment. One way to declare the Airplane class and an airplaneMass() member function is the following:
class Airplane {
public:
...
int airplaneMass() const; // note the plain int return type
...
private:
...
};
However, a better way to implement the above, would be to define a type AirplaneMass that can be used as the function's return type instead of int. AirplaneMass can internally ensure (in it's constructor and any overloaded operators) that the value it encapsulates meets certain constraints. An example implementation of the AirplaneMass datatype could be the following:
class AirplaneMass {
public:
// AirplaneMass constructor
AirplaneMass(int m) {
if (m < MIN || m > MAX) {
// throw exception or log constraint violation
}
// if the value of m meets the constraints,
// assign it to the internal value.
mass_ = m;
}
...
/* range checking should also be done in the implementation
of overloaded operators. For instance, you may want to
make sure that the resultant of the ++ operation for
any instance of AirplaneMass also lies within the
specified constraints. */
private:
int mass_;
};
Thereafter, you can redeclare class Airplane and its airplaneMass() member function as follows:
class Airplane {
public:
...
AirplaneMass airplaneMass() const;
// note the more specific AirplaneMass return type
...
private:
...
};
The above will ensure that the value returned by airplaneMass() is between MIN and MAX. Otherwise, an exception will be thrown, or the error condition will be logged.
I had to do that for conversions this month. I don't know if that might help you, but it appeared quite simple a solution to me.
First, I defined a tolerance level. (Java-ish example code...)
private static final double TOLERANCE = 0.000000000001D;
Then I defined a new "areEqual" method which checks if the difference between both values is lower than the tolerance level or not.
private static boolean areEqual(double a, double b) {
return (abs(a - b) < TOLERANCE);
}
If I get a false somewhere, it means the check has probably failed. I can adjust the tolerance to see if it's just a precision problem or really a bad result. Works quite well in my situation.