C++ Unable to use vector<string> as return type

16,662

Solution 1

This is not a valid vector<string> constructor:

vector<string> thing(one, two);

Change to (for example):

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;
}

Also consider changing parameters to be const std::string& to avoid unnecessary copy.

Solution 2

The problem is not with the return type but with the call to the constructor. The compiler is picking the std::vector constructor:

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

as the best candidate, which it is according to the standard, by substituting std::string as the InputIterator parameter. Your compiler seems to be using traits internally to verify that the argument actually complies with the requirements of InputIterator and complaining because std::string does not fulfill those requirements.

The simple solution is to change the code in the function to:

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

Solution 3

the string type is actually a member of the std:: namespace. The proper return type for your function will be std::vector<std::string>.

You are able to avoid using the std:: prefix in your CPP file because of the line using namespace std;, but in your header, you must include the std:: prefix.

Whatever you do, do not place the using namespace std; in the header file.

Share:
16,662
WilHall
Author by

WilHall

I'm a software engineer. My favorite language is Python.

Updated on June 14, 2022

Comments

  • WilHall
    WilHall almost 2 years

    I am trying to use the functions suggested here to split a string by a deliminator, but I am getting a handful of errors whenever I try to use vector<string> as a return type.

    I made a simple function that returns a vector<string> as a test, but am still getting the same errors:

    // 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;
        }
    }
    

    And a screenshot of the errors: Errors

    Does anyone know why I seem to be unable to use vector<string> as a return type?