473,729 Members | 2,353 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

find / find_first_of - vector of pairs..


Oh what fun it is to get acclimated with the various containers and
algorithms.. I'm trying to determine if I could use find/find_first_of
algorithms to achieve the same object of a for loop when searching for
the first element in a vector of pairs. So now:

typedef std::pair<int, int > int_pair;
typedef std::vector<int _pair> vec_int_pair;
int main()
{
vec_int_pair p;
p.push_back(std ::make_pair( 5, 6));
p.push_back(std ::make_pair( 5, 7));

for (vec_int_pair:: iterator it = p.begin();
it != p.end();
++it)
{
if (it->first = 5)
p.erase(it);
}

// now lets try the same thing with find and/or find_first_of

//it = find ( p.begin(), p.end(), 5); -- 1
//it = find_first_of ( p.begin(), p.end(), 5); -- 2

// validate that we only have 5, 7
cout << p.size() << endl;
for (vec_int_pair:: iterator it = p.begin();
it != p.end();
++it)
{
cout << it->first << endl;
cout << it->second << endl;
}
}

The lines marked --1 and --2 are of interest. My guess is I would
need a function object, but I'm not sure if that even makes sense?
Sample source greatly appreaciated.

Thanks.

Jan 2 '06 #1
6 14898
ma740988 wrote:
typedef std::pair<int, int > int_pair;
typedef std::vector<int _pair> vec_int_pair;
int main()
{
vec_int_pair p;
p.push_back(std ::make_pair( 5, 6));
p.push_back(std ::make_pair( 5, 7));

for (vec_int_pair:: iterator it = p.begin();
it != p.end();
++it)
{
if (it->first = 5) shouldn't this be ==? (Yeah, I know, a typo.) p.erase(it);
all iterators get invalidated after an erase. Hence, this for loop
might produce an unexpected / undefined behavior.
}

// now lets try the same thing with find and/or find_first_of

//it = find ( p.begin(), p.end(), 5); -- 1
//it = find_first_of ( p.begin(), p.end(), 5); -- 2

// validate that we only have 5, 7
cout << p.size() << endl;
for (vec_int_pair:: iterator it = p.begin();
it != p.end();
++it)
{
cout << it->first << endl;
cout << it->second << endl;
}
}

The lines marked --1 and --2 are of interest. My guess is I would
need a function object, but I'm not sure if that even makes sense?
Sample source greatly appreaciated.


You need a function object

class Foo {
int i;
public:
Foo(int j) : i(j) { }
bool operator()(std: :pair<int, int> p)
{
return i==p.first;
}

};

And then use find_if

p.erase(find_if ( p.begin(), p.end(), Foo(5)) );

As an aside, if the sequence of the pairs in the vector doesnot matter,
you can use std::multimap.

int main()
{
std::multimap<i nt, int> p;
p.insert(std::m ake_pair( 5, 6));
p.insert(std::m ake_pair( 5, 7));
p.insert(std::m ake_pair( 4, 7));
p.erase(p.find( 5));
cout << p.size() << endl;

for (std::multimap< int,int>::itera tor it = p.begin();
it != p.end();
++it)
{
cout << it->first << endl;
cout << it->second << endl;
}

}

Jan 2 '06 #2
On 1 Jan 2006 21:26:20 -0800, "ma740988" <ma******@gmail .com> wrote:

Oh what fun it is to get acclimated with the various containers and
algorithms.. I'm trying to determine if I could use find/find_first_of
algorithms to achieve the same object of a for loop when searching for
the first element in a vector of pairs. So now:

<snip>

You may create your own pair, to fit this search:

#include <iostream>
#include <vector>

struct int_pair:std::p air<int,int>
{
public:
int_pair(int a,int b):std::pair<in t,int>(a,b) {}

public:
bool operator==(int n) {return first==n;} // Search criterion
};

typedef std::vector<int _pair> vec_int_pair;

int main()
{
vec_int_pair p;
p.push_back(int _pair( 5, 6));
p.push_back(int _pair( 5, 7));

vec_int_pair::i terator it = std::find ( p.begin(), p.end(), 5);
if (it!=p.end())
{
std::cout << "Found!" << std::endl;
std::cout << it->first << std::endl;
std::cout << it->second << std::endl;
}

}
Best regards,

-- Zara
Jan 2 '06 #3
||shouldn't this be ==? (Yeah, I know, a typo.)
Sure is :). I caught that after transmitting the message.

Thank you both.
If I wanted support for - say a 'combination' of primitive types .. i.e
int, int - double, int - char, float - etc.
A templated solution is the answer. Correct? i.e ..

template <typename T>
class Foo2 {
T i;
public:
Foo2(int j) : i(j) { }
bool operator()(std: :pair<T, T> p)
{
return i==p.first;
}
};

Haven't touched the compiler thus far today, but I suspect the compiler
will 'flag' the user if the user desired to do something bogus. For
instance.
typedef unsigned char* ADDRESS_TYPE;
struct my_struct { ADDRESS_TYPE adt; unsigned int sz; };
std::pair < my_struct, int > my_pair;

An STL container holding 'my_pair' - I'm thinking shouldn't work.

Thanks!!
-- MP
--------------------------------------------------------------------------------------------------------
For real convolution the Fourier transform of the convolution is the
product of the transforms of the two functions being convolved.
The question, then, is what happens for complex convolution.

Jan 2 '06 #4

ma740988 wrote:
If I wanted support for - say a 'combination' of primitive types .. i.e
int, int - double, int - char, float - etc.
A templated solution is the answer. Correct? i.e ..

template <typename T>
to have combinations like int-char or int-float etc you need two
template parameters

template<class T, class U> class Foo2 {
T i;
public:
Foo2(int j) : i(j) { } Foo2(T j) i(j) { }
bool operator()(std: :pair<T, T> p) bool operator()(std: :pair<T, U> p)
{
return i==p.first;
}
};

Haven't touched the compiler thus far today, but I suspect the compiler
will 'flag' the user if the user desired to do something bogus. For
instance.
typedef unsigned char* ADDRESS_TYPE;
struct my_struct { ADDRESS_TYPE adt; unsigned int sz; };
std::pair < my_struct, int > my_pair;

This will give errors if operator<< is not overloaded for my_struct or
if operator== is not defined on my_struct. Otherwise it should work
fine.

Jan 2 '06 #5
||This will give errors if operator<< is not overloaded for
|| my_struct or if operator== is not defined on my_struct.

Trying to put together a complete example here so i could get my head
around this. I overload operator << for the stream
but I dont believe that's what I want here.

typedef unsigned char* ADDRESS_TYPE;
struct my_struct {
ADDRESS_TYPE adt; unsigned int sz;
my_struct(unsig ned int size) : sz(size) {}
my_struct& operator=(my_st ruct& ms) // four basic things. self
assign check/delete if pointers/allocate / return.
{
if (this == &ms)
return *this;
delete [] adt;
adt = new unsigned char[sz]; //allocate memory
return *this;
}
friend std::ostream& operator<< // for cout .. wont
work with the find algo - i dont think..
( std::ostream& Out, const my_struct& rhs )
{
return Out << rhs.adt;
}
};

// later
int main() {} // soon to come.

Help thanks...

One other thing. The text (Eckel - Chapter 7, Generic Container - pg
464) I'm reading suggest that inserting and erasing elements in the
middle of a vector using an iterator is a bad idea. From the looks of
the sample program and my understanding of the words, 'bad idea'
amounts to re-allocation. The program - in a nutshell:
1. reserved space for 11 elements.
2. inserted 10 elements.
3. Found the middle via an iterator - Inserted an additional element
4. erased the element in the middle (using the iteator in 3 which has
since been invalidated).

Besides, the error in 4. i.e using an iterator that has been
invalidated (obviously a bad idea). The words below the program
highlights the implications surrounding reservation for 10 elements as
opposed to 11. Obviously if 10 elements were reserved initially.
Insertion of a new element results in - re-location .. Oops!!

In any event, my question is this: In order for the vector to maintain
it's linear array. Each call to erase results in a call to 'operator='.
Period!! Correct?
---------------------------------------------------------------------------------------------
For real convolution the Fourier transform of the convolution is the
product of the transforms of the two functions being convolved.
The question, then, is what happens for complex convolution.

Jan 3 '06 #6
ma740988 wrote:
my_struct& operator=(my_st ruct& ms) // four basic things. self

You have overloaded assignment operator. Note that you need to provide
operator==() (the eqaulity testing operator) so that find_if works.
Once you provide that, your code will work properly. I tried it and it
worked. The sample 'main' function that I used is -

typedef std::pair < my_struct, int > my_pair;
typedef std::vector<my_ pair> vec_my_pair;
int main()
{
my_struct z(10);
vec_my_pair p;
p.push_back(std ::make_pair(z, 6));
p.push_back(std ::make_pair(z, 7));
p.push_back(std ::make_pair(z, 9));
p.push_back(std ::make_pair(z, 10));

p.erase(std::fi nd_if(p.begin() ,p.end(),Foo2<m y_struct,int>(z )));

for (vec_my_pair::i terator it = p.begin(); it != p.end(); ++it)
{
cout << it->first << endl; // uses operator<< overloaded for
my_struct
cout << it->second << endl;
}
}
One other thing. The text (Eckel - Chapter 7, Generic Container - pg
464) I'm reading suggest that inserting and erasing elements in the
middle of a vector using an iterator is a bad idea. From the looks of
the sample program and my understanding of the words, 'bad idea'
amounts to re-allocation.
Not necessarily. Insertion of an element in the middle of a vector
results into displacement (relocation) of the elements present after
the insertion point. Re-allocation occurs if the capacity needs to be
increased, not otherwise.
In any event, my question is this: In order for the vector to maintain
it's linear array. Each call to erase results in a call to 'operator='.
Period!! Correct?


The standard doesnot give any rules for the implementation - it simply
mentions the pre and post conditions and complexity of the algorithm.
Further, the standard containers require the elements to be assignable,
and hence a call to erase should have no problems in calling
operator=() on the elements.

Hope this helps.

Jan 3 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
4622
by: Ben | last post by:
I have a program which is using a lot of memory. At the moment I store a lot of pointers to objects in std::vector. (millions of them) I have three questions: 1) Lets say the average Vector is of size 2. How much memory can I save by storing my pointers in c++ arrays, rather than vectors.
18
7227
by: ma740988 | last post by:
Trying to get more acclimated with the use of function objects. As part of my test, consider: # include <vector> # include <iostream> # include <algorithm> #include <stdexcept> #include <bitset> using std::vector;
23
1967
by: sidney | last post by:
Hi all, I am trying to make a vector containing objects the have a reference member. However, as soon as I try to push_back an element into this vector, g++ balks at the fact that it needs to instantiate an operator= on the class containing the reference members (see below for what I try to do). #include <vector>
13
2085
by: arnuld | last post by:
this is the code: ------------------------------------------------------------------------- #include <iostream> #include <string> #include <vector> struct Pair { std::string name;
3
1857
by: lovecreatesbea... | last post by:
Can the 3rd and 4th arguments of find_first_of(beg1, end1, beg2, end2) and find_end(beg1, end1, beg2, end2) be the same? I got an invalid iterator on following 2 calls: pos_ic_b = find_first_of(vecIcFile.begin(), vecIcFile.end(), it, it); pos_ic_e = find_end(vecIcFile.begin(), vecIcFile.end(), it, it); But the following 2 calls are successful:
4
5531
by: Anonymous | last post by:
I ahve a vector of doubles taht I need to extract values from. I was just about to use the STL find() algo, but I have a couple of questions: first: can you specify the tolerance threshold to match on doubles? second: if yes, how may this be done (i.e. how many one specify the tolerance threshold for comparing doubles?)
8
2779
by: Diwa | last post by:
Hi Guys, Is there any better way than below to find an int in a string (e.g. "30" in "KFStat30A") // -------------------------------------------------------------- #include <iostream> #include <sstream> #include <vector>
4
1598
by: Angus | last post by:
I have a map between an integer value - call it a deviceID and a device name - call it devicename. If I use a map I can either use the int or the string as the key. But which? If I use for example the deviceid as the key, then if I need to find the deviceID from the devicename then I need to iterate through the whole map. I am worried about performance of this. I setup the map at program startup - and it is static. So I wondered...
1
1840
by: efittery | last post by:
I need to modify the following code to handle a vector of pairs of floats. I was just thinking of casting my vector of floats into being a vector of pairs of floats. Alternately, I have looked into using the instream iterator to initialize the vector of pairs of floats. Any thoughts would be appreciated. given the test.txt file which contains:
0
8917
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8761
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9281
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8148
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6022
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2680
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.