没有用于调用“std::vector<std..”的匹配函数

0 c++ string loops vector c++14

我正在解决的问题指出:我必须接受T测试用例。对于每个测试用例,我必须将字符串作为输入,然后我需要将输入字符串排列为:偶数位置的字符串 {double space} 奇数位置的字符串(例如:输入- StackOverflow,输出- Sakvrlw tcOefo)。我编写了以下代码,其中我为所有测试用例获取输入并将其存储在向量中。然后我将 vector 的元素分配给另一个声明的字符串 s。

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
     int T,i;
     cout << "Enter no. of test cases: ";
     cin >> T;

     vector<string> v;
     vector<string> odd;
     vector<string> even;
     string str;

     for(int i=0; i<T; i++){
        cin >> str;
        v.push_back(str);
     }


     string s;

     for(i=0; i<v.size(); i++){
        s = v.at(i);

        for(i=0; i<s.size(); i++){
            if(i==0){
                even.push_back(s[i]);  //*This is where I am getting error*.
            }else if(i==1){
                odd.push_back(s[i]);
            }else{
                if(i%2==0){
                    even.push_back(s[i]);
                }else{
                    odd.push_back(s[i]);
                }
            }
        }

        for(i=0; i<even.size(); i++){
            cout << even.at(i);
        }

        cout << "  ";

        for(i=0; i<odd.size(); i++){
            cout << odd.at(i);
        }

        cout << endl;

        even.clear();
        odd.clear();
        s.clear();
     }


     return 0;
}


Run Code Online (Sandbox Code Playgroud)

在编译上面的代码时,我得到了"no matching error for call std::vector...". 我到底做错了什么?

小智 5

编译代码时出现以下错误:

main.cpp:34:36: error: no matching function for call to ‘std::vector >::push_back(char&)’.

发生这种情况是因为even是 a vector<string>,并且s[i]是 a char。您正在尝试将字符插入到字符串向量中,这是不可能的,因为它们是不同的类型。

如果我正确理解您的问题,even并且odd必须都是vector<char>or stringnot vector<string>

将声明更改为:

string odd;
string even;
Run Code Online (Sandbox Code Playgroud)

这也允许您替换打印:

for(i=0; i<even.size(); i++) {
    cout << even.at(i);
}
Run Code Online (Sandbox Code Playgroud)

和:

cout << even;
Run Code Online (Sandbox Code Playgroud)

  • “*这是不可能的,因为它们是不同的类型*” - 更准确地说,这是不可能的,只是因为 `std::string` 没有接受单个 `char` 作为其唯一输入的构造函数。但是您可以手动构造一个包含单个 char 的 std::string ,然后构造该字符串的 Push_back() ,例如: Even.push_back(string(1, s[i])); 或Even.push_back(字符串(&amp;s[i], 1));` (2认同)