从地图中获取价值的最佳实践是什么?

what is the best practice of get value from a map?

我对函数有点迷惑return,我的目的是尽量避免复制

我读了一些文档,它告诉我不要使用引用作为地图的值。

但是在下面的代码中,我很疑惑

struct BigCls {
  // this struct has a expensive constructor
  BigCls(...);
};

// solution 1
void create_function() {
  std::map<int, BigCls> m;
  m[1] = BigCls(...);
  m[2] = BigCls(...);
  ...
}

BigCls get(int a) {
  return m.at(a);
}

// solution 2
void create_function() {
  std::map<int, BigCls*> m;
  m[1] = new BigCls(...);
  m[2] = new BigCls(...);
  ...
}

BigCls* get(int a) {
  return m.at(a);
}

// solution 3
void create_function() {
  std::map<int, BigCls&> m;  // i think if map's value is reference, then the cls should be static
  // or it will fail, am i right?
  static BigCls cls(...);
  m[1] = cls;
  ...
}    
BigCls& get(int a) {
  return m.at(a);
}

哪个最快?你认为哪一个是最好的?

您无需在地图中存储引用即可获得对地图中值的引用。这里:

std::map<int,BigCls> m;

BigCls& get(int a) {
  return m.at(a);
}

您正在 return引用地图中的值。像这样调用就没有副本了:

BigCls& x = get(42);

在映射中存储指针不必要地复杂,除非您确实需要那种间接级别(例如,当 BigCls 是多态类型时)。


which one is the fastest? and which one you think is the best one?

这听起来像是过早的优化。根据您是否需要副本或参考,选择 return 副本或参考。它暗示了函数的不同语义。担心性能是因为当您拥有正确的代码并且通过分析和测量您发现它需要改进时。

std::map<Key,T,Compare,Allocator>::at

T& at( const Key& key ); (1) (since C++11)
const T& at( const Key& key) const; (2) (since C++11)

Returns a reference to the mapped value of the element with key equivalent to key. If no such element exists, an exception of type std::out_of_range is thrown.

(cppreference)

std::map::at return 是一个元素引用,因此没有复制行为(除非您将其 return 值分配给非引用变量)。

问题中的代码有问题,m变量不应该在函数内部。

除此问题外,将解决方案 1 中 get 函数的 return 类型从 BigCls 更改为 BigCls & 将是最佳解决方案。

struct BigCls {
  BigCls(...);

  int v1, v2;
};


std::map<int, BigCls> m;

void create_function() {
  m[1] = BigCls(...);
  m[2] = BigCls(...);
  ...
}

BigCls& get(int a) {
  return m.at(a);
}

void examples()
{
  int v1 = get(1).v1;

  BigCls &bigCls2 = get(2);
  int v2 = bigCls2.v2;
}