如何将字符复制到字符串向量

时间:2019-07-30 20:48:00

标签: c++11 std stdvector

尝试多次从解决方案中将字符向量复制到字符串向量均未成功

在复制之前为向量分配内存,将std :: copy放置在“ OutputIterator结果”(基于函数模板)时可以正常工作。我尝试过:

std :: copy(char1.begin(),char1.end(),v1.begin());

但是,这也不成功。使用back_inserter返回错误c2679“二进制'=':未找到采用'char'类型的右侧操作数的运算符(或没有可接受的转换)。

输入文件位于此处:https://adventofcode.com/2018/day/2

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstring>
#include <algorithm>
#include <iterator>
#include <cstdio>



    int main() {

        std::string field1;
        std::string field2;
        char characters;

        std::vector<char>::iterator ptr;
        std::vector<char>::iterator ptr2;

        std::vector<char> char1;
        std::vector<char> char2;

        int size = 0;

        std::ifstream inFile;

        inFile.open("C:\\Users\\Administrator\\Desktop\\c++ files\\input2.txt");

        if (!inFile) {

            std::cout << "abort";

            return 1;

        }

        while (inFile >> characters) {          //read variables from input stream

            char1.push_back(characters);

        }

        std::vector<std::string> v1(6500);

        std::copy(char1.begin(), char1.end(), std::back_inserter(v1)); 

        inFile.close();

        return 0;

    }

    //26

期望向量v1将值保留在向量char1中。我假设问题源于v1和char1的数据类型,但是,我还没有找到具体的解决方案。我不想直接读入字符串向量。因此是我目前的问题。

1 个答案:

答案 0 :(得分:0)

我不确定您要达到什么目标。这里有几个例子:

#include <string>
#include <vector>

int main()
{
    std::string str1{ "Just for an example" }; // You can read it from a file
    int i;

    // **** A. Copy from std::string to std::vector<char>: ****
    i = 0;
    std::vector<char> vct_ch;
    vct_ch.resize(str1.length());
    for (auto & item : vct_ch) // '&' is to get the reference
        item = str1[i++];

    // **** B. Copy from std::vector<char> to std::string: ****
    i = 0;
    std::string str2;
    str2.resize(vct_ch.size());
    for (auto item : vct_ch)
        str2[i++] = item;

    // **** C. Copy from std::vector<char> to std::vector<std::string>: ****
    i = 0;
    std::vector<std::string> vct_str1(32); // Lets say it has 32 std::string items
    vct_str1[0].resize(vct_ch.size()); // and we copy to the first std::string
    for (auto item : vct_ch)
        vct_str1[0][i++] = item;

    // **** D. Source & Dest. Type same as in C. But char per std::string: ****
    i = 0;
    std::vector<std::string> vct_str2(32); // Lets say it has 32 std::string items
    for (auto item : vct_ch) {
        vct_str2[i].resize(1);
        vct_str2[i++][0] = item;
    }

    return 0;
}