【问题标题】:C++ Unable to use vector<string> as return typeC++ 无法使用 vector<string> 作为返回类型
【发布时间】:2012-03-09 20:36:33
【问题描述】:

我正在尝试使用建议的函数 here 通过分隔符拆分字符串,但每当我尝试使用 vector&lt;string&gt; 作为返回类型时都会遇到一些错误。

我做了一个简单的函数,它返回一个vector&lt;string&gt; 作为测试,但我仍然得到同样的错误:

// Test.h
#pragma once

#include <vector>
#include <string>

    using namespace std;
using namespace System;

namespace Test
{
    vector<string> TestFunction(string one, string two);
}

.

//Test.cpp
#include "stdafx.h"
#include "Test.h"

namespace Test
{
    vector<string> TestFunction(string one, string two) {
        vector<string> thing(one, two);
        return thing;
    }
}

还有错误截图:

有谁知道为什么我似乎无法使用 vector&lt;string&gt; 作为返回类型?

【问题讨论】:

  • 您的返回类型必须是std::vector&lt;std::string&gt;
  • @e.James stringvector 都在 std 命名空间中,对吧?所以不应该using namespace std; 照顾吗?
  • 旁白:在 .h 文件中包含 using 通常被认为是非常糟糕的做法。尤其是引用命名空间与类型的一种
  • vector&lt;string&gt; thing(one, two); 这不会用两个字符串初始化向量,没有这样的构造函数。
  • @WilHall:是的,我的错。我没有意识到标题中有using 指令。可怕!

标签: c++ string vector return-type


【解决方案1】:

这不是一个有效的vector&lt;string&gt; 构造函数:

vector<string> thing(one, two);

更改为(例如):

std::vector<std::string> TestFunction(std::string one, std::string two) {
    std::vector<std::string> thing;

    thing.push_back(one);
    thing.push_back(two);

    return thing;
}

还可以考虑将参数更改为const std::string&amp;,以避免不必要的复制。

【讨论】:

  • 这似乎已经修复了它,不过,我希望能够根据您的链接使用列表语法,即:vector&lt;string&gt; thing {one, two}; - 但这是失败的,请参阅:@987654322 @
  • 如果您的编译器支持,您需要启用 C++11 功能才能启用该语法。
  • @WilHall 根据this table,只有 gcc 已经支持初始化列表(以及它的 svn 存储库中的 clang++,如果您点击链接)。
  • 我正在使用 Visual Studio 2010 - 虽然这个问题表明不支持初始化列表 D: - stackoverflow.com/questions/5121529/…
【解决方案2】:

问题不在于返回类型,而在于对构造函数的调用。编译器正在选择 std::vector 构造函数:

template <typename InputIterator>
vector( InputIterator b, InputIterator e );

作为最佳候选者,根据标准,将std::string 替换为InputIterator 参数。您的编译器似乎在内部使用特征来验证参数是否确实符合InputIterator 的要求,并抱怨std::string 不满足这些要求。

简单的解决方法是将函数中的代码改为:

std::vector<std::string> v;
v.push_back( one );
v.push_back( two );
return v;

【讨论】:

    【解决方案3】:

    字符串类型实际上是std:: 命名空间的成员。您的函数的正确返回类型将是 std::vector&lt;std::string&gt;

    由于 using namespace std; 行,您可以避免在 CPP 文件中使用 std:: 前缀,但在标题中,您必须包含 std:: 前缀。

    无论您做什么,都不要using namespace std;放在头文件中。

    【讨论】:

      猜你喜欢
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多