简体   繁体   English

传递矢量 <vector<int> &gt;争论

[英]Passing a vector<vector<int> > to an argument

I'm new in C++ programming and for some time, I've been trying to resolve a problem with a vector<vector<int> > . 我是C ++编程的新手,并且一段时间以来,我一直在尝试解决vector<vector<int> >

This is the header file 这是头文件

#ifndef ASSIGNMENT_H_
#define ASSIGNMENT_H_

#include <iostream>
#include <vector>
#include <string>

using std::string;
using std::vector;
using namespace std;

class Mood{
public:
   string lecture;
   vector<Block> blocks;

   Mood(vector<vector<int> > &m, string lecture){
     this->lecture=lecture;
     for(auto r: m){
        blocks.push_back(Block(r));
     }
  }
};
#endif

Block is another simple class with just 2 int written in the same file (but I think it not important for my problem). Block是另一个简单的类,在同一文件中只写了2个int(但我认为这对我的问题并不重要)。

The problem is in the main written in another file: 问题出在主要写在另一个文件中:

#include <iostream>
#include <vector>
#include <string>
#include "assignment.h"
using std::vector;
using std::string;
using namespace std;
int main(){
   Mood r= Mood({{1,2}},"Hello");
}

The error is very general: expected expression 错误非常笼统:期望表达式

Either you have stripped some important parts of the error message, or your compiler is exceptionally uncommunicative. 您可能已经删除了错误消息的一些重要部分,或者您的编译器异常无法通信。

The handling of initializer lists is still sometimes a bit - erm - suboptimal. 初始化列表的处理有时仍然是-erm-次优。 Please try this: 请尝试以下方法:

auto main() -> int {
   auto r = Mood({vector<int>{1,2}}, "Hello");
}

Update 更新资料

In the comments we have found, that you use C++11 initialization syntax, but don't have C++11 support activated. 在我们发现的注释中,您使用C ++ 11初始化语法,但未激活C ++ 11支持。 Either activate C++11, or resort to the old approach to initialize vectors: 要么激活C ++ 11,要么采用旧的方法初始化矢量:

vector<vector<int> > m;
vector<int> m0;
m.push_back(m0);
m[0].push_back(1);
m[0].push_back(2);
Mood r = Mood(m, "Hello");

Try defining the argument m in the constructor as const, eg: 尝试在构造函数中将参数m定义为const,例如:

Mood(const vector<vector<int> > &m, string lecture)

This will allow you to pass in an R-Value (ie {{2,3}} ) 这将允许您传递R值(即{{2,3}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM