gpt4 book ai didi

c++ - std::map::begin() 返回一个带垃圾的迭代器

转载 作者:行者123 更新时间:2023-11-30 04:11:20 25 4
gpt4 key购买 nike

typedef unsigned long Count;
typedef float Weight;
typedef std::map<std::string, Count> StringToCountMap;
typedef std::map<std::string, Weight> StringToWeightMap;
typedef std::map<unsigned long, StringToCountMap> UnsignedToStringToCountMap;
typedef std::map<unsigned long, StringToWeightMap> UnsignedToStringToWeightMap;

typedef std::map<unsigned long, std::size_t> ClustersMap;


class DefaultClusteringAlgorithm
{
public:
// minumum number of documents changing clusters for algorithm to end
static const unsigned DocumentChangeThreshold = 0;

DefaultClusteringAlgorithm(unsigned numClusters, const UnsignedToStringToWeightMap &documentVectors)
: numClusters_(numClusters)
, documentVectors_(documentVectors)
{
}

~DefaultClusteringAlgorithm() {}

const ClustersMap &DoClustering();

private:
void ChooseInitialCentroids();
unsigned ClusterOnCentroids();
void RecalculateCentroids();
float DocumentDotProduct(const StringToWeightMap &left, const StringToWeightMap &right);
float DocumentLength(const StringToWeightMap &document);

unsigned numClusters_;

// stores cluster_id => centroid
std::vector<StringToWeightMap> centroids_;

// maps question id => cluster id
ClustersMap clusters_;

// document vector
const UnsignedToStringToWeightMap &documentVectors_;
};

void DefaultClusteringAlgorithm::RecalculateCentroids()
{
std::vector<unsigned> newCentroidsSizes(centroids_.size());
std::vector<StringToWeightMap> newCentroids(centroids_.size());

ClustersMap::const_iterator clusterMapping = clusters_.begin();

for (; clusterMapping != clusters_.end(); ++clusterMapping)
{
std::size_t clusterId = clusterMapping->second;

++newCentroidsSizes[clusterId];
const StringToWeightMap &document = documentVectors_.at(clusterMapping->first);

StringToWeightMap::const_iterator termWeight = document.cbegin();

for (; termWeight != document.end(); ++termWeight);
{
newCentroids[clusterId][termWeight->first] += termWeight->second;
}
}

std::vector<unsigned>::iterator centroidSize = newCentroidsSizes.begin();

for (; centroidSize != newCentroidsSizes.end(); ++centroidSize)
{
std::size_t clusterId = centroidSize - newCentroidsSizes.begin();

StringToWeightMap::iterator centroidTermWeight = newCentroids[clusterId].begin();

for (; centroidTermWeight != newCentroids[clusterId].end(); ++centroidTermWeight)
{
centroidTermWeight->second /= *centroidSize;
}
}
}

debugger watch

问题出现在创建const_iterator termWeight:

StringToWeightMap::const_iterator termWeight = document.begin();

如您在上图中所见,termWeight const_iterator 包含无效数据。然而,const std::map 文档是一个完全有效的 std::map。我想不出发生这种情况的任何原因。

我最近了解到 std::map::cbegin() 存在。我应该改用那个方法吗?

编辑:包含更多上下文

最佳答案

哈!我发现了错误!我的 for 循环末尾有一个愚蠢的小分号!

关于c++ - std::map::begin() 返回一个带垃圾的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20278080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com