C++映射:具有自定义类的运算符[]不起作用(总是返回0)
C++ map: operator[] with custom class does not work (always returns 0)
我正在尝试实现一个MinHeap,其中堆上的对象是WorkerNodes。我的方法返回map,它旨在允许客户端代码确定哪些WorkerNode索引已从minHeaify操作更改。
std::cout << "heapifying " << heap_[root] << "from index " << root << "n.";
int size = heap_.size();
bool swapped = false;
std::map<WorkerNode, int> tracker;
for (int i = root; i >= 0; --i)
{
while (true)
{
int leftChild = 2 * i + 1;
if (leftChild < 0 || leftChild >= size)
break;
int rightChild = 2 * i + 2;
int smallerChild = leftChild;
if (rightChild < size && heap_[rightChild] < heap_[leftChild])
smallerChild = rightChild;
if (heap_[i] <= heap_[smallerChild])
break;
// index tracking
tracker[heap_[i]] = smallerChild;
tracker[heap_[smallerChild]] = i;
std::cout << "**nn"
<< heap_[i] << " has moved to " << smallerChild;
std::cout << ", and " << heap_[smallerChild] << " has moved to " << i << "n**";
// swap heap_[i] and heap_[smallerChild]
swapped = true;
T temp = heap_[i];
heap_[i] = heap_[smallerChild];
heap_[smallerChild] = temp;
i = smallerChild;
}
}
if (!swapped) // avoids bad access
{
tracker[heap_[root]] = root;
for (auto &itm : tracker)
{
std::cout << "**n"
<< itm.first << " is at " << itm.second << "!!!n";
}
std::cout << "**nno swap; " << heap_[root] << " stays at " << tracker[heap_[root]] << "n**";
}
return tracker;
这是我看到的输出:
heapifying W1-1from index 0
.**
W1-1 is at 0!!!
**
no swap; W1-1 stays at 0
**heapifying W2-2from index 1
.**
W2-2 is at 1!!!
**
no swap; W2-2 stays at 0
**heapifying W3-3from index 2
.**
W3-3 is at 2!!!
**
no swap; W3-3 stays at 0
**heapifying W0-3from index 3
.**
W0-3 is at 3!!!
**
no swap; W0-3 stays at 0
这个问题是在运行测试用例时引起我注意的,我正在做这样的事情:
WorkerNode key("W4", 2);
// after two decrements, its index should still be 3.
BOOST_TEST(tracker[key] == 3);
得到这样的输出:
error: in "minheap_test_suite/case6": check tracker[key] == 3 has failed [0 != 3]
因此,据我所知,我的minHeaify方法中的pre-exit for循环确认了正在将正确的数据插入到映射中,但当我尝试使用[]
运算符访问这些数据时,它无法定位我刚刚插入的WorkerNode索引配对,返回0作为它可能只是默认构造的值。
当我尝试使用find()
而不是[]
时,就像现在一样:
tracker[heap_[root]] = root;
for (auto &itm : tracker)
{
std::cout << "**n"
<< itm.first << " is at " << itm.second << "!!!n";
}
int index = tracker.find(heap_[root])->second;
std::cout << "**nno swap; " << heap_[root] << " stays at " << index << "n**";
我得到以下输出:
heapifying W1-1from index 0
.**
W1-1 is at 0!!!
**
no swap; W1-1 stays at -1354735968
**heapifying W2-2from index 1
.**
W2-2 is at 1!!!
**
no swap; W2-2 stays at 3233540
这是我的WorkerNode.h文件,删除了注释:
#include <ostream>
#include <string>
struct WorkerNode
{
unsigned numJobs_; ///< worker job count.
std::string workerID_; ///< worker ID string.
explicit WorkerNode() : numJobs_(0), workerID_("") {}
WorkerNode(std::string id) : numJobs_(0), workerID_(id) {}
WorkerNode(std::string id, unsigned jobs) : numJobs_(jobs), workerID_(id) {}
WorkerNode(WorkerNode &&other) : numJobs_(other.numJobs_), workerID_(other.workerID_)
{
other.numJobs_ = 0;
other.workerID_ = "";
}
WorkerNode(const WorkerNode &other) : numJobs_(other.numJobs_), workerID_(other.workerID_) {}
WorkerNode &operator=(const WorkerNode &other)
{
if (this == &other)
return *this;
this->numJobs_ = other.numJobs_;
this->workerID_ = other.workerID_;
return *this;
}
WorkerNode &operator=(WorkerNode &&other)
{
if (this == &other)
return *this;
this->numJobs_ = other.numJobs_;
this->workerID_ = other.workerID_;
other.numJobs_ = 0;
other.workerID_ = "";
return *this;
}
~WorkerNode() {}
bool operator<(const WorkerNode &rhs) const
{
return *this <= rhs;
}
bool operator<=(const WorkerNode &rhs) const
{
if (numJobs_ < rhs.numJobs_)
return true;
else if (rhs.numJobs_ < numJobs_)
return false;
else
{
return workerID_.compare(rhs.workerID_) <= 0 ? true : false;
}
}
bool operator==(const WorkerNode &rhs) const
{
if (numJobs_ == rhs.numJobs_ && workerID_ == rhs.workerID_)
return true;
else
{
return false;
}
}
void operator--()
{
if (numJobs_ > 0)
numJobs_ -= 1;
}
void operator++()
{
numJobs_ += 1;
}
friend std::ostream &operator<<(std::ostream &out, const WorkerNode &n)
{
out << n.workerID_ << "-" << n.numJobs_;
return out;
}
};
WTF我在这里做错了吗?
编辑:
好了,伙计们,这是我的代表。我为之前荒谬的代码膨胀道歉。这个例子100%再现了我目前的困惑。让我们追根究底吧。
Key.h:
// user-defined struct, intended to be used as a map key.
#include <string>
#include <ostream>
struct Key
{
std::string id;
unsigned jobs;
Key(std::string id_ = "", unsigned jobs_ = 0) : id(id_), jobs(jobs_) {}
bool operator<(const Key &rhs) const
{
if (jobs < rhs.jobs)
return true;
else if (rhs.jobs < jobs)
return false;
else
return id.compare(rhs.id) <= 0 ? true : false;
}
bool operator<=(const Key &rhs) const
{
if (jobs < rhs.jobs)
return true;
else if (rhs.jobs < jobs)
return false;
else
return id.compare(rhs.id) <= 0 ? true : false;
}
friend std::ostream &operator<<(std::ostream &o, const Key &key)
{
o << key.id << "-" << key.jobs;
return o;
}
};
MinHeap.h:
#include <vector>
#include <map>
#include "Key.h"
struct MinHeap
{
std::vector<Key> heap;
std::map<Key, int> minHeapify(int root)
{
std::map<Key, int> tracker;
for (int i = 0; i < heap.size(); ++i)
tracker[heap[i]] = i;
return tracker;
}
std::map<Key, int> insert(const Key &key)
{
heap.push_back(key);
return minHeapify(heap.size() - 1);
}
};
main.cpp:
#include <iostream>
#include "MinHeap.h"
int main()
{
MinHeap heap;
std::map<Key, int> tracker;
for (int i = 0; i < 3; ++i)
{
Key key("Key" + std::to_string(i), i);
tracker = heap.insert(key);
//checking tracker contents using auto for loop
std::cout << "tracker keyindex contents: ";
for (auto &itm : tracker)
{
std::cout << itm.first << " ::: " << itm.second << ", ";
}
std::cout << "nn";
//checking key and tracker[key], which should reflect
//each other as well as the operation done in minHeapify.
/// *** what tracker[key] is actually printing ***
std::cout << "tracker[key] = " << tracker[key] << std::endl;
/// **********************************************
/// *** what tracker[key] is expected to be printing ***
std::cout << "actual tracker key index: " << key.jobs << std::endl;
/// ****************************************************
}
return 0;
}
自己运行main.cpp。这里最大的问题是最后两份打印报表。先前的for循环确认预期的Keys确实是由minHeapify(int)
操作返回的,并且具有预期的索引。
但是,尝试使用[Key]
将索引细分为map<Key,int>
不会返回期望的索引。
希望我能更清楚地说明这种困惑。
提前感谢您的帮助。
干杯
我认为这个问题已经在雷米·勒博的评论中指出了。
您对Key::operator<
的实现不满足严格弱排序的要求,因为这是可用作std::map
中密钥的类型的要求。
您需要在实现中做一个小的更改。
bool operator<(const Key &rhs) const
{
if (jobs < rhs.jobs)
return true;
else if (rhs.jobs < jobs)
return false;
else
return id.compare(rhs.id) < 0 ? true : false; // Needs to be <, not <=
}
您可以使用std::tie
简化功能
bool operator<(const Key &rhs) const
{
std::tie(jobs, id) < std::tie(rhs.jobs, rhs.id);
}
这就是一个最小可复制示例的样子:
#include <iostream>
#include <map>
struct Key {
std::string id;
unsigned jobs;
bool operator<(const Key & rhs) const {
if (jobs < rhs.jobs)
return true;
else if (rhs.jobs < jobs)
return false;
else
return id.compare(rhs.id) <= 0 ? true : false;
}
};
int main() {
std::map<Key, int> m;
m[Key { "Key0", 0 }] = 0;
m[Key { "Key1", 1 }] = 1;
m[Key { "Key2", 2 }] = 2;
std::cout << m[Key { "Key0", 0 }] << std::endl;
std::cout << m[Key { "Key1", 1 }] << std::endl;
std::cout << m[Key { "Key2", 2 }] << std::endl;
return 0;
}
这更容易掌握吗?这对人们来说更容易帮助你吗?
你自己现在能找到问题吗?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 为什么在 while 循环中返回表达式不起作用
- 类和构造函数中的函数根本不起作用,并且不返回任何错误
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- 在 c++ 中返回矢量的指针不起作用
- 当我返回内部时,循环在C 中不起作用
- 尝试使用条件并同时返回,但它不起作用
- 指针不起作用,返回地址不是值
- 为什么 C++ 从推断的返回类型中去除引用限定符,为什么生存期延长不起作用?
- 为什么返回Sfinae转换操作员不起作用
- SetCapture 不起作用并返回 nullptr
- 返回值上的 C++ 方法链接不起作用
- 字符串返回功能不起作用 - 'identifier is underfined'
- lambda函数返回类型不起作用
- 从函数返回字符*不起作用
- 调用函数从类返回私有变量不起作用
- 如果后跟返回 (C++),则 cout 不起作用
- C++:传递和返回指向数组的指针-代码不起作用
- 常量 T * 搜索 ( 常量 T &) 返回不起作用
- C++ 随机不起作用(始终返回相同的值)