Qt Container Classes 续(2)

Escene2021 2011-04-05 06:41:19
加精
前面说过,Qt容器类提供了两种遍历器:Java风格的和STL风格的。前者比较容易使用,后者则可以用在一些通过算法中,功能比较强大。
  对于每一个容器类,都有与之相对应的遍历器:只读遍历器和读写遍历器。只读遍历器有 QVectorIterator<T>,QLinkedListIterator<T>和 QListIterator<T>三种;读写遍历器同样也有三种,只不过名字中具有一个Mutable,即 QMutableVectorIterator<T>,QMutableLinkedListIterator<T>和 QMutableListIterator<T>。这里我们只讨论QList的遍历器,其余遍历器具有几乎相同的API。

  可以看出,Java风格的遍历器,遍历器不指向任何元素,而是指向第一个元素之前、两个元素之间或者是最后一个元素之后的位置。使用Java风格的遍历器进行遍历的典型代码是:

QList<double> list;
// ...
QListIterator<double> i(list);
while (i.hasNext()) {
        doSomethingWith(i.next());
}

  这个遍历器默认指向第一个元素,使用hasNext()和next()函数从前向后遍历。你也可以使用toBack()函数让遍历器指向最后一个元素的后面的位置,然后使用hasPrevious()和previous()函数进行遍历。

  这是只读遍历器,而读写遍历器则可以在遍历的时候进行增删改的操作,例如:

QMutableListIterator<double> i(list);
while (i.hasNext()) {
        if (i.next() < 0.0)
                i.remove();
}

当然,读写遍历器也是可以从后向前遍历的,具体API和前面的几乎相同,这里就不再赘述。

  对应于Java风格的遍历器,每一个顺序容器类C<T>都有两个STL风格的遍历器:C<T>::iterator和 C<T>::const_iterator。正如名字所暗示的那样,const_iterator不允许我们对遍历的数据进行修改。 begin()函数返回指向第一个元素的STL风格的遍历器,例如list[0],而end()函数则会返回指向最后一个之后的元素的STL风格的遍历器,例如如果一个list长度为5,则这个遍历器指向list[5]。

  如果容器是空的,begin()和end()是相同的。这也是用于检测容器是否为空的方法之一,不过调用isEmpty()函数会更加方便。

  STL风格遍历器的语法类似于使用指针对数组的操作。我们可以使用++和--运算符使遍历器移动到下一位置,遍历器的返回值是指向这个元素的指针。例如QVector<T>的iterator返回值是 T * 类型,而const_iterator返回值是 const T * 类型。

  一个典型的使用STL风格遍历器的代码是:

QList<double>::iterator i = list.begin();
while (i != list.end()) {
        *i = qAbs(*i);
        ++i;
}

  对于某些返回容器的函数而言,如果需要使用STL风格的遍历器,我们需要建立一个返回值的拷贝,然后再使用遍历器进行遍历。如下面的代码所示:

QList<int> list = splitter->sizes();
QList<int>::const_iterator i = list.begin();
while (i != list.end()) {
        doSomething(*i);
        ++i;
}

  而如果你直接使用返回值,就像下面的代码:

// WRONG
QList<int>::const_iterator i = splitter->sizes().begin();
while (i != splitter->sizes().end()) {
        doSomething(*i);
        ++i;
}

  这种写法一般不是你所期望的。因为sizes()函数会返回一个临时对象,当函数返回时,这个临时对象就要被销毁,因此调用临时对象的begin()函数是相当不明智的做法。并且这种写法也会有性能问题,因为Qt每次循环都要重建临时对象。因此请注意,如果要使用STL风格的遍历器,并且要遍历作为返回值的容器,就要先创建返回值的拷贝,然后进行遍历。

  在使用Java风格的只读遍历器时,我们不需要这么做,因此系统会自动为我们创建这个拷贝,所以,我们只需很简单的按下面的代码书写:

QListIterator<int> i(splitter->sizes());
while (i.hasNext()) {
        doSomething(i.next());
}

  这里我们提出要建立容器的拷贝,似乎是一项很昂贵的操作。其实并不然。还记得我们上节说过一个隐式数据共享吗?Qt就是使用这个技术,让拷贝一个Qt容器类和拷贝一个指针那么快速。如果我们只进行读操作,数据是不会被复制的,只有当这些需要复制的数据需要进行写操作,这些数据才会被真正的复制,而这一切都是自动进行的,也正因为这个原因,隐式数据共享有时也被称为“写时复制”。隐式数据共享不需要我们做任何额外的操作,它是自动进行的。隐式数据共享让我们有一种可以很方便的进行值返回的编程风格:

QVector<double> sineTable()    
{    
                QVector<double> vect(360);    
                for (int i = 0; i < 360; ++i)    
                                vect[i] = std::sin(i / (2 * M_PI));    
                return vect;    
}
// call
QVector<double> v = sineTable();

  Java中我们经常这么写,这样子也很自然:在函数中创建一个对象,操作完毕后将其返回。但是在C++中,很多人都会说,要避免这么写,因为最后一个return语句会进行临时对象的拷贝工作。如果这个对象很大,这个操作会很昂贵。所以,资深的C++高手们都会有一个STL风格的写法:

void sineTable(std::vector<double> &vect)    
{    
                vect.resize(360);    
                for (int i = 0; i < 360; ++i)    
                                vect[i] = std::sin(i / (2 * M_PI));    
}
// call
QVector<double> v;
sineTable(v);

  这种写法通过传入一个引用避免了拷贝工作。但是这种写法就不那么自然了。而隐式数据共享的使用让我们能够放心的按照第一种写法书写,而不必担心性能问题。

  Qt所有容器类以及其他一些类都使用了隐式数据共享技术,这些类包括QByteArray, QBrush, QFont, QImage, QPixmap和QString。这使得这些类在参数和返回值中使用传值方式相当高效。


  不过,为了正确使用隐式数据共享,我们需要建立一个良好的编程习惯。这其中之一就是,对list或者vector使用at()函数而不是[]操作符进行只读访问。原因是[]操作符既可以是左值又可以是右值,这让Qt容器很难判断到底是左值还是右值,而at()函数是不能作为左值的,因此可以进行隐式数据共享。另外一点是,对于begin(),end()以及其他一些非const容器,在数据改变时Qt会进行深复制。为了避免这一点,要尽可能使用const_iterator, constBegin()和constEnd().

  最后,Qt提供了一种不使用遍历器进行遍历的方法:foreach循环。这实际上是一个宏,使用代码如下所示:

QLinkedList<Movie> list;
Movie movie;
...
foreach (movie, list) {
        if (movie.title() == "Citizen Kane") {
                std::cout << "Found Citizen Kane" << std::endl;
                break;
        }
}

  很多语言,特别是动态语言,以及Java 1.5之后,都有foreach的支持。Qt中使用宏实现了foreach循环,有两个参数,第一个是单个的对象,成为遍历对象,相当于指向容器元素类型的一个指针,第二个是一个容器类。它的意思很明确:每次取出容器中的一个元素,赋值给前面的遍历元素进行操作。需要注意的是,在循环外面定义遍历元素,对于定义中具有逗号的类而言,如QPair<int, double>,是唯一的选择。



...全文
531 28 打赏 收藏 转发到动态 举报
写回复
用AI写文章
28 条回复
切换为时间正序
请发表友善的回复…
发表回复
lpp1989 2012-04-25
  • 打赏
  • 举报
回复
有关于QLIST更详细的介绍吗?
yourstone 2011-04-11
  • 打赏
  • 举报
回复
很好的啊 以前弄过一段时间 后来没继续了 。。
xz33704 2011-04-09
  • 打赏
  • 举报
回复
顶啊 !!正需要
virus701 2011-04-09
  • 打赏
  • 举报
回复
~~~~~~~~~~~~~
gxlant 2011-04-09
  • 打赏
  • 举报
回复
很好,很强大
huanlihing123 2011-04-08
  • 打赏
  • 举报
回复
给长还打算差距拉萨曾经的生产技术的理解的是 是lcd市场vl;s的
zncggaofei 2011-04-08
  • 打赏
  • 举报
回复
Qt的隐式数据共享
kyforever 2011-04-08
  • 打赏
  • 举报
回复
非常好,很到位。谢谢大家。
shuikun 2011-04-07
  • 打赏
  • 举报
回复
作者很有耐心,不错
lmc158 2011-04-07
  • 打赏
  • 举报
回复
  这是只读遍历器,而读写遍历器则可以在遍历的时候进行增删改的操作,例如:

QMutableListIterator<double> i(list);
while (i.hasNext()) {
        if (i.next() < 0.0)
                i.remove();
}
q910553611 2011-04-07
  • 打赏
  • 举报
回复
<td align="center" id="upid" height="80">选择文件:
<input type="file" name="file1" size="40" class="tx1" value="">
<input type="submit" name="Submit" value="开始上传" class="button" onclick="javascript:mysub()">
火山1009 2011-04-07
  • 打赏
  • 举报
回复
hewstone 2011-04-06
  • 打赏
  • 举报
回复
不错,有种相见恨晚的感觉
beyondma 2011-04-06
  • 打赏
  • 举报
回复
不错。价个精!
jxliuyunpeng 2011-04-06
  • 打赏
  • 举报
回复
赞,太强了
A Brief History of Qt Part I: Basic Qt Chapter 1. Getting Started Hello Qt Making Connections Laying Out Widgets Using the Reference Documentation Chapter 2. Creating Dialogs Subclassing QDialog Signals and Slots in Depth Rapid Dialog Design Shape-Changing Dialogs Dynamic Dialogs Built-in Widget and Dialog Classes Chapter 3. Creating Main Windows Subclassing QMainWindow Creating Menus and Toolbars Setting Up the Status Bar Implementing the File Menu Using Dialogs Storing Settings Multiple Documents Splash Screens Chapter 4. Implementing Application Functionality The Central Widget Subclassing QTableWidget Loading and Saving Implementing the Edit Menu Implementing the Other Menus Subclassing QTableWidgetItem Chapter 5. Creating Custom Widgets Customizing Qt Widgets Subclassing QWidget Integrating Custom Widgets with Qt Designer Double Buffering
Part II: Intermediate Qt Chapter 6. Layout Management Laying Out Widgets on a Form Stacked Layouts Splitters Scrolling Areas Dock Windows and Toolbars Multiple Document Interface Chapter 7. Event Processing Reimplementing Event Handlers Installing Event Filters Staying Responsive during Intensive Processing Chapter 8. 2D Graphics Painting with QPainter Coordinate System Transformations High-Quality Rendering with QImage Item-Based Rendering with Graphics View Printing Chapter 9. Drag and Drop Enabling Drag and Drop Supporting Custom Drag Types Clipboard Handling Chapter 10. Item View Classes Using the Item View Convenience Classes Using Predefined Models Implementing Custom Models Implementing Custom Delegates Chapter 11. Container Classes Sequential Containers Associative Containers Generic Algorithms Strings, Byte Arrays, and Variants Chapter 12. Input/Output Reading and Writing Binary Data Reading and Writing Text Traversing Directories Embedding Resources Inter-Process Communication Chapter 13. Databases Connecting and Querying Viewing Tables Editing Records Using Forms Presenting Data in Tabular Forms Chapter 14. Multithreading Creating Threads Synchronizing Threads Communicating with the Main Thread Using Qt's Classes in Secondary Threads Chapter 15. Networking Writing FTP Clients Writing HTTP Clients Writing TCP Client–Server Applications Sending and Receiving UDP Datagrams Chapter 16. XML Reading XML with QXmlStreamReader Reading XML with DOM Reading XML with SAX Writing XML Chapter 17. Providing Online Help Tooltips, Status Tips, and "What's This?" Help Using a Web Browser to Provide Online Help Using QTextBrowser as a Simple Help Engine Using Qt Assistant for Powerful Online Help
Part III: Advanced Qt Chapter 18. Internationalization Working with Unicode Making Applications Translation-Aware Dynamic Language Switching Translating Applications Chapter 19. Look and Feel Customization Using Qt Style Sheets Subclassing QStyle Chapter 20. 3D Graphics Drawing Using OpenGL Combining OpenGL and QPainter Doing Overlays Using Framebuffer Objects Chapter 21. Creating Plugins Extending Qt with Plugins Making Applications Plugin-Aware Writing Application Plugins Chapter 22. Application Scripting Overview of the ECMAScript Language Extending Qt Applications with Scripts Implementing GUI Extensions Using Scripts Automating Tasks through Scripting Chapter 23. Platform-Specific Features Interfacing with Native APIs Using ActiveX on Windows Handling X11 Session Management Chapter 24. Embedded Programming Getting Started with Qt/Embedded Linux Customizing Qt/Embedded Linux Integrating Qt Applications with Qtopia Using Qtopia APIs
Part IV: Appendixes Appendix A. Obtaining and Installing Qt A Note on Licensing Installing Qt/Windows Installing Qt/Mac Installing Qt/X11 Appendix B. Building Qt Applications Using qmake Using Third-Party Build Tools Appendix C. Introduction to Qt Jambi Getting Started with Qt Jambi Using Qt Jambi in the Eclipse IDE Integrating C++ Components with Qt Jambi Appendix D. Introduction to C++ for Java and C# Programmers Getting Started with C++ Main Language Differences The Standard C++ Library About the Authors Jasmin Blanchette Mark Summerfield Production Index
Rapid GUI programming with Python and Qt 1 Contents 8 Foreword 14 Introduction 16 Part I: Python Programming 22 Chapter 1. Data Types and Data Structures 24 Executing Python Code 25 Variables and Objects 27 Numbers and Strings 30 Collections 44 Built-in Functions 52 Summary 56 Exercises 57 Chapter 2. Control Structures 60 Conditional Branching 61 Looping 64 Functions 70 Exception Handling 81 Summary 87 Exercises 87 Chapter 3. Classes and Modules 90 Creating Instances 92 Methods and Special Methods 94 Inheritance and Polymorphism 114 Modules and Multifile Applications 119 Summary 122 Exercises 123 Part II: Basic GUI Programming 124 Chapter 4. Introduction to GUI Programming 126 A Pop-Up Alert in 25 Lines 127 An Expression Evaluator in 30 Lines 131 A Currency Converter in 70 Lines 136 Signals and Slots 142 Summary 151 Exercise 152 Chapter 5. Dialogs 154 Dumb Dialogs 156 Standard Dialogs 162 Smart Dialogs 169 Summary 177 Exercise 178 Chapter 6. Main Windows 180 Creating a Main Window 181 Handling User Actions 205 Summary 216 Exercise 217 Chapter 7. Using Qt Designer 220 Designing User Interfaces 223 Implementing Dialogs 231 Testing Dialogs 236 Summary 238 Exercise 239 Chapter 8. Data Handling and Custom File Formats 242 Main Window Responsibilities 244 Data Container Responsibilities 250 Saving and Loading Binary Files 255 Saving and Loading Text Files 264 Saving and Loading XML Files 271 Summary 280 Exercise 281 Part III: Intermediate GUI Programming 282 Chapter 9. Layouts and Multiple Documents 284 Layout Policies 285 Tab Widgets and Stacked Widgets 287 Splitters 295 Single Document Interface (SDI) 298 Multiple Document Interface (MDI) 305 Summary 315 Exercise 316 Chapter 10. Events, the Clipboard, and Drag and Drop 318 The Event-Handling Mechanism 318 Reimplementing Event Handlers 320 Using the Clipboard 325 Drag and Drop 327 Summary 332 Exercise 333 Chapter 11. Custom Widgets 336 Using Widget Style Sheets 337 Creating Composite Widgets 340 Subclassing Built-in Widgets 341 Subclassing QWidget 343 Summary 360 Exercise 361 Chapter 12. Item-Based Graphics 364 Custom and Interactive Graphics Items 366 Animation and Complex Shapes 383 Summary 393 Exercise 394 Chapter 13. Rich Text and Printing 396 Rich Text Editing 397 Printing Documents 413 Summary 426 Exercise 427 Chapter 14. Model/View Programming 428 Using the Convenience Item Widgets 430 Creating Custom Models 438 Creating Custom Delegates 451 Summary 457 Exercise 458 Chapter 15. Databases 460 Connecting to the Database 461 Executing SQL Queries 461 Using Database Form Views 466 Using Database Table Views 472 Summary 485 Exercise 486 Part IV: Advanced GUI Programming 488 Chapter 16. Advanced Model/View Programming 490 Custom Views 491 Generic Delegates 498 Representing Tabular Data in Trees 507 Summary 520 Exercise 520 Chapter 17. Online Help and Internationalization 524 Online Help 525 Internationalization 527 Summary 534 Exercise 535 Chapter 18. Networking 536 Creating a TCP Client 538 Creating a TCP Server 544 Summary 549 Exercise 549 Chapter 19. Multithreading 552 Creating a Threaded Server 554 Creating and Managing Secondary Threads 559 Implementing a Secondary Thread 567 Summary 572 Exercise 573 This Is Not Quite the End 574 Appendix A. Installing 576 Installing on Windows 576 Installing on Mac OS X 581 Installing on Linux and Unix 585 Appendix B. Selected PyQt Widgets 590 Appendix C. Selected PyQt Class Hierarchies 596 Index 600 A 601 B 602 C 604 D 606 E 608 F 610 G 611 H 611 I 612 J 613 K 613 L 614 M 615 N 616 O 616 P 617 Q 618 R 630 S 631 T 637 U 639 V 639 W 640 X 640 Y 640 Z 640
Python Cookbook英文版 Table of Contents Foreword Preface 1. Python Shortcuts 1.1 Swapping Values Without Using a Temporary Variable 1.2 Constructing a Dictionary Without Excessive Quoting 1.3 Getting a Value from a Dictionary 1.4 Adding an Entry to a Dictionary 1.5 Associating Multiple Values with Each Key in a Dictionary 1.6 Dispatching Using a Dictionary 1.7 Collecting a Bunch of Named Items 1.8 Finding the Intersection of Two Dictionaries 1.9 Assigning and Testing with One Statement 1.10 Using List Comprehensions Instead of map and filter 1.11 Unzipping Simple List-Like Objects 1.12 Flattening a Nested Sequence 1.13 Looping in Parallel over Index and Sequence Items 1.14 Looping Through Multiple Lists 1.15 Spanning a Range Defined by Floats 1.16 Transposing Two-Dimensional Arrays 1.17 Creating Lists of Lists Without Sharing References 2. Searching and Sorting 2.1 Sorting a Dictionary 2.2 Processing Selected Pairs of Structured Data Efficiently 2.3 Sorting While Guaranteeing Sort Stability 2.4 Sorting by One Field, Then by Another 2.5 Looking for Items in a Sorted Sequence Using Binary Search 2.6 Sorting a List of Objects by an Attribute of the Objects 2.7 Sorting by Item or by Attribute 2.8 Selecting Random Elements from a List Without Repetition 2.9 Performing Frequent Membership Tests on a Sequence 2.10 Finding the Deep Index of an Item in an Embedded Sequence 2.11 Showing Off Quicksort in Three Lines 2.12 Sorting Objects Using SQL's ORDER BY Syntax 3. Text 3.1 Processing a String One Character at a Time 3.2 Testing if an Object Is String-Like 3.3 Aligning Strings 3.4 Trimming Space from the Ends of a String 3.5 Combining Strings 3.6 Checking Whe

16,212

社区成员

发帖
与我相关
我的任务
社区描述
Qt 是一个跨平台应用程序框架。通过使用 Qt,您可以一次性开发应用程序和用户界面,然后将其部署到多个桌面和嵌入式操作系统,而无需重复编写源代码。
社区管理员
  • Qt
  • 亭台六七座
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧