比较std :: vector Sizes时出错

时间:2011-05-03 17:46:12

标签: c++ vector map

使用标准C ++库元素map和vector,我遇到了一些简单代码的奇怪问题。

我有一个图表,表示为map<int, Edgelist>,其中Edgelist被定义为vector<int>。我还有一个match函数,用于比较两个图表,如果true中包含pattern,则会返回subject

代码是一个更大的应用程序的一部分,但是出现此问题的最小编译样本在这里:

#include <vector>
#include <iostream>
#include <map>

typedef int Vertex;
typedef std::vector<Vertex> EdgeList;
typedef std::map<Vertex, EdgeList> PatternGraph;
typedef std::vector<Vertex>::iterator EdgeListIter;
typedef std::map<Vertex, EdgeList>::iterator GraphIter;
const Vertex ROOT = 1;

bool match(PatternGraph &pattern, Vertex p_start,
           PatternGraph &subject, Vertex s_start)
{
  int num_p, num_s;
  num_p = pattern[p_start].size();
  num_s = subject[s_start].size();

  if (pattern[p_start].size() == 0)
    return true;
  if (subject[s_start].size() == 0)
    return false;
  if (pattern[p_start].size() != subject[s_start].size())
    return false;
  if (pattern[p_start].size() == 1) {
    Vertex pattern_child, subject_child;
    pattern_child = pattern[p_start][0];
    subject_child = subject[s_start][0];
    return match(pattern, pattern_child, subject, subject_child);
  } else {
    Vertex p1, p2, s1, s2;
    p1 = pattern[p_start][0];
    p2 = pattern[p_start][1];
    s1 = subject[s_start][0];
    s2 = subject[s_start][1];
    return ((match(pattern, p1, subject, s1) && match(pattern, p2, subject, s2)) ||
        (match(pattern, p2, subject, s1) && match(pattern, p1, subject, s2)));
  }
}

bool test_match()
{
  bool passed = true;
  std::cout << "Running Match Test...";
  PatternGraph p1, p2, p3;
  p1[1] = std::vector<int>(2,3);
  p1[2] = std::vector<int>(4,5);
  p1[3] = std::vector<int>();
  p1[4] = std::vector<int>();
  p1[5] = std::vector<int>();

  p2[1] = std::vector<int>(2,3);
  p2[2] = std::vector<int>(4,5);
  p2[3] = std::vector<int>();
  p2[4] = std::vector<int>();
  p2[5] = std::vector<int>();

  p3[1] = std::vector<int>(2);
  p3[2] = std::vector<int>(3,4);
  p3[3] = std::vector<int>();
  p3[4] = std::vector<int>();

  if (!match(p1, ROOT, p2, ROOT)) {
    std::cout << "P1 Does not Match P2 when it should" << std::endl;
    passed = false;
  } else if (match(p2, ROOT, p3, ROOT)) {
    std::cout << "P2 matches P3 when it shouldn't" << std::endl;
    passed = false;
  } else {
    std::cout << "Match Test Passed." << std::endl;
  }

  return passed;
}

int main(int argc, char *argv[])
{

  test_match();
  return 0;
}

输出为“运行匹配测试... P2不应该匹配P3” 我调试了这段代码,发现由于某些原因,在调用match(p2, ROOT, p3, ROOT)时,p2[1]p3[1]的大小都等于2,{{1 }应该等于p2[1],而2应该等于p3[1]

我很难过,感谢任何帮助。我使用的编译器是Apple的g ++ 4.2.1

1 个答案:

答案 0 :(得分:2)

这将创建一个向量,其中2个元素初始化为0:

p3[1] = std::vector<int>(2);

这会创建一个向量,其中一个元素初始化为2:

p3[1] = std::vector<int>(1, 2);