473,721 Members | 2,230 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

If I change from std::vector to std::list my compiler becomes very displeased with me

Hello, consider this complete program (sorry, it's not minimal but I hope
it's readable at least):

#include <algorithm>
#include <iostream>
#include <vector>

class Row
{
public:
Row(int row)
:
m_row(row) {}

int get_row() const
{
return m_row;
}

private:
int m_row;
};

static void print_collectio n(const std::vector<Row >&);

bool less_wrt_row(co nst Row& lhs, const Row& rhs)
{
return lhs.get_row() < rhs.get_row();
}

int
main()
{
std::vector<Row > collection;

collection.push _back(Row(39));
collection.push _back(Row(3));
collection.push _back(Row(202)) ;
collection.push _back(Row(1));

std::cout << "Before sorting:" << std::endl;

print_collectio n(collection);

std::sort(colle ction.begin(), collection.end( ), less_wrt_row);

std::cout << "After sorting:" << std::endl;

print_collectio n(collection);

return 0;
}

static void
print_collectio n(const std::vector<Row >& collection)
{
std::vector<Row >::const_iterat or itr = collection.begi n();

while(itr != collection.end( ))
{
std::cout << itr->get_row() << std::endl;

++itr;
}
}

This program compiles and links and runs without noticable error. But if I
change the type of collection from std::vector to std::list, my compiles
becomes very displeased with me. The output is very long and quite
unreadable for a beginner like me. I assume std::list and std::vector are
not "compatible " with each other with regards to the sorting functions in
the standard library. But say I do have a std::list that I want sorted using
a binary predicate, how should I do it? Am I crazy wanting a std::list if I
want it to be sorted? What data structure should I use then?

Thanks for any replies
Jul 22 '05 #1
5 1784
>std::sort(coll ection.begin(), collection.end( ), less_wrt_row);

Random access of list cannott be done, as we can do with vector. The
sort algorithm should access randomly inorder to sort which is not
possible with list.
One of the first error i got is

MurugesanSH@INP-Murgesansh /cygdrive/d/shanprog/ccprog
$ g++ -o list list.cc
/usr/include/c++/3.3.1/bits/stl_algo.h: In function `void
std::sort(_Rand omAccessIter, _RandomAccessIt er, _Compare) [with
_RandomAccessIt er = std::_List_iter ator<Row, Row&, Row*>, _Compare =
bool
(*)(const Row&, const Row&)]':
list.cc:44: instantiated from here
/usr/include/c++/3.3.1/bits/stl_algo.h:2209 : error: no match for
'operator-' in
From which it can be seen that random access is not possible with list.

-Shan

Jul 22 '05 #2
"Eric Lilja" <er************ *@yahoo.com> wrote in message
news:cr******** **@news.island. liu.se
Hello, consider this complete program (sorry, it's not minimal but I
hope it's readable at least):

#include <algorithm>
#include <iostream>
#include <vector>

class Row
{
public:
Row(int row)
:
m_row(row) {}

int get_row() const
{
return m_row;
}

private:
int m_row;
};

static void print_collectio n(const std::vector<Row >&);

bool less_wrt_row(co nst Row& lhs, const Row& rhs)
{
return lhs.get_row() < rhs.get_row();
}

int
main()
{
std::vector<Row > collection;

collection.push _back(Row(39));
collection.push _back(Row(3));
collection.push _back(Row(202)) ;
collection.push _back(Row(1));

std::cout << "Before sorting:" << std::endl;

print_collectio n(collection);

std::sort(colle ction.begin(), collection.end( ), less_wrt_row);

std::cout << "After sorting:" << std::endl;

print_collectio n(collection);

return 0;
}

static void
print_collectio n(const std::vector<Row >& collection)
{
std::vector<Row >::const_iterat or itr = collection.begi n();

while(itr != collection.end( ))
{
std::cout << itr->get_row() << std::endl;

++itr;
}
}

This program compiles and links and runs without noticable error. But
if I change the type of collection from std::vector to std::list, my
compiles becomes very displeased with me. The output is very long and
quite unreadable for a beginner like me. I assume std::list and
std::vector are not "compatible " with each other with regards to the
sorting functions in the standard library. But say I do have a
std::list that I want sorted using a binary predicate, how should I
do it? Am I crazy wanting a std::list if I want it to be sorted? What
data structure should I use then?
Thanks for any replies


The std::sort function requires a random access iterator. Lists do not
permit random access. Accordingly, if you want to sort a list, you use the
sort member function for lists, i.e., you replace

std::sort(colle ction.begin(), collection.end( ), less_wrt_row);

with

collection.sort (less_wrt_row);
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)

Jul 22 '05 #3
>std::sort(coll ection.begin(), collection.end( ), less_wrt_row);
with
collection.sor t(less_wrt_row) ;


But comparison operator < ("less than") must be defined for the list
element type.

-Shan

Jul 22 '05 #4
"Shan" <sh*******@redi ffmail.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
std::sort(coll ection.begin(), collection.end( ), less_wrt_row);
with
collection.so rt(less_wrt_row );


But comparison operator < ("less than") must be defined for the list
element type.

No.
As for std::sort, there are two overloads of std::list::sort :
one that uses the < operator, the other that takes a predicate
as a parameter (as in the above usage).

BTW: list's sort member function provides guaranteed O(lgN)
performance, and will not copy elements -- which makes it
more efficient than std::sort when collection items are
expensive to copy.
Happy 2005,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <> http://www.brainbench.com
Jul 22 '05 #5
"Ivan Vecerina" <NO************ *************** *******@vecerin a.com> wrote in
message news:cr******** **@news.hispeed .ch...
BTW: list's sort member function provides guaranteed O(lgN)
performance,

Of course I meant O(NlgN).
[ for std::sort worst case could be e.g. O(N2) ]
Jul 22 '05 #6

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

Similar topics

3
3953
by: Mike Pemberton | last post by:
I'm sure there's a good explanation for this effect, but I get rather a strange output from this little test: #include <iostream> #include <list> int main() { std::list<int> int_list;
26
10723
by: BCC | last post by:
Hi, A colleague has some code like this: class CMyObject { // Bunch of Member functions } class CMyObjectList: public std::vector<CMyObject> {
11
8877
by: Steve | last post by:
Hi, I'm using a std::vector to store a list of user defined objects. The vector may have well over 1000 elements, and I'm suffering a performance hit. If I use push_back I get a much worse perfomance than if I first define the vector of a given size, then write to the elements with myvec = However, I'm currently thinking that it isn't feasible to obtain the vector size, so really need to resize the vector dynamically as I go. Is...
2
4772
by: Morten Aune Lyrstad | last post by:
Hi! I haven't been using the standard template libraries much. I have a hard time trying to figure out just what is the practical difference between std::vector and std::list. Aren't both basically a list of objects? Why the two types? And most importantly of all: Which one is the faster? Is it practical to use these in game programming for dynamic arrays, or are they too slow? Yours, Morten Aune Lyrstad
17
3351
by: Michael Hopkins | last post by:
Hi all I want to create a std::vector that goes from 1 to n instead of 0 to n-1. The only change this will have is in loops and when the vector returns positions of elements etc. I am calling this uovec at the moment (for Unit-Offset VECtor). I want the class to respond correctly to all usage of STL containers and algorithms so that it is a transparent replacement for std:vector. The options seems to be:
2
520
by: Priya Mishra | last post by:
Hi All It was very nice to intract with this group, While in my previous post, I was suggested to reffer the link, in order to learn C++, Well I was going thoruigh the link in which i had some querry, well below is the code. #include <vector>
7
2345
by: TBass | last post by:
So I have a class: class Client { unsigned int ClientID; .... }; class MyListenSocket
3
2524
by: Ray D. | last post by:
Hey all, I'm trying to pass a list into a function to edit it but when I compile using g++ I continue to get the following error: maintainNeighbors.cpp:104: error: invalid initialization of non-const reference of type 'std::list<HostID, std::allocator<HostID&' from a temporary of type 'std::list<HostID, std::allocator<HostID*' helpers.cpp:99: error: in passing argument 1 of `void
3
2108
by: Carter | last post by:
I am currently writing some code where I have a list of objects with a maximum occupancy of 4. I have been employing std::vector for this but I was wondering how much overhead is involved. Is it better to use some other data structure if speed is critical i.e. maybe a struct like this- template <typename T> struct max_four { int element_count;
0
8738
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
9376
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9230
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
9148
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
9085
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6678
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
4499
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3207
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2146
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.