C++ :: Efficient Algorithm On List Iterator

Mar 6, 2013

I have a list and a vector, for example like

list<int> mylist = {1, 1, 1, 0, 0, 1, 0, 0}
vector<int> myvec;

I want to create an efficient algorithm to erase all element of value "1", and give these elements to a vector. My code (not efficient) is as follows

for(auto it = mylist.begin(); it != mylist.end(); it++) {
if(*it == 1) {
myvec.push_back(*it);
it = mylist.erase(it);
if(it != mylist.begin())
it--;
}
}

View 8 Replies


ADVERTISEMENT

C++ :: Unexpected Result Decrementing End Of Range Iterator In Call To Transform Algorithm

Aug 23, 2013

I found this piece code on the following site:

[URL]

I predicted the outcome as being 01230 as I thought the prefix decrement operator on iterator ce would prevent the final element of the list from being transformed.

I was wrong, the correct output is 01234.

So, I removed the decrement prefix and ran the test again, expecting a different result. It wasn't! The result was still 01234.

Only when I decremented ce twice did I get the result I initially expected, 01230.

why the first decrement of ce appears to have no effect?

#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <cstdio>
int main() {
typedef std::list<int> L;

[code]....

View 2 Replies View Related

C++ :: Cannot Dereference Iterator At The End Of List?

Apr 8, 2014

Why this code works
Elenco e1;
e1.add(Persona("a","b"));
e1.add(Persona("c","d"));
e1.add(Persona("e","f"));
e1.add(Persona("e","f"));
e1.remove(2); //list of 4 elements

but this not work?
Elenco e1;
e1.add(Persona("a","b"));
e1.add(Persona("c","d"));
e1.add(Persona("e","f"));
e1.remove(2); //list of 3 elements

This is remove method:
Persona Elenco:: remove(int pos){
list<Persona> ::iterator iter=l.begin();
for(int i=0 ;i<pos;i++){
iter++;
}
return *(l.erase(iter)); //erase ritorna un iterator
}

View 4 Replies View Related

Visual C++ :: Program To Print List Using Iterator And Operator Overloading

Nov 19, 2014

I'm trying to use the given Iterators to overload my = operator to print my list to screen. I keep getting Link2019 error though and have narrowed the problem down to my print operator. I'm wondering if it has anything to do with the fact that my operator is in private part of class? I'm new to this concept.

Code:
#include "List.h"
// methods for Node all
//ME
Node::Node( const string &s, Node * p, Node * z) : word( s ), next( p ), prev(z)//constructor {
word = s; // init. word data with a copy of s
next = p; // next pointer points to p

[Code] .....

View 1 Replies View Related

C++ :: Most Efficient Way To Read A Bit From A Byte?

Mar 30, 2013

What is the most efficient way to read a bit at a particular position in a byte?

View 3 Replies View Related

C/C++ :: Fastest / Most Efficient Way To Add Two Fractions

Jul 12, 2012

I have to write a function

struct rNumber add(rNumber a ,rNumber b); 

which adds two rational numbers in following representation :
rNumber := s*(n/d)* 2^e
struct rNumber{
 _byte_t s; // sign (do not consider for this question)
 uint n; //numerator
 uint d;// denominator
 short e;//exponent
}  

If the exponents of both numbers are not equal, then they have to be made equal in order to add them. This can be made in 4 ways : increase or decrease the n or d of both numbers.

But if we decrease the denominator of a number (a.d =1) by shifting it for example 1 bit to the right, we get 0 which leads to INFINITY for the fraction. In another case decreasing the numerator would lead the n to be 0 which meanse the whole fraction is then 0.

According to this, in worst case, all 4 cases has to be checked for the right result.

So far the UNDERFLOW of n or d is considered. If we try to increase the value of n or d, then OVERFLOW may also occur.

The very first, intuitive solution would be iteratively increase/decrease one of the terms and to check if the change leads to ZERO or INFINITY.

View 5 Replies View Related

C++ :: Linked List Sorting Algorithm?

May 31, 2013

This is the algorithm I have so far and it works great. I was wondering what other people think? Comments/Critiques??

void LinkedList::sort()
{
if (head != 0)
{

[Code].....

View 14 Replies View Related

C++ :: Writing Delete Algorithm In Ordered Linked List

Oct 19, 2013

I am trying to write a delete algorithm for an ordered linked list. Search and traverse I think I have down but delete is giving me fits. It crashes every time.

I have a private pointer to a ListNode strcuture called head in my TestLL class. The ListNode structure contains int Key, double dataValue, and ListNode *next. The function returns true if the node to delete was found and deleted or false if it was not found.

Code:
bool TestLL::Delete(int Key) {
ListNode *back = NULL, *temp = head;
//Search for the node to delete
while((temp != NULL) && (key != temp -> key))

[Code] .....

View 4 Replies View Related

C++ :: Shortest Path Algorithm Through Sudo-linked List

Feb 9, 2013

I am needing to code a shorted path algorithm through a sort of sudo-linked list. I say sudo because its not a true linked list as in *next *prev. The Data in memory that i need to do this through is in memory via a class.

The important parts of the class is one element is just an int that tells me the current node number, the second is an int that tells me how many neighbors this node has, and the third is a vector of ints containing the number of the neighboring nodes.

The vector was needed because each node type can have a different amount of neighbors.

For example if the class data looks like this:

0 1 1

that means that it is node 0, it has 1 neighbor, and the neighboring node is 1

another example:

8 3 1 2 3

means node 8, 3 neighbors, and the neighbors are nodes 1 2 3

I need to find a way to get from 1 node to another using this linked list, and the shortest path if we plan the data points well enough can be determined by how many nodes there are from start to finish.

View 2 Replies View Related

C/C++ :: Dijkstra Algorithm - Reading In Data To A Linked List

Mar 20, 2014

Program to implement Dijkstra's Algorithm. Have Problems storing graph info into linked-list . The input is in the following format

5
1 2 9.0
1 3 12.0
2 4 18.0
2 3 6.0
2 5 20.0
3 5 15.0
0
1 5

The first number is the number of vertexes in the graph. Then next lines up to 0 are the edges of the graph. With the first and second numbers being the vertexes and the third being how far the edge is between them. Trying to read in the data and store the edges into there locations in the List adjacency for that vertex. This example would make a graph with five vertexes with edges from 1 to 2&3. 2 to 4&3&1 etc. It also stores in the opposites ex 2 1 9.0.

When reading it in and printing it back out it seems that it is only storing the last data entered for that vertex. EX. When trying to print out the data read in i only get 1 3 12.0, 2 5 20.0, 3 5 15.0, ( 4 2 18.0, 5 3 15.0 would show up if `if(i<n)` was removed it is there so it does not show duplicate edges).

#include <cstdio>
using namespace std;
struct ListCell {
ListCell* next;
int vertex;
double weight;
ListCell(int v, double w, ListCell* nxt)

[Code] ....

View 5 Replies View Related

C++ :: List Of Latitude And Longitude Coordinates - Sorting Algorithm

Jul 4, 2012

I have a list of latitude and longitude coordinates which are supposed to trace the outline of a city. Somehow they got scrambled so that they are now out of order. I'd like to write a program to arrange them such that one could follow from one coordinate to the next and trace the perimeter. However, I've run out of ideas for algorithms. What I did so far was a simple search for the nearest coordinate, starting from the first coordinate pair in the array. This produced local regions which worked rather well, but globally there were large jumps as the algorithm ran out of nearby coordinates and was forced to jump across the map.

Is there already a developed algorithm to perform this function?

View 1 Replies View Related

C++ :: How To Get Iterator To The I'th Element

Jun 17, 2013

I'm making my first steps in STL, and I have a few question:

Is there a way to get an iterator to the i'th element in the collection (set or list), instead of just to the end or the begin?

And another question: Let's say I have an iterator, pointing to some element in my collection, and I use erase() (which takes as parameter an iterator that points to the soon-to-be erased element), what happens to that iterator? will it now point to NULL?

View 7 Replies View Related

C/C++ :: How To Declare Iterator

Aug 20, 2014

I have this class with template:

template<template<class, class> class ContainerType>
class Movie {
public:
typedef ContainerType<Actor*, std::allocator<Actor*> > Container;

and i have a member func to find actor in movie according to actor id:

const Actor* findActor(int id) const {
typename Container::iterator it;
Actor* p(NULL);
it=actors.begin();
std::for_each(it,actors.end(),(*it)->getId()==id?p=*it:0);
if (p==*actors.end()) return NULL;
return p;
}

I receive error that no match for operator= in it.

How to declare correct iterator ?the type of actors is Container..

View 6 Replies View Related

C++ :: Use Of Iterator Across Files And Classes

Nov 18, 2013

Here's a few parts of a program I'm working at. It does compile, and it does work as expected. Anyway Eclipse Kepler marks one line as a bug with the remark Field 'befehl' could not be resolved. The bug sign didn't show up when both classes were in one file.

ScriptInterpreter maintains and processes a vector of Objects, initialised with example data. An iterator of the vector keeps track of the current position while various methods process the data. I've copied the relevant lines only.

I can live with a few wrongly bug-marked lines in Eclipse. What I don't want is any hidden errors that express at some time later.

Is there anything wrong with the code? Anything that's not recommended and compiles anyway? Is anything c++11-specific about the questionable line?

AtomicCommand.h
class AtomicCommand {
public:
int befehl;

[Code] .....

Note that line 9 has a bug sign, too. Eclipse doesn't recognise all my c++11 code.

View 4 Replies View Related

C++ :: How To Control Iterator Of Multimap

Feb 22, 2013

I am running some simulation, in which i need to control the iterator of a multimap, like

multimap<double, int> mapp;
......

int n=6;
for(int i=0; i<5; i++) {
for(auto it = mapp.begin()+i*n; it!=mapp.begin()+(i+1)*n; it++) {
......

However this way of controlling is not possible for multimap. Why and how the make it work? Do I need to overload the operator +?

View 14 Replies View Related

C++ :: Can't Seem To Make STL Iterator Class

May 24, 2013

I can't seem to make the STL iterator class work how I need it to.I am implementing a multi list graph and I need to iterate through my STL list of Vertex pointer objects. I keep getting the error:

Error 1 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::_List_iterator<_Mylist>' (or there is no acceptable conversion) and the same for != for my terminating condition.

template <typename V, typename E>
void Graph<V, E>::InsertEdge(V from, V to, E edge) {
list<Vertex<V>*>::iterator iter;
for(iter = m_Vertices.begin(); iter != m_Vertices.end(); ++iter)

[code].....

View 2 Replies View Related

C++ :: Difference Between Iterator And Pointer

Jan 21, 2013

I just figured out that some std functions (for example: copy) need the resource and target objects have iterators to work. Otherwise, the compiler rejects. In case of two arrays, declared as:

double myA[100] = {};
array<double, 100> myB = {};

myA[0] is like a pointer, myB.begin() an iterator, if I do not make any mistake. So, what is exactly the difference between the pointer and the iterator here? They all give the access to elements.

If I need the target of copy to be an array like myA which cannot give an iterator, is there a way to make the command "copy" work for it?

View 9 Replies View Related

C++ :: Get Iterator Position After Find If

Jan 25, 2013

I want to get the iterator position after to use find if:

std::list<Texture*>::iterator result = find_if(
texturelist.begin(),
texturelist.end(),
std::bind2nd<CompareTEX>(CompareTEX(),n_tex));
if (result != texturelist.end()) {
return // position result
}

View 5 Replies View Related

C++ :: Vector Iterator Not Incrementable

May 25, 2013

I am receiving the error: Vector Iterator not incrementable. However, when erasing I'm already re-setting 'it' and pre-incrementing at the end of the while-clause.what's wrong?

vector<st>::iterator it = map[0][0].begin();
while(it != map[0][0].end()) {
if((*it).val == 5) {

[Code] .....

View 1 Replies View Related

C/C++ :: Manipulating Data Through Own Iterator

Apr 10, 2014

We were given a task to use lists and iterators. We were supposed to make them from scratch. I'm done with that. The problems that I'm having are as following:

1. I'm not able to access the list made of Course datatype which is present in each Student instance. Does this mean I need to make an iterator for that course list inside the student class?

2. Similarly since I don't have direct access to The course list so I added the course into the Student list through the student objects not through the iterator. How can I do it through the iterator?

3. Printing of a particular student and his courses is not happening as my iterator made for student only prints out the students, not the courses present in their courselist. How to do that?

Here's the code

#include <iostream>
#include <string>
using namespace std;
const int ILLEGAL_SIZE = 1;
const int OUT_OF_MEMORY = 2;
const int NO_SPACE = 3;
const int ILLEGAL_INDEX = 4;

[Code] .....

View 1 Replies View Related

C/C++ :: Storing Map Iterator In Vector?

Jan 10, 2013

I'm trying out the code below; it runs and produces the output I'd expect, but could it lead to undefined behavior?

To test with, I show the key and wait for user input; if the input doesn't match the value, the iterator is stored in the vector.

map<string, string> test;
map<string, string>::iterator it;  
vector<map<string, string>::iterator> bad_input;  
string input;  
test["key 1"] = "value 1";

[Code] ....

I am also interested in knowing if I can use an iterator to walk through the vector? I tried

vector<map<string, string>::iterator>::iterator v_it;  
for(v_it = bad_input.begin(); v_it != bad_input.end(); ++v_it)
    cout << v_it-> ??  

However, I couldn't figure out how to access "first" and "second" using this method. Is it possible to do so?

View 2 Replies View Related

C++ :: Segmentation Fault On Multimap Iterator

Jan 5, 2015

I have created a multimap for my road points. The key refers to the road number and the values are vec3 points that make up the road.

I am trying to iterate through the values of each key point and create a road segment at each point on the road (except the last), adjust the values to be on the road points and then store them in a std::vector.

The RoadSegment constructor creates 6 vec3 points and pushes them onto a std::vector.

I have a segmentation fault in the line marked in bold
[for(mapIt = it.first; mapIt != it.second; ++mapIt)]

When i take out the lines creating the new objects and pushing them onto the std::vector it works fine.

std::vector<glm::vec3>::iterator SegIt;
for(int i = 0; i < m_genRoads->getKeyValueData().size(); i++)
{
int numberDesired = m_genRoads->getMultimapData().count(i) - 1;

[Code]...

View 1 Replies View Related

C++ :: Function To Find Out Iterator Of Certain Value In Vector

Sep 4, 2013

I defined the following function to find out the iterator of a certain value in the vector. I defined it as such so if the value exist in the vector then return a iterator of it, if not then return a pointer pointing to nonsense.:

vector<tIndex_t>::iterator unlabelTit(const tIndex_t index) {
for(vector<tIndex_t>::iterator it=unlabelT.begin(); it<unlabelT.end(); it++) {
if(index==*it) return it;
} return NULL;
}

But looks this one is not accepted by compiler, saying I cannot do this kind of comparison like:

unlabelTit(i)!=NULL;

so I just delete the return NULL; and then the compiler giving me warning about no return statement before }.

a pointer pointing to nonsense? how to do that?

View 3 Replies View Related

C++ :: Iterator To A Vector Of Struct Type?

Nov 18, 2013

I'm working on a program where I have a vector full of <myClassType> structs.

I'm trying to insert items into a vector, searching first through the vector to make sure the value isn't already in the vector before inserting it. The "find" function isn't working properly.

I keep getting C2678 "binary '==': no operator found which takes a left-hand operand of type "myClassType" or there is no conversion errors in Visual Studio 2010.

I know it's something having to do with the find function and my iterators, but I can't, for the life of me, figure out what it is.

I've tried switching to const_iterators, but I get the same error message.

void foo::insert(const myClassType& en) {
vector<myClassType>::iterator it;
vector<myClassType>::iterator it1;
it = find(Table.begin(), Table.end(), en.memberOne);

[Code] .....

View 3 Replies View Related

C++ :: Error In Iterator Declaration With Typename Map

Jun 24, 2014

I'm trying to make a function to show the content of maps as follows:

template<typename A, typename B>
void show_map(const std::map<A,B> &src) {
for( std::map<A,B>::iterator it=src.begin(); it!=src.end(); ++it ) {
cout << it->first << " ____ " << it->second << endl;
}
};

However, I got this error in the 'for' line: "error: expected ‘;’ before ‘it’" (and then errors that it is not declared, etc). I'm sure that there is no missing ; in other functions. If you try to write a random line before that you get no error there for example, always in the for.

It is there something that you need to do with iterators when you declare generic datatypes?

View 4 Replies View Related

C++ :: What Could Cause A Core Dump At Iterator Pre-increment

Oct 15, 2014

I got the core dump file so I know exactly which line it crashes. Below are some of the information:

OS: Red Hat Enterprise 5.8

Example snippets of when the crash happen:

Code:

typedef map<int, MyClassObj> MyMapT;
.
.
void someFunction( MyMapT& inMap )
{
for ( MyMapT::iterator iter=inMap.begin(); iter!=inMap.end(); ++iter )
{
.
.
}
}

Using GDB, I am able to find out that it crashes at the "++iter" as the .h file indicate it was a "++" operation for the iterator. Tracing up the stack frame it indicate it crash during the copy constructor of some "__rb_tree_node". I did some Googling and it seems that is some Red-Black tree implementation for the map. Honestly I do not quite understand the Red-Black tree and I believe STL map is a very very well tested container, so the problem must lie in my code so that I can look out for it.

View 14 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved