简体   繁体   English

如何从向量中找到唯一的单词并将它们放入另一个向量中?

[英]How do I find unique words from vector and put them into another vector?

I have tried making this function, but with no success.我试过制作这个 function,但没有成功。 I am just starting c++ and can not seem to figure this out.我刚开始 c++ 似乎无法弄清楚这一点。

vector<string> findUniqueWords(vector<string> vardi){
    vector<string> unikVardi;
    unikVardi.push_back(vardi[0]);
    for (int i = 1; i < vardi.size(); i++){
        for(int k = 0; k < unikVardi.size(); k++){
            if (vardi[i] != unikVardi[k]){
                unikVardi.push_back(vardi[i]);
            }
        }

     return unikVardi;
    }

}

you must write something like that:你必须写这样的东西:

vector<string> findUniqueWords(vector<string> vardi){
vector<string> unikVardi;
unikVardi.push_back(vardi[0]);
for (int i = 1; i < vardi.size(); i++){
    bool unique = true;
    for(int k = 0; k < unikVardi.size(); k++){
        if (vardi[i] == unikVardi[k]){
           unique  = false;
        }
    }
    if(unique)    unikVardi.push_back(vardi[i]);

}
return unikVardi;

} }

The idea is to push the elements only once if they do not exist in the resultant words list.这个想法是如果元素不存在于结果单词列表中,则仅推送一次元素。 You can use a loop, std::count , std::find , etc. to verify the non-existence of the elements.您可以使用循环、 std::countstd::find等来验证元素的不存在。 Or, you can also use std::unique directly.或者,您也可以直接使用std::unique

With a loop, it would be something like this ( live ):使用循环,它会是这样的( live ):

using Words = std::vector<std::string>;

Words findUniqueWords( const Words& words )
{
    Words uniqueWords;
    uniqueWords.push_back( words[0] );

    for ( int i = 1; i < words.size(); ++i )
    {
        bool isAdded = false;
        for ( int j = 0; j < uniqueWords.size(); ++j )
        {
            if ( words[i] == uniqueWords[j] )
            {
                isAdded = true;
                break;
            }
        }

        if ( !isAdded )
        {
            uniqueWords.push_back( words[i] );
        }
    }

    return uniqueWords;
}

Here's an example with std::count ( live ):这是std::count ( live ) 的示例:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using Words = std::vector<std::string>;

Words findUniqueWords( const Words& words )
{
    Words uniqueWords;
    uniqueWords.push_back( words[0] );

    for ( int i = 1; i < words.size(); ++i )
    {
        if ( std::count( uniqueWords.cbegin(), uniqueWords.cend(), words[i] ) == 0 )
        {
            uniqueWords.push_back( words[i] );
        }
    }

    return uniqueWords;
}

int main()
{
    const Words words { "abc", "xyz", "abc", "xyz", "jkl" };

    const auto result = findUniqueWords( words );
    for ( const auto& word : result )
    {
        std::cout << word << '\n';
    }

    return 0;
}

Output: Output:

abc
xyz
jkl

Also, you need to take care of the case when the input words is an empty list.此外,您需要注意输入words为空列表的情况。

Relevant thread: Why is "using namespace std;"相关线程: 为什么是“使用命名空间标准;” considered bad practice? 被认为是不好的做法?

It should return with one element of unikVardi with the first element of vardi它应该返回一个带有vardi unikVardi

You are pushing the first element with these two lines:您正在使用这两行推送第一个元素:

vector<string> unikVardi;
unikVardi.push_back(vardi[0]);

Now You are comparing with these two vector现在您正在与这两个vector进行比较

 for (int i = 1; i < vardi.size(); i++){

    // unikVardi.size() == 1

     for(int k = 0; k < unikVardi.size(); k++){
        if (vardi[i] != unikVardi[k]){
          unikVardi.push_back(vardi[i]);
     }
 }
 return unikVardi;

After one iteration it will go back to the calling station.经过一次迭代后,它将 go 回到调用站。 :-P :-P

See with main():参见 main():

#include <iostream>
#include <bits/stdc++.h>
#include <string>

using namespace std;

vector<string> findUniqueWords(vector<string> vardi){


    vector<string> unikVardi;
    unikVardi.clear();


    unikVardi.push_back(vardi[0]);


    for (int i = 1; i < vardi.size(); i++) {
        for(int k = 0; k < unikVardi.size(); k++) {

        cout<<vardi[i]<<" Outside:  "<<unikVardi[k]<<endl;
            if (vardi[i] != unikVardi[k]){
                cout<<vardi[i]<<" "<<unikVardi[k]<<endl;
                unikVardi.push_back(vardi[i]);
            }
        }

     return unikVardi;
    }

}

int main()
{
    vector<string> g1, g2;
    string str = "This";

    for (int i = 1; i <= 5; i++)
        g1.push_back(str);

    g2 = findUniqueWords(g1);

    for (int i = 0; i < g2.size(); i++)
        cout<<g2.size()<<endl;
    return 0;
}

It will give you just This because it has only one element.它只会给你This ,因为它只有一个元素。 This element is equeal to vardi[1] second element.该元素等同于vardi[1]第二个元素。 So, it will not go to the if loop.所以,它不会 go 到if循环。 Back to main() with one element.使用一个元素返回main()

I hope you will now understand what is occuring in your function.我希望您现在了解 function 中发生了什么。

The std::unique link actually has an example to do exactly this, using std::sort , std::unique链接实际上有一个例子可以做到这一点,使用std::sort

std::vector<std::string> findUniqueWords(std::vector<std::string> vardi)
{
    std::sort(vardi.begin(), vardi.end());
    vardi.erase(std::unique(vardi.begin(), vardi.end()), vardi.end());
    return vardi;
}

Using the range-v3 library, this becomes even easier,使用range-v3库,这变得更加容易,

std::vector<std::string> findUniqueWords(std::vector<std::string> vardi)
{
    return vardi 
           | ranges::move 
           | ranges::actions::sort 
           | ranges::actions::unique;
}

Smart guys already designed in the standard library all what you may need.聪明人已经在标准库中设计了您可能需要的所有东西。 If you want to successfully study C++ you should read manuals, they often give good examples, std::unique如果你想成功学习 C++ 你应该阅读手册,他们经常给出很好的例子, std::unique

vector<string> findUniqueWords(vector<string> vardi){
    std::sort(vardi.begin(), vardi.end());
    auto last = std::unique(vardi.begin(), vardi.end());
    vardi.erase(last, vardi.end());
    return vardi;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将向量放入y值? - How do I put a vector into y values? 如何将项目放入const向量? - How do I put items into a const vector? 如何将质数放入向量中? - How do I put prime numbers into a vector? 如何使用 RcppArmadillo 在另一个向量中找到向量中元素的索引? - How do I find the indices of elements in a vector which are also in another vector using RcppArmadillo? 你如何从文件中读取 n 个字节并将它们放入向量中<uint8_t>使用迭代器? - How do you read n bytes from a file and put them into a vector<uint8_t> using iterators? 如何跳过字符串流中的空格和换行符并将它们放入向量中? - How to skip the space and the new line from stringstream and put them in a vector? 如何有效地将唯一对象从一个矢量复制到另一个矢量(由相同对象的子集组成)? - How do I efficiently copy unique objects from one vector to another (which is made up of a subset of identical objects)? 从文件中提取单词并将它们放入 `std::array 的`std::vector`<string,4> `</string,4> - Extract words from a file and put them into a `std::vector` of `std::array<string,4>` 如何正确地从向量的一部分中找到一个值? - How do I correctly find a value from part of a vector? 如何针对另一个向量对向量进行排序? - How do I sort a vector with respect to another vector?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM