Search Results

Search found 173 results on 7 pages for 'iterators'.

Page 5/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • Why does string::find return size_type and not an iterator?

    - by dehmann
    In C++, why does string::find return size_type and not an iterator? It would make sense because functions like string::replace or string::insert take iterators as input, so you could find some character and immediately pass the returned iterator to replace, etc. Also, std::find returns an iterator -- why is std::string::find different?

    Read the article

  • C#: LINQ vs foreach - Round 1.

    - by James Michael Hare
    So I was reading Peter Kellner's blog entry on Resharper 5.0 and its LINQ refactoring and thought that was very cool.  But that raised a point I had always been curious about in my head -- which is a better choice: manual foreach loops or LINQ?    The answer is not really clear-cut.  There are two sides to any code cost arguments: performance and maintainability.  The first of these is obvious and quantifiable.  Given any two pieces of code that perform the same function, you can run them side-by-side and see which piece of code performs better.   Unfortunately, this is not always a good measure.  Well written assembly language outperforms well written C++ code, but you lose a lot in maintainability which creates a big techncial debt load that is hard to offset as the application ages.  In contrast, higher level constructs make the code more brief and easier to understand, hence reducing technical cost.   Now, obviously in this case we're not talking two separate languages, we're comparing doing something manually in the language versus using a higher-order set of IEnumerable extensions that are in the System.Linq library.   Well, before we discuss any further, let's look at some sample code and the numbers.  First, let's take a look at the for loop and the LINQ expression.  This is just a simple find comparison:       // find implemented via LINQ     public static bool FindViaLinq(IEnumerable<int> list, int target)     {         return list.Any(item => item == target);     }         // find implemented via standard iteration     public static bool FindViaIteration(IEnumerable<int> list, int target)     {         foreach (var i in list)         {             if (i == target)             {                 return true;             }         }           return false;     }   Okay, looking at this from a maintainability point of view, the Linq expression is definitely more concise (8 lines down to 1) and is very readable in intention.  You don't have to actually analyze the behavior of the loop to determine what it's doing.   So let's take a look at performance metrics from 100,000 iterations of these methods on a List<int> of varying sizes filled with random data.  For this test, we fill a target array with 100,000 random integers and then run the exact same pseudo-random targets through both searches.                       List<T> On 100,000 Iterations     Method      Size     Total (ms)  Per Iteration (ms)  % Slower     Any         10       26          0.00046             30.00%     Iteration   10       20          0.00023             -     Any         100      116         0.00201             18.37%     Iteration   100      98          0.00118             -     Any         1000     1058        0.01853             16.78%     Iteration   1000     906         0.01155             -     Any         10,000   10,383      0.18189             17.41%     Iteration   10,000   8843        0.11362             -     Any         100,000  104,004     1.8297              18.27%     Iteration   100,000  87,941      1.13163             -   The LINQ expression is running about 17% slower for average size collections and worse for smaller collections.  Presumably, this is due to the overhead of the state machine used to track the iterators for the yield returns in the LINQ expressions, which seems about right in a tight loop such as this.   So what about other LINQ expressions?  After all, Any() is one of the more trivial ones.  I decided to try the TakeWhile() algorithm using a Count() to get the position stopped like the sample Pete was using in his blog that Resharper refactored for him into LINQ:       // Linq form     public static int GetTargetPosition1(IEnumerable<int> list, int target)     {         return list.TakeWhile(item => item != target).Count();     }       // traditionally iterative form     public static int GetTargetPosition2(IEnumerable<int> list, int target)     {         int count = 0;           foreach (var i in list)         {             if(i == target)             {                 break;             }               ++count;         }           return count;     }   Once again, the LINQ expression is much shorter, easier to read, and should be easier to maintain over time, reducing the cost of technical debt.  So I ran these through the same test data:                       List<T> On 100,000 Iterations     Method      Size     Total (ms)  Per Iteration (ms)  % Slower     TakeWhile   10       41          0.00041             128%     Iteration   10       18          0.00018             -     TakeWhile   100      171         0.00171             88%     Iteration   100      91          0.00091             -     TakeWhile   1000     1604        0.01604             94%     Iteration   1000     825         0.00825             -     TakeWhile   10,000   15765       0.15765             92%     Iteration   10,000   8204        0.08204             -     TakeWhile   100,000  156950      1.5695              92%     Iteration   100,000  81635       0.81635             -     Wow!  I expected some overhead due to the state machines iterators produce, but 90% slower?  That seems a little heavy to me.  So then I thought, well, what if TakeWhile() is not the right tool for the job?  The problem is TakeWhile returns each item for processing using yield return, whereas our for-loop really doesn't care about the item beyond using it as a stop condition to evaluate. So what if that back and forth with the iterator state machine is the problem?  Well, we can quickly create an (albeit ugly) lambda that uses the Any() along with a count in a closure (if a LINQ guru knows a better way PLEASE let me know!), after all , this is more consistent with what we're trying to do, we're trying to find the first occurence of an item and halt once we find it, we just happen to be counting on the way.  This mostly matches Any().       // a new method that uses linq but evaluates the count in a closure.     public static int TakeWhileViaLinq2(IEnumerable<int> list, int target)     {         int count = 0;         list.Any(item =>             {                 if(item == target)                 {                     return true;                 }                   ++count;                 return false;             });         return count;     }     Now how does this one compare?                         List<T> On 100,000 Iterations     Method         Size     Total (ms)  Per Iteration (ms)  % Slower     TakeWhile      10       41          0.00041             128%     Any w/Closure  10       23          0.00023             28%     Iteration      10       18          0.00018             -     TakeWhile      100      171         0.00171             88%     Any w/Closure  100      116         0.00116             27%     Iteration      100      91          0.00091             -     TakeWhile      1000     1604        0.01604             94%     Any w/Closure  1000     1101        0.01101             33%     Iteration      1000     825         0.00825             -     TakeWhile      10,000   15765       0.15765             92%     Any w/Closure  10,000   10802       0.10802             32%     Iteration      10,000   8204        0.08204             -     TakeWhile      100,000  156950      1.5695              92%     Any w/Closure  100,000  108378      1.08378             33%     Iteration      100,000  81635       0.81635             -     Much better!  It seems that the overhead of TakeAny() returning each item and updating the state in the state machine is drastically reduced by using Any() since Any() iterates forward until it finds the value we're looking for -- for the task we're attempting to do.   So the lesson there is, make sure when you use a LINQ expression you're choosing the best expression for the job, because if you're doing more work than you really need, you'll have a slower algorithm.  But this is true of any choice of algorithm or collection in general.     Even with the Any() with the count in the closure it is still about 30% slower, but let's consider that angle carefully.  For a list of 100,000 items, it was the difference between 1.01 ms and 0.82 ms roughly in a List<T>.  That's really not that bad at all in the grand scheme of things.  Even running at 90% slower with TakeWhile(), for the vast majority of my projects, an extra millisecond to save potential errors in the long term and improve maintainability is a small price to pay.  And if your typical list is 1000 items or less we're talking only microseconds worth of difference.   It's like they say: 90% of your performance bottlenecks are in 2% of your code, so over-optimizing almost never pays off.  So personally, I'll take the LINQ expression wherever I can because they will be easier to read and maintain (thus reducing technical debt) and I can rely on Microsoft's development to have coded and unit tested those algorithm fully for me instead of relying on a developer to code the loop logic correctly.   If something's 90% slower, yes, it's worth keeping in mind, but it's really not until you start get magnitudes-of-order slower (10x, 100x, 1000x) that alarm bells should really go off.  And if I ever do need that last millisecond of performance?  Well then I'll optimize JUST THAT problem spot.  To me it's worth it for the readability, speed-to-market, and maintainability.

    Read the article

  • What did programmers do before variable scope, where everything is global?

    - by hydroparadise
    So, I am having to deal with seemingly archiac language (called PowerOn) where I have a main method, a few datatypes to define variables with, and has the ability to have sub-procedures (essentially void methods) that does not return a type nor accepts any arguements. The problem here is that EVERYTHING is global. I've read of these type of languages, but most books take the aproach "Ok, we use to use a horse and cariage, but now, here's a car so let's learn how to work on THAT!" We will NEVER relive those days". I have to admit, the mind is struggling to think outside of scope and extent. Well here I am. I am trying to figure out how to best manage nothing but global variables across several open methods. Yep, even iterators for for loops have to be defined globaly, which I find myself recycling in different parts of my code. My Question: for those that have this type experience, how did programmers deal with a large amount of variables in a global playing field? I have feeling it just became a mental juggling trick, but I would be interested to know if there were any known aproaches.

    Read the article

  • C# iterator for async file copy

    - by uno
    Been running in circles to find the best solution for my client. We have a server that images are uploaded via ftp. I want to write an application that scans this server at frequent intervals and if it finds files it copies them to another,processing server. So if during a time cycle, my app finds that there are 100 files, i want to start copying as many files as i can across to the processing server i figured delegates would be the way to go but now i come across iterators...what do the experts say?

    Read the article

  • How to write Tetris in Scala? (code review)

    - by eed3si9n
    Today's the 25th birthday of Tetris. I believe writing Tetris clone is one of the best ways to familiarize oneself to a new language or a platform. It's not completely trivial and it lends itself well to learning language specific constructs like iterators and closures. I've been hearing about Scala, and finally decided to read some docs and write a Tetris clone. So, this is my first Scala code. I did try to use functional constructs, but am sure there are lots of things I can improve to do it more Scala way. Please give me suggestions using comment. Also other submissions of Tetris clone in Scala are welcome too. I'm aware that the actual question itself is somewhat subjective, but I think this is of some value since others can use this as example (or anti-example) code. Edit: Let me rephrase the question. What can I do to make the code more Scala-ish?

    Read the article

  • Polynomial division overloading operator (solved)

    - by Vlad
    Ok. here's the operations i successfully code so far thank's to your help: Adittion: polinom operator+(const polinom& P) const { polinom Result; constIter i = poly.begin(), j = P.poly.begin(); while (i != poly.end() && j != P.poly.end()) { //logic while both iterators are valid if (i->pow > j->pow) { //if the current term's degree of the first polynomial is bigger Result.insert(i->coef, i->pow); i++; } else if (j->pow > i->pow) { // if the other polynomial's term degree is bigger Result.insert(j->coef, j->pow); j++; } else { // if both are equal Result.insert(i->coef + j->coef, i->pow); i++; j++; } } //handle the remaining items in each list //note: at least one will be equal to end(), but that loop will simply be skipped while (i != poly.end()) { Result.insert(i->coef, i->pow); ++i; } while (j != P.poly.end()) { Result.insert(j->coef, j->pow); ++j; } return Result; } Subtraction: polinom operator-(const polinom& P) const //fixed prototype re. const-correctness { polinom Result; constIter i = poly.begin(), j = P.poly.begin(); while (i != poly.end() && j != P.poly.end()) { //logic while both iterators are valid if (i->pow > j->pow) { //if the current term's degree of the first polynomial is bigger Result.insert(-(i->coef), i->pow); i++; } else if (j->pow > i->pow) { // if the other polynomial's term degree is bigger Result.insert(-(j->coef), j->pow); j++; } else { // if both are equal Result.insert(i->coef - j->coef, i->pow); i++; j++; } } //handle the remaining items in each list //note: at least one will be equal to end(), but that loop will simply be skipped while (i != poly.end()) { Result.insert(i->coef, i->pow); ++i; } while (j != P.poly.end()) { Result.insert(j->coef, j->pow); ++j; } return Result; } Multiplication: polinom operator*(const polinom& P) const { polinom Result; constIter i, j, lastItem = Result.poly.end(); Iter it1, it2, first, last; int nr_matches; for (i = poly.begin() ; i != poly.end(); i++) { for (j = P.poly.begin(); j != P.poly.end(); j++) Result.insert(i->coef * j->coef, i->pow + j->pow); } Result.poly.sort(SortDescending()); lastItem--; while (true) { nr_matches = 0; for (it1 = Result.poly.begin(); it1 != lastItem; it1++) { first = it1; last = it1; first++; for (it2 = first; it2 != Result.poly.end(); it2++) { if (it2->pow == it1->pow) { it1->coef += it2->coef; nr_matches++; } } nr_matches++; do { last++; nr_matches--; } while (nr_matches != 0); Result.poly.erase(first, last); } if (nr_matches == 0) break; } return Result; } Division(Edited): polinom operator/(const polinom& P) const { polinom Result, temp2; polinom temp = *this; Iter i = temp.poly.begin(); constIter j = P.poly.begin(); int resultSize = 0; if (temp.poly.size() < 2) { if (i->pow >= j->pow) { Result.insert(i->coef / j->coef, i->pow - j->pow); temp = temp - Result * P; } else { Result.insert(0, 0); } } else { while (true) { if (i->pow >= j->pow) { Result.insert(i->coef / j->coef, i->pow - j->pow); if (Result.poly.size() < 2) temp2 = Result; else { temp2 = Result; resultSize = Result.poly.size(); for (int k = 1 ; k != resultSize; k++) temp2.poly.pop_front(); } temp = temp - temp2 * P; } else break; } } return Result; } }; The first three are working correctly but division doesn't as it seems the program is in a infinite loop. Final Update After listening to Dave, I finally made it by overloading both / and & to return the quotient and the remainder so thanks a lot everyone for your help and especially you Dave for your great idea! P.S. If anyone wants for me to post these 2 overloaded operator please ask it by commenting on my post (and maybe give a vote up for everyone involved).

    Read the article

  • How to CompareTo two Object without known about their real type

    - by Kamil
    I have to implement a one linked list but it should put object in appropriate position. Everything was OK when I use it in conjunction with specific class, but when I tried make it universal and argument of method insert was Object some problem appeared. When I want to input Object in right position I should use CompareTo method, but there isn't method in Object class! The problem is how to compare two object elements without known about their real types. Maybe I should use generic class type? But what about CompareTo? Or maybe combine with Element class and place CompareTo there? I suppose it is feasible. :) public void insert(Object o) { Element el = new Element(o); // initializing and setting iterators while(!it.isDone() && ((it.current().getValue())).CompareTo(o)<0) // it.current() returns Element of List { //move interators } //... }

    Read the article

  • Polynomial division overloading operator

    - by Vlad
    Ok. here's the operations i successfully code so far thank's to your help: Adittion: polinom operator+(const polinom& P) const { polinom Result; constIter i = poly.begin(), j = P.poly.begin(); while (i != poly.end() && j != P.poly.end()) { //logic while both iterators are valid if (i->pow > j->pow) { //if the current term's degree of the first polynomial is bigger Result.insert(i->coef, i->pow); i++; } else if (j->pow > i->pow) { // if the other polynomial's term degree is bigger Result.insert(j->coef, j->pow); j++; } else { // if both are equal Result.insert(i->coef + j->coef, i->pow); i++; j++; } } //handle the remaining items in each list //note: at least one will be equal to end(), but that loop will simply be skipped while (i != poly.end()) { Result.insert(i->coef, i->pow); ++i; } while (j != P.poly.end()) { Result.insert(j->coef, j->pow); ++j; } return Result; } Subtraction: polinom operator-(const polinom& P) const //fixed prototype re. const-correctness { polinom Result; constIter i = poly.begin(), j = P.poly.begin(); while (i != poly.end() && j != P.poly.end()) { //logic while both iterators are valid if (i->pow > j->pow) { //if the current term's degree of the first polynomial is bigger Result.insert(-(i->coef), i->pow); i++; } else if (j->pow > i->pow) { // if the other polynomial's term degree is bigger Result.insert(-(j->coef), j->pow); j++; } else { // if both are equal Result.insert(i->coef - j->coef, i->pow); i++; j++; } } //handle the remaining items in each list //note: at least one will be equal to end(), but that loop will simply be skipped while (i != poly.end()) { Result.insert(i->coef, i->pow); ++i; } while (j != P.poly.end()) { Result.insert(j->coef, j->pow); ++j; } return Result; } Multiplication: polinom operator*(const polinom& P) const { polinom Result; constIter i, j, lastItem = Result.poly.end(); Iter it1, it2, first, last; int nr_matches; for (i = poly.begin() ; i != poly.end(); i++) { for (j = P.poly.begin(); j != P.poly.end(); j++) Result.insert(i->coef * j->coef, i->pow + j->pow); } Result.poly.sort(SortDescending()); lastItem--; while (true) { nr_matches = 0; for (it1 = Result.poly.begin(); it1 != lastItem; it1++) { first = it1; last = it1; first++; for (it2 = first; it2 != Result.poly.end(); it2++) { if (it2->pow == it1->pow) { it1->coef += it2->coef; nr_matches++; } } nr_matches++; do { last++; nr_matches--; } while (nr_matches != 0); Result.poly.erase(first, last); } if (nr_matches == 0) break; } return Result; } Division(Edited): polinom operator/(const polinom& P) { polinom Result, temp; Iter i = poly.begin(); constIter j = P.poly.begin(); if (poly.size() < 2) { if (i->pow >= j->pow) { Result.insert(i->coef, i->pow - j->pow); *this = *this - Result; } } else { while (true) { if (i->pow >= j->pow) { Result.insert(i->coef, i->pow - j->pow); temp = Result * P; *this = *this - temp; } else break; } } return Result; } The first three are working correctly but division doesn't as it seems the program is in a infinite loop. Update Because no one seems to understand how i thought the algorithm, i'll explain: If the dividend contains only one term, we simply insert the quotient in Result, then we multiply it with the divisor ans subtract it from the first polynomial which stores the remainder. If the polynomial we do this until the second polynomial( P in this case) becomes bigger. I think this algorithm is called long division, isn't it? So based on these, can anyone help me with overloading the / operator correctly for my class? Thanks!

    Read the article

  • Java List use through use of JSTL <c:forEach>

    - by Mark Lewis
    Hello If I have a JSF backing bean return an object of type ArrayList, I should be able to use to iterate over the elements in the list. Each element contains a map and although the question of how to access the map content through JSTL has been answered here, if I pass an array of such maps, I can't find how to iterate over them and still access the map content using JSTL. There's documentation which refers to simple iterators but not to those whose items are themselves maps. BalusC, I'm not trying to force the issue, just that I've been looking at this all day, and still cannot seem to be able to output the contents of my data structure through jsp (only on the console). This as a separate question still has merit. If anyone can give me a simple example of how a java List is iterated over in JSP I'd be massively appreciative. Mark

    Read the article

  • Java .doc generation

    - by bozo
    Hi, anyone knows an easy method to generate mail merge .doc file from Java? So, I want to create a Word (95/97) document in Word, put some simple placeholders in it (only single value, no iterators and other advanced tags) like the ones used with mailmerge option, and then at runtime replace those placeholders with values from Java. One option is to use Jasperreports, but this would require that I create exact replica of non-trivial Word document in Jasper format, which is not easy and is hard to change later. Is there some method of filling placeholders in Word from Java, which does not require low-level document alteration with positioning and others low-level .doc tags from code, but something like this: docPreparer.fillPlaceholder('placeholder1', 'my real value from runtime'); Some CRMs do this via ActiveX control for internet explorer, and it works great (they use Word's mailmerge) but I need an all-Java solution. Ideas? Thanks, Bozo

    Read the article

  • Changing a Container while using Visitor

    - by Florian
    Hi everyone, I implemented the Visitor pattern in C++ using a STL-like iterator for storing the Visitor's current position in the container. Now I would like to change the container while I iterate over it, and I'm especially interested in deleting items from the container, even the one I'm currently visiting. Now obviously this will invalidate the Visitors internal iterator, because it was pointing to exactly this item. Currently, I store a list of all iterators in the container and update them, as soon as anything is added to or removed from the list. So in a way this is similar to the Observer pattern applied to the iterator (as Observer) and the list (as Observable). Alternatively I considered having the visitor() methods return some hint to the Visitor about what happend to the current item and how to proceed iterating, but that doesn't sound like such a good idea either, because the visit() implementation shouldn't really care about finding the next item. So, my question is: What's the best way to keep a visitor working, even when items are added to the container or removed from it. Regards, Florian

    Read the article

  • C++ Template Classes Circular Dependency Problem

    - by TomWij
    We have two classes: template<typename T, typename Size, typename Stack, typename Sparse> class Matrix and template<typename T, typename Size> class Iterator Matrix should be able to return begin and end iterators and Iterator will keep a referrence to the Matrix to access the elements via it's interface. We don't want Iterator to depend on the internal storage of the Matrix to prevent coupling. How can we solve this cyclic dependency problem? (The internal Storage class has the same template parameters as the Matrix class and the same access procedures as the Matrix itself)

    Read the article

  • C#: How to remove items from the collection of a IDictionary<E, ICollection<T>> with LINQ?

    - by Rosarch
    Here is what I am trying to do: private readonly IDictionary<float, ICollection<IGameObjectController>> layers; foreach (ICollection<IGameObjectController> layerSet in layers.Values) { foreach (IGameObjectController controller in layerSet) { if (controller.Model.DefinedInVariant) { layerSet.Remove(controller); } } } Of course, this doesn't work, because it will cause a concurrent modification exception. (Is there an equivalent of Java's safe removal operation on some iterators?) How can I do this correctly, or with LINQ?

    Read the article

  • How can I eliminate an element in a vector if a condition is met

    - by michael
    Hi, I have a vector of Rect: vector<Rect> myRecVec; I would like to remove the ones which are overlapping in the vector: So I have 2 nested loop like this: vector<Rect>::iterator iter1 = myRecVec.begin(); vector<Rect>::iterator iter2 = myRecVec.begin(); while( iter1 != myRecVec.end() ) { Rectangle r1 = *iter1; while( iter2 != myRecVec.end() ) { Rectangle r2 = *iter1; if (r1 != r2) { if (r1.intersects(r2)) { // remove r2 from myRectVec } } } } My question is how can I remove r2 from the myRectVect without screwing up both my iterators? Since I am iterating a vector and modifying the vector at the same time? I have thought about putting r2 in a temp rectVect and then remove them from the rectVect later (after the iteration). But how can I skip the ones in this temp rectVect during iteration?

    Read the article

  • how to get the type of a deferred template parameter

    - by smerlin
    Is there a way to get the defered type of a class template parameter ? template <class TPtr> struct foo { typedef TPtr ptr_type; typedef ??? element_type; /* shall be the type of a deferred TPtr*/ }; so foo<const char*>::element_type results in const char, and foo<std::vector<int>::iterator_type>::element_type results in int. i am aware of that i can use the value_type typedef for c++ iterators (like std::vector<int>::iterator_type::value_type), but raw pointers havent got a value_type typedef, so i am out of luck there.

    Read the article

  • C++ boost or STL `y += f(x)` type algorithm

    - by aaa
    hello. I know I can do this y[i] += f(x[i]) using transform with two input iterators. however it seems somewhat counterintuitive and more complicated than for loop. Is there a more natural way to do so using existing algorithm in boost or Stl. I could not find clean equivalent. here is transform (y = y + a*x): using boost::lambda; transform(y.begin(), y.end(), x.begin(), y.begin(), (_1 + scale*_2); // I thought something may exist: transform2(x.begin(), x.end(), y.begin(), (_2 + scale*_1); // it does not, so no biggie. I will write wrapper Thanks

    Read the article

  • C++ Urban Myths

    - by Neil Butterworth
    I'm starting to write an article on what I'm calling "C++ Urban Myths" - that is, ideas and conceptions about C++ that are common but have no actual roots in reality. Some that I've come up with so far are: TR1 is part of standard C++ TR1 (technical Report #1) proposed a whole bunch of changes to C++. Unfortunately, it was never accepted. It is faster to use iterators to access a vector than operator[] Or vice versa. All tests I've carried out indicate the two are nearly identical in performance. The C++ Standard contains something called the STL It doesn't - neither "STL" nor "Standard Template Library" appear in the Standard. I'm wondering if the SO C++ community can come up with any better ones? Ideally, they should be expressible in a single sentence, and not involve any code. Edit: I guess I didn't make it clear enough that I was interested in myths believed by C++ developers, not misconceptions held by non-C++users. Oh well...

    Read the article

  • Are pointers primitive types in C++?

    - by Space_C0wb0y
    I was wondering about the last constructor for std::string mentioned here. It says: template<class InputIterator> string (InputIterator begin, InputIterator end); If InputIterator is an integral type, behaves as the sixth constructor version (the one right above this) by typecasting begin and end to call it: string(static_cast<size_t>(begin),static_cast<char>(end)); In any other case, the parameters are taken as iterators, and the content is initialized with the values of the elements that go from the element referred by iterator begin to the element right before the one referred by iterator end. So what does that mean if InputIterator is a char * ?

    Read the article

  • Trimming a vector of strings

    - by dreamlax
    I have an std::vector of std::strings containing data similar to this: [0] = "" [1] = "Abc" [2] = "Def" [3] = "" [4] = "Ghi" [5] = "" [6] = "" How can I get a vector containing the 4 strings from 1 to 4? (i.e. I want to trim all blank strings from the start and end of the vector): [0] = "Abc" [1] = "Def" [2] = "" [3] = "Ghi" Currently, I am using a forward iterator to make my way up to "Abc" and a reverse iterator to make my way back to "Ghi", and then constructing a new vector using those iterators. This method works, but I want to know if there is an easier way to trim these elements. P.S. I'm a C++ noob. Edit Also, I should mention that the vector may be composed entirely of blank strings, in which case a 0-sized vector would be the desired result.

    Read the article

  • How to get the number of loop when using an iterator, in C++?

    - by pollux
    Dear reader, I'm working on a aplication where I draw a couple of images, like this: void TimeSlice::draw(float fX, float fY) { list<TimeSliceLevel*>::iterator it = levels.begin(); float level_x = x; float level_y = y; while(it != levels.end()) { (*it)->draw(level_x,level_y); level_y += (*it)->height; ++it; } } Though this is a bit incorrect. I need to position the TimeSliceLevel* on a X.. When I've got a for(int i = 0; i < slices.size(); ++i) loop, I can use x = i * width. Though I'm using an iterator as I've been told many times that's good programming : and I'm wondering if the iterator has a "index" number of something which I can use to calculate the new X position? (So it's more a question about using iterators) Kind regards, Pollux

    Read the article

  • Iterating through std queue

    - by Ockonal
    Hi, I'm trying to use BOOST_FOREACH for iterating through the std::queue. But there isn't iterators in that class cause I have an error: std::queue<std::string> someList; BOOST_FOREACH(std::string temp, someList) { std::cout << temp; } >no matching function for call to begin(...) >no type named ‘iterator’ in ‘class std::queue<std::basic_string<char> >’ I need in structure like: the first comes, the first goes away.

    Read the article

  • Adapting non-iterable containers to be iterated via custom templatized iterator

    - by DAldridge
    I have some classes, which for various reasons out of scope of this discussion, I cannot modify (irrelevant implementation details omitted): class Foo { /* ... irrelevant public interface ... */ }; class Bar { public: Foo& get_foo(size_t index) { /* whatever */ } size_t size_foo() { /* whatever */ } }; (There are many similar 'Foo' and 'Bar' classes I'm dealing with, and it's all generated code from elsewhere and stuff I don't want to subclass, etc.) [Edit: clarification - although there are many similar 'Foo' and 'Bar' classes, it is guaranteed that each "outer" class will have the getter and size methods. Only the getter method name and return type will differ for each "outer", based on whatever it's "inner" contained type is. So, if I have Baz which contains Quux instances, there will be Quux& Baz::get_quux(size_t index), and size_t Baz::size_quux().] Given the design of the Bar class, you cannot easily use it in STL algorithms (e.g. for_each, find_if, etc.), and must do imperative loops rather than taking a functional approach (reasons why I prefer the latter is also out of scope for this discussion): Bar b; size_t numFoo = b.size_foo(); for (int fooIdx = 0; fooIdx < numFoo; ++fooIdx) { Foo& f = b.get_foo(fooIdx); /* ... do stuff with 'f' ... */ } So... I've never created a custom iterator, and after reading various questions/answers on S.O. about iterator_traits and the like, I came up with this (currently half-baked) "solution": First, the custom iterator mechanism (NOTE: all uses of 'function' and 'bind' are from std::tr1 in MSVC9): // Iterator mechanism... template <typename TOuter, typename TInner> class ContainerIterator : public std::iterator<std::input_iterator_tag, TInner> { public: typedef function<TInner& (size_t)> func_type; ContainerIterator(const ContainerIterator& other) : mFunc(other.mFunc), mIndex(other.mIndex) {} ContainerIterator& operator++() { ++mIndex; return *this; } bool operator==(const ContainerIterator& other) { return ((mFunc.target<TOuter>() == other.mFunc.target<TOuter>()) && (mIndex == other.mIndex)); } bool operator!=(const ContainerIterator& other) { return !(*this == other); } TInner& operator*() { return mFunc(mIndex); } private: template<typename TOuter, typename TInner> friend class ContainerProxy; ContainerIterator(func_type func, size_t index = 0) : mFunc(func), mIndex(index) {} function<TInner& (size_t)> mFunc; size_t mIndex; }; Next, the mechanism by which I get valid iterators representing begin and end of the inner container: // Proxy(?) to the outer class instance, providing a way to get begin() and end() // iterators to the inner contained instances... template <typename TOuter, typename TInner> class ContainerProxy { public: typedef function<TInner& (size_t)> access_func_type; typedef function<size_t ()> size_func_type; typedef ContainerIterator<TOuter, TInner> iter_type; ContainerProxy(access_func_type accessFunc, size_func_type sizeFunc) : mAccessFunc(accessFunc), mSizeFunc(sizeFunc) {} iter_type begin() const { size_t numItems = mSizeFunc(); if (0 == numItems) return end(); else return ContainerIterator<TOuter, TInner>(mAccessFunc, 0); } iter_type end() const { size_t numItems = mSizeFunc(); return ContainerIterator<TOuter, TInner>(mAccessFunc, numItems); } private: access_func_type mAccessFunc; size_func_type mSizeFunc; }; I can use these classes in the following manner: // Sample function object for taking action on an LMX inner class instance yielded // by iteration... template <typename TInner> class SomeTInnerFunctor { public: void operator()(const TInner& inner) { /* ... whatever ... */ } }; // Example of iterating over an outer class instance's inner container... Bar b; /* assume populated which contained items ... */ ContainerProxy<Bar, Foo> bProxy( bind(&Bar::get_foo, b, _1), bind(&Bar::size_foo, b)); for_each(bProxy.begin(), bProxy.end(), SomeTInnerFunctor<Foo>()); Empirically, this solution functions correctly (minus any copy/paste or typos I may have introduced when editing the above for brevity). So, finally, the actual question: I don't like requiring the use of bind() and _1 placeholders, etcetera by the caller. All they really care about is: outer type, inner type, outer type's method to fetch inner instances, outer type's method to fetch count inner instances. Is there any way to "hide" the bind in the body of the template classes somehow? I've been unable to find a way to separately supply template parameters for the types and inner methods separately... Thanks! David

    Read the article

  • Obtain container type from (its) iterator type in C++ (STL)

    - by KRao
    It is easy given a container to get the associated iterators, example: std::vector<double>::iterator i; //An iterator to a std::vector<double> I was wondering if it is possible, given an iterator type, to deduce the type of the "corresponding container" (here I am assuming that for each container there is one and only one (non-const) iterator). More precisely, I would like a template metafunction that works with all STL containers (without having to specialize it manually for each single container) such that, for example: ContainerOf< std::vector<double>::iterator >::type evaluates to std::vector<double> Is it possible? If not, why? Thank you in advance for any help!

    Read the article

  • How to define a custom iterator in C++

    - by Robert Martin
    I've seen a number of posts on SO about how to define custom iterators, but nothing that seems to exactly answers my question, which is... How do I create an iterator that hides a nested for loop? For instance, I have a class Foo, inside of the Foo is a Bar, and inside of the Bar is a string. I could write for (const Foo& foo : foo_set) for (const Bar& bar : foo.bar_set) if (bar.my_string != "baz") cout << bar.my_string << endl; but instead I want to be able to do something like: for (const string& good : foo_set) cout << good << endl; How do I do something like this?

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >