C++ 函数返回类型是C++中的向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7196264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:35:18  来源:igfitidea点击:

function return type is vector in c++

c++functionvector

提问by yogesh patel

i want vector as return type of function in my code like,

我想要向量作为我的代码中函数的返回类型,例如,

class SocketTransportClient{
    void sendData(RMLInfoset *info){
        vector<unsigned long>::iterator blockIterator;
        vector<unsigned long> vectBlock=info->getRML(); // error :  error C2440: 'initializing' : cannot convert from 'std::vector<_Ty>' to 'std::vector<_Ty>'
    }
}

class RMLInfoset  {
    vector<unsigned int> RMLInfoset::getRML(){
        return  vectDataBlock;
    }
}

but it show an error 'cannot convert from 'std::vector<_Ty>' to 'std::vector<_Ty>' ' so please any one help me, Thanks.

但它显示错误“无法从 'std::vector<_Ty>' 转换为 'std::vector<_Ty>' ' 所以请任何人帮助我,谢谢。

回答by Greg Hewgill

Your function is declared to return vector<unsigned int>but you're actuallytrying to assign the result to a vector<unsigned long>. Those are different types and not assignment-compatible. Change your function declaration:

您的函数被声明为返回,vector<unsigned int>但您实际上是在尝试将结果分配给vector<unsigned long>. 这些是不同的类型,并且不兼容分配。更改您的函数声明:

  vector<unsigned long> RMLInfoset::getRML(){

You will also need to change the type of vectDataBlock. Basically, decide which vector type you want to use and be consistent.

您还需要更改vectDataBlock. 基本上,决定要使用的向量类型并保持一致

回答by James

Well, part of the problem is that you never actually build the vector vin Myfun.

好吧,部分问题在于您从未真正构建过vector vin Myfun.

std::vector<int> Myfun() {
  std::vector<int> v;
  return v;
}

EDIT:

编辑:

After the question edit, there is still a small problem - you need to declare the vector as a std::vector<int>, not just a vector<int>, as above. This is because vector resides in the stdnamespace.

在问题编辑之后,还有一个小问题——你需要将向量声明为 a std::vector<int>,而不仅仅是 a vector<int>,如上所述。这是因为 vector 驻留在std命名空间中。

回答by john

You have three errors

你有三个错误

1) You didn't use #include <vector>

1)你没有使用 #include <vector>

2) It should be std::vector<int> v;instead of vector<int> v;

2)它应该std::vector<int> v;代替vector<int> v;

3) You didn't post all of your code.

3)您没有发布所有代码。