0

when I was researching vectors, I noticed that size() is supposed to give the number of elements in the vector, right? So, when I found c++ does not have a string split() function built-in, I decided to make one. The problem is, vector.size() displays the same value as vector.capacity() as shown in the code:

#include <iostream>
#include <algorithm>

using namespace std;

void split(string input, char chr, vector<string> list) {
    string add;
    string conv;
    int size = 0;
    for (int i = 0; i <= input.size(); i++) {
        if ((input[i] != char(chr)) && (input[i] != 0)) {
            conv = input[i];
            add += conv;
        }
        else {
            cout << list.size() << endl;
            if (size <= list.capacity()) {
                list[size] = add;
                add = "";
                size++;
            }
        }
    }
}

int main() {
    vector<string> list(6);
    split("test1,test2", ',', list);
    for (int i = 0; i < 2; i++) {
        cout << list[i] << endl;
    }
}

The output is this:

6
6
<blank line>
<blank line>

whereas it SHOULD be this from my understanding:

1
2
test1
test2

Edit: if this is of any importance, I am compiling with -std=c++11

4

2 回答 2

2

您初始化向量的大小为 6,而不是容量 6。它将在内部使用 6 个空元素构造,因此设置值 0 和 1 不会改变这一点。

您只看到空行的原因是您按值传递向量而不是通过引用拆分函数。

于 2013-08-31T13:38:49.360 回答
0
#include <iostream>
#include <string>
#include <vector>

void split (const std::string& s, char sep, std::vector<std::string>& words)
{
    if (s.empty()) return;
    std::size_t beg = 0;
    std::size_t end = s.find(sep, beg);

    while (end != std::string::npos)
    {
        words.push_back(s.substr(beg, end - beg));
        beg = end + 1;
        end = s.find(sep, beg);
    }
    words.push_back(s.substr(beg));
}

int main() {
    std::vector<std::string> words;
    split("test1,test2", ',', words);
    for (std::size_t i = 0; i != words.size(); ++i) {
        std::cout << words[i] << std::endl;
    }
    return 0;
}
于 2013-08-31T14:03:23.787 回答