简体   繁体   中英

Copying only the letters in a vector to another vector in C++

I need to find only the letters in a 2-dimensional vector and copy them to a one dimensional vector. For example, the vector could contain:

3    4    5
A    B 
A    C
A    B
B    C
1    C    3

Then, the new vector would contain:

A    B   C

The letters shouldn't be repeated. This is part of a bigger project and I'm stuck in this part.

You can keep track of which letters you've seen using an array:

bool seen[26] = { false };
for (const auto& v : v2d)
    for (const auto& c : v)
        if ('A' <= c && c <= 'Z')
            seen[c - 'A'] = true;
std::string result;
for (char c = 'A'; c <= 'Z'; ++c)
    if (seen[c - 'A']) result += c;

You use wrong container for Letters. Change your vector on set and you will get right behavior:

std::set<string> Letters;

So I had these two vectors:

vector<vector<string>> gateInputs; //2D vector with data
vector<string> Letters; // Vector where I'll store only the letters

I was told to use isalpha , but it only works with char and my vector is of type string , so I used the following function:

bool all_alpha(const std::string& str)
{
    for (std::size_t i = 0; i < str.size(); ++i)
    if (!std::isalpha(str[i])) return false;
}

Then I called that function to store only the letters in my vector Letters :

for (int i = 0; i <gateInputs.size(); i++)
    {
    for (int j = 0; j<gateInputs[i].size(); j++)
    {
        if (all_alpha(gateInputs[i][j]))
        {
            string m = gateInputs[i][j];
            Letters.push_back(m);
        }
    }
}

And it worked. Now the vector Letters contains the following:

A   B  A  C  A  B  B  C  C

Then I just had to sort the vector and delete the duplicates:

// Sort letters in vector
sort(Letters.begin(), Letters.end());
// Erase duplicates
Letters.erase(unique(Letters.begin(), Letters.end()), Letters.end());

And done! The array now contains:

A    B    C

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM