我看不到我做錯了什麼。我認爲這可能是三大法則之一。 Codepad link容器不會排序,包含測試用例,(簡單的問題?)
#include <deque>
//#include <string>
//#include <utility>
//#include <cstdlib>
#include <cstring>
#include <iostream>
//#include <algorithm> // I use sort(), so why does this still compile when commented out?
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
using namespace std;
namespace fs = boost::filesystem;
class Page
{
public:
// constructor
Page(const char* path, const char* data, int size) :
path_(fs::path(path)),
size_(size),
data_(new char[size])
{
// cout << "Creating Page..." << endl;
strncpy(data_, data, size);
// cout << "done creating Page..." << endl;
}
// copy constructor
Page(const Page& other) :
path_(fs::path(other.path())),
size_(other.size()),
data_(new char[other.size()])
{
// cout << "Copying Page..." << endl;
strncpy(data_, other.data(), size_);
// cout << "done copying Page..." << endl;
}
// destructor
~Page() { delete[] data_; }
// accessors
const fs::path& path() const { return path_; }
const char* data() const { return data_; }
int size() const { return size_; }
// operators
Page& operator = (const Page& other) {
if (this == &other)
return *this;
char* newImage = new char[other.size()];
strncpy(newImage, other.data(), other.size());
delete[] data_;
data_ = newImage;
return *this;
}
bool operator < (const Page& other) const { return path_ < other.path(); }
private:
fs::path path_;
int size_;
char* data_;
};
class Book
{
public:
Book(const char* path) :
path_(fs::path(path))
{
cout << "Creating Book..." << endl;
cout << "pushing back #1" << endl;
pages_.push_back(Page("image1.jpg", "firstImage", 10));
cout << "pushing back #3" << endl;
pages_.push_back(Page("image3.jpg", "thirdImage", 10));
cout << "pushing back #2" << endl;
pages_.push_back(Page("image2.jpg", "secondImage", 11));
cout << "testing operator <" << endl;
cout << pages_[0].path().string() << (pages_[0] < pages_[1]? " < " : " > ") << pages_[1].path().string() << endl;
cout << pages_[1].path().string() << (pages_[1] < pages_[2]? " < " : " > ") << pages_[2].path().string() << endl;
cout << pages_[0].path().string() << (pages_[0] < pages_[2]? " < " : " > ") << pages_[2].path().string() << endl;
cout << "sorting" << endl;
BOOST_FOREACH (Page p, pages_)
cout << p.path().string() << endl;
sort(pages_.begin(), pages_.end());
cout << "done sorting\n";
BOOST_FOREACH (Page p, pages_)
cout << p.path().string() << endl;
cout << "done Creating Book" << endl;
}
private:
deque<Page> pages_;
fs::path path_;
};
int main() {
Book* book = new Book("/some/path/");
}
您可能不會爲C樣式字符串的空終止符分配額外的字節。字符串比較可能因此而失敗。 – dirkgently 2010-03-15 15:36:54
正在對路徑進行比較。 c風格的字符串是我的程序中的文件流,並且未被排序,這就是爲什麼它們被命名爲「數據」的原因。 – Kache 2010-03-15 15:39:47
你的'op ='不會更新'fs :: path'對象。 – dirkgently 2010-03-15 15:42:09